Sunday 31 March 2013

Add Dynamic Data in Listview With SimpleAdapter and BaseAdapter in Android

NewMainClass.java


public class NewMainClass extends Activity
{
Button mButton;
ListView mListView;

public static BaseAdapter mAdapter;
public ArrayList<GetProductDetail>temp_GetProductDetails;
GetProductDetail mProductDetail;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newmain);
mButton=(Button)findViewById(R.id.btn);
mListView=(ListView)findViewById(R.id.list);
mAdapter=new baseAdapter(NewSecondActivity.mGetProductDetails);
   mListView.setAdapter(mAdapter);

   mButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent mIntent=new Intent(getApplicationContext(), NewSecondActivity.class);
startActivity(mIntent);
}
});
     
   mListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        Toast.makeText(NewMainClass.this, "You have chosen: " + " " + position, Toast.LENGTH_LONG).show();
        }
        });
 
}

@Override
protected void onResume() {
super.onResume();
System.out.println("Class Size "+NewSecondActivity.mGetProductDetails.size());
for (int i = 0; i <NewSecondActivity.mGetProductDetails.size(); i++)
{
String s=NewSecondActivity.mGetProductDetails.get(i).getPrice();
System.out.println("Price "+s);

}
}

public class baseAdapter extends BaseAdapter
{
ViewHolder holder ;

public baseAdapter(ArrayList<GetProductDetail> mGetProductDetails)
{
temp_GetProductDetails=mGetProductDetails;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return temp_GetProductDetails.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
mProductDetail = temp_GetProductDetails.get(position);

holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newrow, null);
holder.mTextViewAmount=(TextView)convertView.findViewById(R.id.amount);
holder.mTextViewPrice=(TextView)convertView.findViewById(R.id.rate);
holder.mTextViewProduct=(TextView)convertView.findViewById(R.id.productname);
holder.mTextViewQty=(TextView)convertView.findViewById(R.id.qty);

holder.mTextViewAmount.setText(mProductDetail.getAmount());
holder.mTextViewPrice.setText(mProductDetail.getPrice());
holder.mTextViewProduct.setText(mProductDetail.getProduct());
holder.mTextViewQty.setText(mProductDetail.getQty());

return convertView;
}

}

public class ViewHolder
{
TextView mTextViewProduct;
TextView mTextViewPrice;
TextView mTextViewQty;
TextView mTextViewAmount;
}
 
}


NewSecondActivity.java

public class NewSecondActivity extends Activity{

EditText mEditTextProductName;
EditText mEditTextQty;
EditText mEditTextPrice;
EditText mEditTextAmount;
Button mButtonSend;
public static ArrayList<GetProductDetail>mGetProductDetails=new ArrayList<GetProductDetail>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
mEditTextProductName=(EditText)findViewById(R.id.editText1);
mEditTextQty=(EditText)findViewById(R.id.editText2);
mEditTextPrice=(EditText)findViewById(R.id.editText3);
mEditTextAmount=(EditText)findViewById(R.id.editText4);

mButtonSend=(Button)findViewById(R.id.button1);
mButtonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GetProductDetail mProductDetail=new GetProductDetail();
mProductDetail.product=mEditTextProductName.getText().toString();
mProductDetail.qty=mEditTextQty.getText().toString();
mProductDetail.price=mEditTextPrice.getText().toString();
mProductDetail.amount=mEditTextAmount.getText().toString();
mGetProductDetails.add(mProductDetail);

NewMainClass.mAdapter.notifyDataSetChanged();
finish();
}
});
}

}

GetProductDetail.java

public class GetProductDetail {

String product="";
String qty="";
String price="";
String amount="";
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}


Click below link  for download project.
https://sites.google.com/site/nepstareblogspotin/http-nepstare-blogspot-in/DemoArraylist.rar?attredirects=0&d=1

Searching Text in Listview


TextswitcherdemoActivity.java


public class TextswitcherdemoActivity extends Activity {

 ArrayAdapter<String> dataAdapter = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  //Generate list View from ArrayList
  displayListView();

 }

 private void displayListView() {

  //Array list of countries
  List<String> countryList = new ArrayList<String>();
  countryList.add("Aruba");
  countryList.add("Anguilla");
  countryList.add("Netherlands Antilles");
  countryList.add("Antigua and Barbuda");
  countryList.add("Bahamas");
  countryList.add("Belize");
  countryList.add("Bermuda");
  countryList.add("Barbados");
  countryList.add("Canada");
  countryList.add("Costa Rica");
  countryList.add("Cuba");
  countryList.add("Cayman Islands");
  countryList.add("Dominica");
  countryList.add("Dominican Republic");
  countryList.add("Guadeloupe");
  countryList.add("Grenada");
  countryList.add("Greenland");
  countryList.add("Guatemala");
  countryList.add("Honduras");
  countryList.add("Haiti");
  countryList.add("Jamaica");

  //create an ArrayAdaptar from the String Array
  dataAdapter = new ArrayAdapter<String>(this,
    R.layout.country_list, countryList);
  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);

  //enables filtering for the contents of the given ListView
  listView.setTextFilterEnabled(true);

  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    // When clicked, show a toast with the TextView text
    Toast.makeText(getApplicationContext(),
     ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
   }
  });

  EditText myFilter = (EditText) findViewById(R.id.myFilter);
  myFilter.addTextChangedListener(new TextWatcher() {

  public void afterTextChanged(Editable s) {
  }

  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  }

  public void onTextChanged(CharSequence s, int start, int before, int count) {
   dataAdapter.getFilter().filter(s.toString());
  }
  });
 }  
}


Click below link for download project
https://sites.google.com/site/httpnepstareblogspotin/http-nepstare-blogspot-in/Textswitcherdemo.rar?attredirects=0&d=1

Friday 1 March 2013

Listview with Checkbox

PlanetsActivity .java

public class PlanetsActivity extends Activity {
 
  private ListView mainListView ;
  private Planet[] planets ;
  private ArrayAdapter<Planet> listAdapter ;
 
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   
    // Find the ListView resource.
    mainListView = (ListView) findViewById( R.id.mainListView );
   
    // When item is tapped, toggle checked properties of CheckBox and Planet.
    mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick( AdapterView<?> parent, View item,
                               int position, long id) {
        Planet planet = listAdapter.getItem( position );
        planet.toggleChecked();
        PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
        viewHolder.getCheckBox().setChecked( planet.isChecked() );
      }
    });

   
    // Create and populate planets.
    planets = (Planet[]) getLastNonConfigurationInstance() ;
    if ( planets == null ) {
      planets = new Planet[] {
          new Planet("Mercury"), new Planet("Venus"), new Planet("Earth"),
          new Planet("Mars"), new Planet("Jupiter"), new Planet("Saturn"),
          new Planet("Uranus"), new Planet("Neptune"), new Planet("Ceres"),
          new Planet("Pluto"), new Planet("Haumea"), new Planet("Makemake"),
          new Planet("Eris")
      };
    }
    ArrayList<Planet> planetList = new ArrayList<Planet>();
    planetList.addAll( Arrays.asList(planets) );
   
    // Set our custom array adapter as the ListView's adapter.
    listAdapter = new PlanetArrayAdapter(this, planetList);
    mainListView.setAdapter( listAdapter );    
  }
 
  /** Holds planet data. */
  private static class Planet {
    private String name = "" ;
    private boolean checked = false ;
    public Planet() {}
    public Planet( String name ) {
      this.name = name ;
    }
    public Planet( String name, boolean checked ) {
      this.name = name ;
      this.checked = checked ;
    }
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
    public boolean isChecked() {
      return checked;
    }
    public void setChecked(boolean checked) {
      this.checked = checked;
    }
    public String toString() {
      return name ;
    }
    public void toggleChecked() {
      checked = !checked ;
    }
  }
 
  /** Holds child views for one row. */
  private static class PlanetViewHolder {
    private CheckBox checkBox ;
    private TextView textView ;
    public PlanetViewHolder() {}
    public PlanetViewHolder( TextView textView, CheckBox checkBox ) {
      this.checkBox = checkBox ;
      this.textView = textView ;
    }
    public CheckBox getCheckBox() {
      return checkBox;
    }
    public void setCheckBox(CheckBox checkBox) {
      this.checkBox = checkBox;
    }
    public TextView getTextView() {
      return textView;
    }
    public void setTextView(TextView textView) {
      this.textView = textView;
    }  
  }
 
  /** Custom adapter for displaying an array of Planet objects. */
  private static class PlanetArrayAdapter extends ArrayAdapter<Planet> {
   
    private LayoutInflater inflater;
   
    public PlanetArrayAdapter( Context context, List<Planet> planetList ) {
      super( context, R.layout.simplerow, R.id.rowTextView, planetList );
      // Cache the LayoutInflate to avoid asking for a new one each time.
      inflater = LayoutInflater.from(context) ;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      // Planet to display
      Planet planet = (Planet) this.getItem( position );

      // The child views in each row.
      CheckBox checkBox ;
      TextView textView ;
     
      // Create a new row view
      if ( convertView == null ) {
        convertView = inflater.inflate(R.layout.simplerow, null);
       
        // Find the child views.
        textView = (TextView) convertView.findViewById( R.id.rowTextView );
        checkBox = (CheckBox) convertView.findViewById( R.id.CheckBox01 );
       
        // Optimization: Tag the row with it's child views, so we don't have to
        // call findViewById() later when we reuse the row.
        convertView.setTag( new PlanetViewHolder(textView,checkBox) );

        // If CheckBox is toggled, update the planet it is tagged with.
        checkBox.setOnClickListener( new View.OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) v ;
            Planet planet = (Planet) cb.getTag();
            planet.setChecked( cb.isChecked() );
          }
        });      
      }
      // Reuse existing row view
      else {
        // Because we use a ViewHolder, we avoid having to call findViewById().
        PlanetViewHolder viewHolder = (PlanetViewHolder) convertView.getTag();
        checkBox = viewHolder.getCheckBox() ;
        textView = viewHolder.getTextView() ;
      }

      // Tag the CheckBox with the Planet it is displaying, so that we can
      // access the planet in onClick() when the CheckBox is toggled.
      checkBox.setTag( planet );
     
      // Display planet data
      checkBox.setChecked( planet.isChecked() );
      textView.setText( planet.getName() );    
     
      return convertView;
    }
   
  }
 
  public Object onRetainNonConfigurationInstance() {
    return planets ;
  }
}


Click below link for download project
https://sites.google.com/site/httpnepstareblogspotin/listview-with-checkbox/Planets.zip?attredirects=0&d=1