I just want to get the value of clicked list item,
i.e if list contains apple,ball,cat, then clicked on apple then it gives value as apple, ,In the below code I am using inner class base adapter to display the data.
public class RecordsActivity extends Activity implements
OnItemClickListener
{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
ArrayList<String> billDate = new ArrayList<String>();
ArrayList<String> billNo = new ArrayList<String>();
ArrayList<String >partyName=new ArrayList<String>();
ArrayList<String> billAmount = new ArrayList<String>();
ArrayList<String >receipt=new ArrayList<String>();
ArrayList<String >balance=new ArrayList<String>();
ArrayList<String> week = new ArrayList<String>();
ArrayList<String> amount = new ArrayList<String>();
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
/*listProduct.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
listProduct.setClickable(true);
String data = (String)listProduct.getItemAtPosition(arg2);
Toast.makeText(getApplicationContext(),data,
Toast.LENGTH_SHORT).show();
}
});*/
}
protected void onResume()
{
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name +
"' ", null);
String
BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst())
{
do
{
BILL_DATE = c.getString(1);
BILL_NO=c.getString(2);
PARTY_NAME=c.getString(3);
BILL_AMOUNT=c.getString(4);
RECEIPT=c.getString(5);
BALANCE=c.getString(6);
WEEK=c.getString(7);
AMOUNT=c.getString(8);
billDate.add(BILL_DATE);
billNo.add(BILL_NO);
partyName.add(PARTY_NAME);
billAmount.add(BILL_AMOUNT);
receipt.add("RECEIPT");
balance.add(BALANCE);
week.add(WEEK);
amount.add(AMOUNT);
} while (c.moveToNext());
}
DisplyRecords dsptProd=new
DisplyRecords(RecordsActivity.this,billDate,billNo,partyName,
billAmount,receipt,balance,week,amount);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB()
{
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
class DisplyRecords extends BaseAdapter
{
Context c;
ArrayList<String > BILLDATE;
ArrayList<String>BILLNO;
ArrayList<String> PARTYNAME;
ArrayList<String>BILLAMOUNT;
ArrayList<String>RECEIPT;
ArrayList<String> BALANCE;
ArrayList<String>WEEK;
ArrayList<String>AMOUNT;
public DisplyRecords(RecordsActivity recordsactivity,ArrayList<String>
billDate, ArrayList<String> billNo, ArrayList<String>
partyName,ArrayList<String> billAmount, ArrayList<String> receipt,
ArrayList<String> balance, ArrayList<String> week,ArrayList<String> amount)
{
this.c=recordsactivity;
this.BILLDATE=billDate;
this.BILLNO=billNo;
this.PARTYNAME=partyName;
this.BILLAMOUNT=billAmount;
this.RECEIPT=receipt;
this.BALANCE=balance;
this.WEEK=week;
this.AMOUNT=amount;
//TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return BILLDATE.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int pos, View row, ViewGroup parent)
{
View child=row;
LayoutInflater layoutinflater;
if(child==null)
{
layoutinflater=(LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView)
child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView)
child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
txt_billdate.setText(BILLDATE.get(pos));
txt_billno.setText(BILLNO.get(pos));
txt_partyname.setText(PARTYNAME.get(pos));
txt_billamt.setText(BILLAMOUNT.get(pos));
txt_receipt.setText(RECEIPT.get(pos));
txt_balance.setText(BALANCE.get(pos));
txt_wk.setText(WEEK.get(pos));
txt_amount.setText(AMOUNT.get(pos));
// TODO Auto-generated method stub
return child;
}
}
A few assumptions here, your actual fields do not need to be ArrayList's since each query returns a single row item from the db, i create a master object with Strings to represent the data...
So here is how i would do it, you need to re structure your data
First i would change your data to a :
public class ParentObject {
public String BILLDATE ;
public String BILLNO ;
public String PARTYNAME ;
public String BILLAMOUNT ;
public String RECEIPT ;
public String BALANCE ;
public String WEEK ;
public String AMOUNT ;
}
UPDATE
then i would change my Activity to:
public class RecordsActivity extends Activity implements OnItemClickListener{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
// your new parent object ArrayList, much cleaner
List<ParentObject> parentObjects;
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(this);
}
protected void onResume(){
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name + "' ", null);
String BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst()){
// initialize the parent arrayList
parentObjects = new ArrayList<ParentObject>();
do{
// initialize a single object
ParentObject parentObject = new ParentObject();
// fill in its data
parentObject.BILL_DATE = c.getString(1);
parentObject.BILL_NO=c.getString(2);
parentObject.PARTY_NAME=c.getString(3);
parentObject.BILL_AMOUNT=c.getString(4);
parentObject.RECEIPT=c.getString(5);
parentObject.BALANCE=c.getString(6);
parentObject.WEEK=c.getString(7);
parentObject.AMOUNT=c.getString(8);
// add it to your list
parentObjects.add(parentObject);
} while (c.moveToNext());
}
// pass the List<ParentObject> into your adapter
DisplyRecords dsptProd= new DisplyRecords(RecordsActivity.this, (ArrayList<ParentObject>)parentObjects);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB(){
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// access to all your data through the parentObject
ParentObject data = (ParentObject) listProduct.getItemAtPosition(position);
// access all fields for this parent
Toast.makeText(RecordsActivity.this, "data: "+ data.BILL_DATE, + " ," + data.BILL_NO, " , etc", Toast.LENGTH_LONG).show();
}
}
and then update your Adapter to handle the List
class DisplyRecords extends BaseAdapter {
Context c;
List<ParentObject> parentObjects;
public DisplyRecords(Context context, ArrayList<ParentObject> parentObjects){
this.c=context;
this.parentObjects = parentObjects;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return parentObjects.size();
}
#Override
public Object getItem(int position) {
return parentObjects.get(position); // always return this parent
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int pos, View row, ViewGroup parent){
// You should implement the ViewHolder pattern, this is not doing that...
View child=row;
LayoutInflater layoutinflater;
if(child==null){
layoutinflater=(LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView) child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView) child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
ParentObject parentObject = parentObjects.get(pos);
txt_billdate.setText(parentObject.BILLDATE);
txt_billno.setText(parentObject.BILLNO.);
txt_partyname.setText(parentObject.PARTYNAME);
txt_billamt.setText(parentObject.BILLAMOUNT);
txt_receipt.setText(parentObject.RECEIPT);
txt_balance.setText(parentObject.BALANCE);
txt_wk.setText(parentObject.WEEK);
txt_amount.setText(parentObject.AMOUNT);
// TODO Auto-generated method stub
return child;
}
}
Related
When I am trying to set value to the list view using custom adapter it shows only the last entered value in the hash map. hash map is static.I dont know why I am not getting all the values in the hashmap for that keys I am used in hashmap.
here my code
public class Nextclass extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextclass);
list = (ListView)findViewById(R.id.list1);
SelectItems();
ViewItems();
}
private List<Map<String, String>> SelectItems() {
// TODO Auto-generated method stub
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct code ,desc ,name "
+ " from item", null);
while (c.moveToNext()){
String cod = c.getString(c.getColumnIndex("code"));
datanums.put("code", cod);
String desc1 = c.getString(c.getColumnIndex("desc"));
datanums.put("desc", desc1);
String name = c.getString(c.getColumnIndex("name"));
datanums.put("name", name);
datas.add(datanums);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
return datas;
}
private void ViewItems() {
// TODO Auto-generated method stub
arrTemp = new String[datas.size()];
MyListAdapter myListAdapter = new MyListAdapter();
list.setAdapter(myListAdapter);
Log.v("list itemm",datas.toString());
}
public class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(datas != null && datas.size() != 0){
return datas.size();
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datas.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = Orders.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.order_simple_row, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.name);
holder.textView2 = (TextView) convertView.findViewById(R.id.code);
holder.textview3 = (TextView) convertView.findViewById(R.id.desc);
holder.editText1 = (EditText) convertView.findViewById(R.id.cases);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(datanums.get("name"));
holder.textview3.setText(datanums.get("code"));
holder.textView2.setText(datanums.get("desc"));
holder.editText1.setText(arrTemp[position]);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
arrTemp[holder.ref] = arg0.toString();
}
});
return convertView;
}
private class ViewHolder {
public Object list;
TextView textView1,textView2,textview3;
EditText editText1,editText2;
int ref;
}
return convertView;
}
private class ViewHolder {
public Object list;
TextView textView1,textView2,textview3;
EditText editText1;
int ref;
}
please help.I used alternate methods,but not worked.thanks in advance
holder.textView1.setText(datas.get(position).get("name"));
holder.textview3.setText(datas.get(position).get("code"));
holder.textView2.setText(datas.get(position).get("desc"));
you are adding hash map in the array list but in the adapter you are trying to get data from the hash map, instead of that you need to take value from arraylist which will return hashmap object and from that object you need to get value for your keys.
hope this will help.
Hi there I am facing issue when deleting row view from list. I just create a place order activity and there I register list and then create a class of cart Adapter.
When I delete the row it generates the exception can't delete the row. Is there any solution?
PlaceOrder.java
public class PlaceOrder extends Activity {
String [] pIds;
String [] pNames;
String [] pPrizes;
static ListView lv;
ImageView bck;
String [] listImages;
String food_id;
String userdata[];
Intent i;
Intent intent;
TextView totalprze;
float tprize;
ProgressDialog pDialog;
TableRow p_order;
AlertDialog.Builder builder;
List<String> cart=new ArrayList<String>();
String [] pId;
String [] PName;
String [] pPrize;
Intent intent_one;
String userid;
String status,message;
String [] delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
lv=(ListView)findViewById(R.id.cart_list);
bck=(ImageView) findViewById(R.id.placeholder_bg_btn);
totalprze =(TextView) findViewById(R.id.place_order_price);
p_order=(TableRow)findViewById(R.id.p_order);
intent=new Intent(this,Food.class);
builder = new AlertDialog.Builder(this);
p_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
builder.setMessage(Html.fromHtml("<b>Place Order</b>"+"<br>Do you want to continue ?"))
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Cursor cursor = new ShopingCartHelper(PlaceOrder.this).getData(userid);
// Toast.makeText(getApplicationContext(), "View Cart",Toast.LENGTH_LONG).show();
if (cursor .moveToFirst()) {
while (cursor.isAfterLast() == false) {
String pid = cursor.getString(cursor
.getColumnIndex("id"));
String pName = cursor.getString(cursor
.getColumnIndex("product_name"));
String prize = cursor.getString(cursor
.getColumnIndex("price"));
cart.add(pid);
cart.add(pName);
// System.out.print("Product Name "+pName+"Price"+prize+"id"+id+"\n");
cart.add(prize);
cursor.moveToNext();
}
int length=cart.size();
pId=new String[cart.size()/3];
PName=new String[cart.size()/3];
pPrize=new String[cart.size()/3];
//System.out.print(length+"\n\n\n\n Values of List \n\n\n\n");
int k=0;
String[] values=cart.toArray(new String[cart.size()]);
// System.out.print("Values are :\n\n"+values);
int count=0;
for(int j=0;j<values.length/3;j++){
pId[j]=values[count];
count=count+1;
PName[j]=values[count];
count=count+1;
pPrize[j]=values[count];
count=count+1;
}
for(int i=0;i<pPrize.length;i++){
System.out.println(pPrize[i]);
}
}
// Toast.makeText(getApplicationContext(), "Yes",Toast.LENGTH_SHORT).show();
new place_order().execute();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
);
AlertDialog d = builder.create();
// d.setTitle("Are you sure");
d.show();
TextView messageText = (TextView)d.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
}
});
i=new Intent(this,Menu.class);
bck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle=new Bundle();
//bundle.putStringArray("images", ListImages);
bundle.putString("food_id", food_id);
bundle.putStringArray("images", listImages);
bundle.putStringArray("userData",userdata);
i.putExtras(bundle);
startActivity(i);
}
});
if(this.getIntent().getExtras()!=null)
{
Bundle b=this.getIntent().getExtras();
pIds=b.getStringArray("pId");
pNames=b.getStringArray("PName");
pPrizes=b.getStringArray("pPrize");
userdata=b.getStringArray("userData");
tprize=b.getFloat("totalprize");
food_id=b.getString("food_id");
listImages=b.getStringArray("images");
String prz=Float.toString(tprize);
totalprze.setText("$"+prz);
delete=new String[pIds.length];
for(int m=0;m<pIds.length;m++){
delete[m]="Delete";
}
lv.setAdapter(new cartAdapter(PlaceOrder.this, pIds, pNames, pPrizes,userdata,delete));
userid=userdata[0];
pIds=null;
pNames=null;
pPrizes=null;
}
}
public void onBackPressed() {
pIds=null;
pNames=null;
pPrizes=null;
}
}
Cart Adapter.java
public class cartAdapter extends BaseAdapter{
String [] pIdz;
String [] pNamz;
String [] pPrizs;
String [] userData;
String [] del;
// List<String> imges;
Context context;
DrawerLayout dLayout;
// private ShopingCartHelper obj;
//ListView dList;
private static LayoutInflater inflater=null;
JSONArray jCat = null;
int count=0;
ProgressDialog pDialog;
public cartAdapter(PlaceOrder ctx,
String[] pIds,String[] pNams, String[] pprise,String [] userdata, String[] delete) {
pIdz=pIds;
pNamz=pNams;
context=ctx;
pPrizs=pprise;
userData=userdata;
del=delete;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
if(pIdz==null){
Toast.makeText(context, "There is issue with net connection.", Toast.LENGTH_LONG).show();
//Intent i=new Intent(context,WelcomeActivity.class);
//context.startActivity(i);
return count ;
}else{
return pIdz.length;
}
}
#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;
}
public class holder{
DrawerLayout dLayout;
TextView pid;
TextView pname;
TextView pprise;
Button delete;
ListView lv;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final holder hldr=new holder();
View rowView = null;
rowView = inflater.inflate(R.layout.place_order_item_list, null);
//hldr.dLayout= (DrawerLayout)rowView.findViewById(R.id.btn_drawer_layout);
// hldr.dLayout=(DrawerLayout)rowView.findViewById(R.id.btndrawerLayout);
hldr.pid=(TextView) rowView.findViewById(R.id.item_id);
hldr.pname=(TextView) rowView.findViewById(R.id.item_name);
hldr.pprise=(TextView) rowView.findViewById(R.id.item_price);
hldr.delete=(Button) rowView.findViewById(R.id.delete);
hldr.pid.setText(pIdz[position]);
hldr.pname.setText(pNamz[position]);
hldr.pprise.setText(pPrizs[position]);
hldr.delete.setText(del[position]);
hldr.delete.setTag(position);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pid=Integer.parseInt(hldr.pid.getText().toString());
new ShopingCartHelper(context).delProduct(pid);
pIdz[position]=null;
pNamz[position]=null;
pPrizs[position]=null;
del[position]=null;
// new PlaceOrder().updateAdapter(context,pIdz,pNamz,pPrizs,del);
//
notifyDataSetChanged();
}
});
return rowView;
// TODO Auto-generated method stub
}
}
Your problem is in CartAdapter.java, you have:
pIdz[position]=null;
pNamz[position]=null;
pPrizs[position]=null;
del[position]=null;
You don't delete the item in list, you only set it to 'null' value. So when call 'notifyDataSetChanged' you made a NullPointerException.
To fix this bug, change all String[] to ArrayList, and easy call Java.util.ArrayList.remove(index)
As you want to remove the row from the list so you have to delete that explicitly for that you should declare Pidz like this
ArrayList<String> Pidz;
And in your cartAdapter constructor
Pidz = Arrays.asList(pIds);
Please modify your onclicklistener like this,
public void onClick(View v) {
int pid=Integer.parseInt(hldr.pid.getText().toString());
new ShopingCartHelper(context).delProduct(pid);
pIdz[position]=null;
pNamz[position]=null;
pPrizs[position]=null;
del[position]=null;
pIdz.remove(position);
notifyDataSetChanged();
}
});
Hi I can not delete a row from list View i don't know how to delete it i search a lot from Internet i try out many examples but yet i can't solve the issue . when i click the hldr.delete button the complete row of list View delete from the list solution pls.
PlaceOrder Activity
public class PlaceOrder extends Activity {
String [] pIds;
String [] pNames;
String [] pPrizes;
static ListView lv;
ImageView bck;
String [] listImages;
String food_id;
String userdata[];
Intent i;
TextView totalprze;
float tprize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
lv=(ListView)findViewById(R.id.cart_list);
bck=(ImageView) findViewById(R.id.placeholder_bg_btn);
totalprze =(TextView) findViewById(R.id.place_order_price);
i=new Intent(this,Menu.class);
bck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle=new Bundle();
//bundle.putStringArray("images", ListImages);
bundle.putString("food_id", food_id);
bundle.putStringArray("images", listImages);
bundle.putStringArray("userData",userdata);
i.putExtras(bundle);
startActivity(i);
}
});
if(this.getIntent().getExtras()!=null)
{
Bundle b=this.getIntent().getExtras();
pIds=b.getStringArray("pId");
pNames=b.getStringArray("PName");
pPrizes=b.getStringArray("pPrize");
userdata=b.getStringArray("userData");
tprize=b.getFloat("totalprize");
food_id=b.getString("food_id");
listImages=b.getStringArray("images");
String prz=Float.toString(tprize);
totalprze.setText("$"+prz);
lv.setAdapter(new cartAdapter(PlaceOrder.this, pIds, pNames, pPrizes,userdata));
pIds=null;
pNames=null;
pPrizes=null;
}
}
public void onBackPressed() {
pIds=null;
pNames=null;
pPrizes=null;
}
}
CartAdapter
public class cartAdapter extends BaseAdapter{
String [] pIdz;
String [] pNamz;
String [] pPrizs;
String [] userData;
// List<String> imges;
Context context;
// private ShopingCartHelper obj;
private static LayoutInflater inflater=null;
JSONArray jCat = null;
int count=0;
ProgressDialog pDialog;
public cartAdapter(PlaceOrder ctx,
String[] pIds,String[] pNams, String[] pprise,String [] userdata) {
pIdz=pIds;
pNamz=pNams;
context=ctx;
pPrizs=pprise;
userData=userdata;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
if(pIdz==null){
Toast.makeText(context, "There is issue with net connection.", Toast.LENGTH_LONG).show();
//Intent i=new Intent(context,WelcomeActivity.class);
//context.startActivity(i);
return count ;
}else{
return pIdz.length;
}
}
#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;
}
public class holder{
TextView pid;
TextView pname;
TextView pprise;
Button delete;
ListView lv;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final holder hldr=new holder();
View rowView = null;
Bitmap bitmap = null;
rowView = inflater.inflate(R.layout.place_order_item_list, null);
hldr.pid=(TextView) rowView.findViewById(R.id.item_id);
hldr.pname=(TextView) rowView.findViewById(R.id.item_name);
hldr.pprise=(TextView) rowView.findViewById(R.id.item_price);
hldr.delete=(Button) rowView.findViewById(R.id.delete);
hldr.pid.setText(pIdz[position]);
hldr.pname.setText(pNamz[position]);
hldr.pprise.setText(pPrizs[position]);
/* convertView.setTag(hldr);
hldr.delete.setTag(hldr);*/
//
// Picasso.with(context).load(imgs[position]).into(hldr.img);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// rowView.remove(position); //removing from your List
//Toast.makeText(context, "Delete",Toast.LENGTH_LONG).show();
int pid=Integer.parseInt(hldr.pid.getText().toString());
//Toast.makeText(context, "pid"+pid, Toast.LENGTH_LONG).show();
new ShopingCartHelper(context).delProduct(pid);
//PlaceOrder.lv.removeViewAt(position);
notifyDataSetChanged();
}
});
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// // TODO Auto-generated method stub
// cartAdapter.this.pIdz.remove[position];
// Toast.makeText(context, "hi",Toast.LENGTH_LONG).show();
}
});
return rowView;
// TODO Auto-generated method stub
}
}
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3. And if you want to delete from the listview the array which you are used should be dynamic(Adding & Deleting). So make the pIdz; pNamz;pPrizs;userData into some Modal Object, and prepare the list of Modal Objects and pass it to adapter and make the life easier
You'd be better off with a List, e.g. an ArrayList:
hldr.delete.setTag(position);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position = (int)v.getTag();
list.remove(position);
notifyDataSetChanged();
}
});
First.
You should make a object that stores all your different strings instead of using multiple arrays for each value.
Ej:
class MyClass
{
String id;
String name
String price;
public MyClass(String id, String name, String price)
{
this.id = id;
this.name = name;
this.price = price;
}
}
That way you wouldnt have to delete the position of each of the arrays.
And finally to answer your question, just delete the value of position you want to delete for each of the arrays.
Since they are Array and not ArrayList you will need to recreate it with the correct new dimension (Note it will be much easier with ArrayList).
Then just call notifyDataSetChanged() on your Adapter class.
Hope this helps.
Being a newbie to android I am trying to implement List view on my project. The list view works. However I am only able to see one row in my list. I wish to add as many rows as I want dynamically.
I have created a separate XML which defines the structure of a single row in the list view.
Here is what I have coded until now :
public class Offers extends Activity
{
ListView latesttrans;
ArrayList<String> listItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offers);
latesttrans = (ListView) findViewById(R.id.listView1);
latesttrans.setAdapter(new mylist2(this));
}
}
class SingleRow2
{
String title;
String description;
SingleRow2(String title, String description)
{
this.title=title;
this.description=description;
}
}
class mylist2 extends BaseAdapter
{
int i=0;
Boolean flagValue = false;
ArrayList<SingleRow> list;
Context context;
mylist2(Context c)
{
context=c;
list=new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] title = res.getStringArray(R.array.titles);
String[] description = res.getStringArray(R.array.description);
list.add(new SingleRow(title[i],description[i]));
i++;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0)
{
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0)
{
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup viewGroup)
{
// TODO Auto-generated method stub
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row_offers,viewGroup,false);
Uri latesttransuri = Uri.parse("content://sms/inbox");
Cursor latesttranscursor = context.getContentResolver().query(latesttransuri, new String[]{"_id","address","date","body"}, null, null, null);
if(flagValue == false)
{
latesttranscursor.moveToFirst();
flagValue = true;
}
String address = null,body = null;
int i=0;
while(latesttranscursor.moveToNext())
{
address=latesttranscursor.getString(1);
long date = latesttranscursor.getLong(2);
String sdate = millisToDate(date);
body = latesttranscursor.getString(3);
if(body.contains("FREE"))
{
TextView title = (TextView) row.findViewById(R.id.textViewSingleOffer1);
TextView description = (TextView) row.findViewById(R.id.textViewSingleOffer2);
title.setText(address);
description.setText(body);
}
else if(body.contains("unlimited"))
{
TextView title = (TextView) row.findViewById(R.id.textViewSingleOffer1);
TextView description = (TextView) row.findViewById(R.id.textViewSingleOffer2);
title.setText(address);
description.setText(body);
}
}
return row;
}
public String millisToDate(long currentTime)
{
String finalDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime);
Date date = calendar.getTime();
finalDate = date.toString();
return finalDate;
}
}
You don't iterate over your items. In the constructor of your adapter you just increment i once, and then stop. This results in having one row. Change it to a for loop like this:
for(int i = 0; i < var; i++) {
list.add(new SingleRow(title[i], description[i]));
}
Where var is the size of your array that you retrieve from the resources.
For more information about ListView and the use of Adapters: http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter
I have a listview with textview and checkbox. The text values are stored in a HashMap. Data is retrieved from a DB. Map key is the ID and Map value is a Location. When I pass the HashMap to the adapter, it starts printing from position 0 (zero). Because of this I get a null text(with no value) and miss one value(the last one) in the HashMap. Can't I use a HashMap as the data source?
EDIT: Here is the code
public class LocationActivity extends Activity{
myAdapter myA;
Map<Integer,String> locLables;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
locLables = new HashMap<Integer, String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.put(new Integer(cursor.getString(0)),cursor.getString(1));
System.out.println(cursor.getString(0)+" "+ cursor.getString(1));
} while (cursor.moveToNext());
}
}
cursor.close();db.close();
//System.out.println(locLables);
myA = new myAdapter(this, locLables, listview);
listview.setAdapter(myA);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg2 == 0 )
arg2 = arg2+1;
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
Here is the Adapter class
class myAdapter extends BaseAdapter{
ListView listView;
Activity cntx;
Map<Integer,String> locations;
List<Integer> locids = new LinkedList<Integer>();
public myAdapter(Activity context,Map<Integer,String> locLables, ListView lv){
cntx = context;
locations = locLables;
listView = lv;
System.out.println(locations);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return locations.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
final int posi = position;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.locationmain_entry, null);
TextView tv = (TextView)row.findViewById(R.id.textView12);
final CheckBox cb = (CheckBox)row.findViewById(R.id.checkBox12);
if(locids.contains(posi))
cb.setChecked(true);
//here I get a null value as the first element and misses the last value..
tv.setText(locations.get(position));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("Chedked" + posi+ locations.get(posi));
//cb.setChecked(true);
if(!locids.contains(posi))
locids.add(posi);
//System.out.println(locids.get(posi));
}else if(!isChecked){
//cb.setChecked(false);
if(locids.contains(posi))
locids.remove(new Integer(posi));
System.out.println("NOt checked" +posi + locations.get(posi));
}
}
});
return row;
}
It runs for the number of elements in the Map. As it is using a 0 (by position variable) it misses the last value as well.
What you can do is
ArrayList<Hashmap<Integer,String>> myList = new ArrayList<Hashmap<Integer,String>>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables = new HashMap<Integer, String>();
locLables.put(new Integer(cursor.getString(0)),cursor.getString(1));
myList.add(locLables);
} while (cursor.moveToNext());
}
}
cursor.close();db.close();
myA = new myAdapter(this, myList, listview);
listview.setAdapter(myA);
You will have to change your "myAdapter" Adapter's constructor to hold "ArrayList> myList" instead of "Map locLables"..
This will help... Let me know if the problem still persists..