Android: fill list view with data from sqlite - android

Overview: The programme I'm now trying to make has the following steps.
get the input data from users and store them in the SQLite database.
Fill the list view with the data retrieved from the database.
In order to implement 1, I first created the addNewItem() method as follows.
public void addNewPost(Post post) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// get the variables which are to be put into the database row.
String uploader = post.getUploader();
String content = post.getContent();
String privacy_level = post.getPrivacyLevel();
String uploaded_at = post.getUploadedAt();
String edited_at = post.getEditedAt();
values.put(KEY_UPLOADER, uploader);
values.put(KEY_CONTENT, content);
values.put(KEY_PRIVACY_LEVEL, privacy_level);
values.put(KEY_UPLOADED_AT, uploaded_at);
values.put(KEY_EDITED_AT, edited_at);
db.insert(TABLE_POST, null, values);
db.close();
}
And for 2, I created another method called initListView().
private void initListView() {
SQLiteDatabase db = sqliteHandler.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + SQLiteHandler.TABLE_POST, null);
username.clear();
uploaded_at.clear();
content.clear();
if(cursor.moveToFirst()) {
do {
username.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADER)));
uploaded_at.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADED_AT)));
content.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_CONTENT)));
} while(cursor.moveToNext());
}
FeedAdapter adapter = new FeedAdapter(this, username, uploaded_at, content);
listView.setAdapter(adapter);
cursor.close();
}
And finally this is the FeedAdapter class.
public class FeedAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> username;
private ArrayList<String> uploaded_at;
private ArrayList<String> content;
public FeedAdapter(Context context, ArrayList<String> username, ArrayList<String> uploaded_at, ArrayList<String> content) {
this.context = context;
this.username = username;
this.uploaded_at = uploaded_at;
this.content = content;
}
public int getCount() {
return username.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater;
if(convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, null);
ImageView ivFeedThumbnail = (ImageView) convertView.findViewById(R.id.ivFeedThumbnail);
TextView tvFeedUsername = (TextView) convertView.findViewById(R.id.tvFeedUsername);
TextView tvFeedUploaded = (TextView) convertView.findViewById(R.id.tvFeedCreated);
TextView tvFeedText = (TextView) convertView.findViewById(R.id.tvFeedText);
TextView tvFeedLikes = (TextView) convertView.findViewById(R.id.tvFeedLikes);
TextView tvFeedComments = (TextView) convertView.findViewById(R.id.tvFeedComments);
Button btnLike = (Button) convertView.findViewById(R.id.btnLike);
Button btnComment = (Button) convertView.findViewById(R.id.btnComment);
tvFeedUsername.setText(username.get(position));
tvFeedUploaded.setText(uploaded_at.get(position));
tvFeedText.setText(content.get(position));
}
return convertView;
}
}
The code seems to have no problem, but when I run the application, the list is still empty.
Any tips for the solution will be very much appreciated.

Related

Problem of displaying data into custom listView

I'm not good at using Custom Listview but I want to display my SQLite data into it.When I try it doesn't show me any thing in List.
thanks, guys to tell me what is the problem in advance:
Rq: Retrieving data works fine And my table has 3 rows :
my source code:
new_facture.java:
Databasehelper mydatabase;
ArrayAdapter<String> adapter;
ArrayList<String> itemList;
ArrayList<Product> arrayList;
CustomAdaptorLP customAdaptorLP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_facture);
ListView LP = (ListView)findViewById(R.id.productLV);
mydatabase = new Databasehelper(this);///-----Inialisation de base
arrayList = new ArrayList<>();
arrayList = mydatabase.getallProductdataintolist();
customAdaptorLP = new CustomAdaptorLP(this,arrayList);
Product product = new Product();
Log.d("stat", " offline mode");
LP.setAdapter(customAdaptorLP);
CustomAdaptorLP.java::
private Activity activity;
private ArrayList<Product> Items;
private LayoutInflater inflater;
TextView tvId,tvname,tvprix;
Product sm;
public CustomAdaptorLP(Activity activity, ArrayList<Product> items) {
this.activity = activity;
this.Items = items;
}
#Override
public int getCount() {
return 0;
}
#Override
public Product getItem(int position) {
return Items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater == null){
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null){
convertView = inflater.inflate(R.layout.lp_layout,null);
}
tvId = (TextView)convertView.findViewById(R.id.id_product);
tvname = (TextView)convertView.findViewById(R.id.name_product);
tvprix = (TextView)convertView.findViewById(R.id.prix_product);
sm = Items.get(position);
tvId.setText(sm.id);
tvname.setText(sm.produit);
tvprix.setText(sm.prix);
return convertView;
}
and Product is a class has 3 Strings id/produit/prix with GET/SET and those two constructs:
public Product(String id, String produit, String prix) {
this.id = id;
this.produit = produit;
this.prix = prix;
}
public Product() {
}
Databasehelper.java
public ArrayList<Product> getallProductdataintolist(){
ArrayList<Product> list = new ArrayList<>();
String sql = "select * from " + Table2;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db .rawQuery(sql,null);
if(cursor.moveToFirst()){
do{
Product sm = new Product();
sm.setId(cursor.getString(0));
sm.setProduit(cursor.getString(1));
sm.setPrix(cursor.getString(2));
}while (cursor.moveToNext());
}
return list;
}
I think you return 0 in getCount() method instead Items.size(); change your Adapter class method like below.
#Override
public int getCount() {
return Items.size();
}

how to delete a row from a ListView with a delete button in the row

I have a class which extends ArrayAdapter<String>. I want to have a delete image button deletes the particular row.. This is my code:
public class ViewCartList extends ArrayAdapter<String> {
private String[] cart_item_name;
private String[] cart_item_quan;
private String[] cart_item_price;
private Activity context;
public ViewCartList(Activity context, String[] cartitemquan, String[] cartitemname,String[] cartitemprice){
super(context,R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan[position]);
textViewItemName.setText(cart_item_name[position]);
textViewItemPrice.setText(cart_item_price[position]);
imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
}
});
return listViewItem;
}
}
And This is my Basket class where I am using this above adapter class.
What to do if i want to remove a particular row from the ListView from that delete button given above..
public class Basket extends AppCompatActivity implements View.OnClickListener {
TextView cartview;
MyCartDatabse myDatabase;
SQLiteDatabase sql;
ContentValues cv;
String wr;
ListView list;
public static String[] quan =null;
public static String[] itemname=null;
public static String[] baseprice=null;
TextView edit_order;
public boolean imrow;
ViewCartList vc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basket);
myDatabase = new MyCartDatabse(this,"mydb",null,1);
sql = myDatabase.getWritableDatabase();
cv = new ContentValues();
list = (ListView)findViewById(R.id.listcart);
getRecords();
edit_order = (TextView)findViewById(R.id.edit_order);
edit_order.setOnClickListener(this);
}
public void getRecords(){
sql = myDatabase.getReadableDatabase();
Cursor cursor = sql.rawQuery("select * from cart ",null);
quan = new String[cursor.getCount()];
itemname = new String[cursor.getCount()];
baseprice = new String[cursor.getCount()];
int i = 0;
if(cursor.getCount()>0){
while(cursor.moveToNext()){
String uquan = cursor.getString(5);
String uname = cursor.getString(1);
String uprice = cursor.getString(4);
quan[i] = uquan;
itemname[i] = uname;
baseprice[i] = uprice;
i++;
}
vc = new ViewCartList(this,quan,itemname,baseprice);
list.setAdapter(vc);
}
else{
// Do something
}
cursor.close();
}
#Override
public void onClick(View view) {
edit_order.setText("Apply Changes");
}
}
The elegant approach for your problem is to pass an ArrayList of object to your Adapter and then handle the delete action.
So you might consider creating an object like this.
public class Cart {
public String cart_item_name;
public String cart_item_quan;
public String cart_item_price;
}
Now take an ArrayList of that class and populate the ArrayList to pass to your Adapter.
public class ViewCartList extends BaseAdapter {
private Context context;
private ArrayList<Cart> mCartList;
public ViewCartList(Context context, ArrayList<Cart> mCartList) {
this.context = context;
this.mCartList = mCartList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(mCartList.get(position).cart_item_quan);
textViewItemName.setText(mCartList.get(position).cart_item_name);
textViewItemPrice.setText(mCartList.get(position).cart_item_price);
// Remove the following and set the visibility true from the layout.
// imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Delete the row
mCartList.remove(position);
notifyDatasetChanged();
}
});
return listViewItem;
}
}
If you want to completely delete the item you should consider using List<String> instead of Array
Here is updated code for List
public class ViewCartList extends ArrayAdapter<String> {
private List<String> cart_item_name; // Use List here
private List<String> cart_item_quan; // Use List here
private List<String> cart_item_price; // Use List here
private Activity context;
public ViewCartList(Activity context, List<String> cartitemquan, List<String> cartitemname,List<String> cartitemprice){
super(context, R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan.get(position));
textViewItemName.setText(cart_item_name.get(position));
textViewItemPrice.setText(cart_item_price.get(position));
imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
cart_item_quan.remove(position);
cart_item_name.remove(position);
cart_item_price.remove(position);
notifyDataSetChanged();
}
});
return listViewItem;
}
}
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
cart_item_name[position] = null;
cart_item_quan[position]= null;
cart_item_price[position] = null;
notifydatasetchanged();
}
});
public class ViewCartList extends ArrayAdapter<String> {
private String[] cart_item_name;
private String[] cart_item_quan;
private String[] cart_item_price;
private Activity context;
public ViewCartList(Activity context, String[] cartitemquan, String[] cartitemname,String[] cartitemprice){
super(context,R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan[position]);
textViewItemName.setText(cart_item_name[position]);
textViewItemPrice.setText(cart_item_price[position]);
imcut.setVisibility(View.VISIBLE);
imcut.setTag(position);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
int pos = Integer.parseInt(view.getTag().toString());
mCartList.remove(position);
notifyDatasetChanged();
}
});
return listViewItem;
}
}

How do I retrieve two fields from a prepopulate sqlite db and assign it to custom list view?

I want to retrieve data from two fields from prepopulate sqlite database. The fields are Organization Name (org_name) and Contact Number (contact_no). After that I need to assign org_name data to a large text field and contact_no to small text field in my custom list view.
I have tried this only with one field. It's working fine. But when I'm trying to retrieve two fields it's not working. This is what I tried. Please help me to solve this issue.
ContactView class
public class ContactView extends Activity {
private ListView listView;
private ListView listView1;
List<Organization> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBAccess databaseAccess = DBAccess.getInstance(this);
databaseAccess.open();
List<String> quotes = databaseAccess.getQuotes(getIntent().getStringExtra("ID_EXTRA"));
databaseAccess.close();
List<Organization> rowItem=new ArrayList<Organization>();
for(String quote:quotes){
Organization temp=new Organization(quote);
rowItem.add(temp);
}
listView = (ListView)findViewById(R.id.listView);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.single_row_item, rowItem);
listView.setAdapter(adapter);
}
Database Access Class
public class DBAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DBAccess instance;
String passedVar = null;
private ListView listView;
public DBAccess(Context context) {
this.openHelper = new HelloDatabase(context);
}
public static DBAccess getInstance(Context context) {
if (instance == null) {
instance = new DBAccess(context);
}
return instance;
}
public void open() {
this.database = openHelper.getWritableDatabase();
}
public void close() {
if (database != null) {
this.database.close();
}
}
public List<String> getQuotes(String id) {
List<String> list = new ArrayList<>();
Integer value;
if (id != null) {
Cursor cursor = database.rawQuery("SELECT org_name,contact_no FROM org_name WHERE category_id = \"" + id + "\"", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
list.add(cursor.getString(cursor.getColumnIndex("contact_no")));
cursor.moveToNext();
}
cursor.close();
}
return list;
}}
Bean class
public class Organization {
public String title;
public String telenum;
public Organization(String title,String telenum) {
this.title = title;
this.telenum=telenum;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTelenum(){
return telenum;
}
public void setTelenum(String telenum){
this.telenum=telenum;
}
}
CustomListViewAdapter class
public class CustomListViewAdapter extends ArrayAdapter<Organization> {
Context context;
public CustomListViewAdapter(Context context, int layout,
List<Organization> items) {
super(context, layout, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtTitle;
TextView txtTele;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Organization rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.single_row_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.org_name);
holder.txtTele = (TextView) convertView.findViewById(R.id.tele_num);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtTitle.setText(rowItem.getTitle());
holder.txtTele.setText(rowItem.getTelenum());
return convertView;
}}
Note : If any one facing the same issue, kindly use SimpleCursorAdapter. Its simple, easy to use and efficient. Find a simple example here or checkout my answer on this thread https://stackoverflow.com/a/37560755/5460053
It is not working for two fields because of the following lines in getQuotes() method of DBAccess class :
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));//Adding org_name first. org_name is added at indexes : 0,2,4,...
list.add(cursor.getString(cursor.getColumnIndex("contact_no")));//Then adding contact_no. contact_no is added at indexes : 1,3,5,...
cursor.moveToNext();
}
Then while creating a datasource for the adapter, org_name and contact_no are added at alternate indexes
List<Organization> rowItem=new ArrayList<Organization>();
for(String quote:quotes){
Organization temp=new Organization(quote);//I wonder how this worked as there is only one contructor for Organization which is expecting 2 parameters
rowItem.add(temp);
}
Change your DBAccess class getQuotes() to this :
public List<Organization> getQuotes(String id) {
List<Organization> list = new ArrayList<>();
if (id != null) {
Cursor cursor = database.rawQuery("SELECT org_name,contact_no FROM org_name WHERE category_id = \"" + id + "\"", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Organization org = new Organization(cursor.getString(0),
cursor.getString(cursor.getColumnIndex("contact_no")));
list.add(org);
cursor.moveToNext();
}
cursor.close();
}
return list;
}
And change your ContactView Activity's onCreate() to this :
public class ContactView extends Activity {
private ListView listView;
private ListView listView1;
List<Organization> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBAccess databaseAccess = DBAccess.getInstance(this);
databaseAccess.open();
List<Organization> rowItem = databaseAccess.getQuotes(getIntent().getStringExtra("ID_EXTRA"));
databaseAccess.close();
listView = (ListView)findViewById(R.id.listView);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.single_row_item, rowItem);
listView.setAdapter(adapter);
}

Listview is not updating inside baseadapter after changing database value

I use SQLITE database to store list items and Baseadapter to display listview in my application.
Each item in the listview have edit text value, By default the value is 1.
When user changes the value from 1 to 2 , then the value has to be updated in database.
This update has to be done inside Adapter.
Below is the Adapter code where I change the edit text value.
public class CustomAdapter_cart extends BaseAdapter {
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_images = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
ArrayList<String> list_productid = new ArrayList<String>();
ArrayList<Integer> ids = new ArrayList<Integer>();
CustomAdapter_cart cart_refresh;
Bitmap b;
Context context;
AddToCart cart;
String value,name,price,image_new,model,product,qty;
private static LayoutInflater inflater = null;
Cursor cu;
String quant;
Holder holder = new Holder();
SharedPreferences sharedpreferences;
ArrayList<String>listMessages = new ArrayList<String>(new LinkedHashSet<String>());
ArrayList<String> quant_items = new ArrayList<String>();
Cursor mCursor;
ContentValues data=new ContentValues();
String model_item;
String id;
int id_final;
public CustomAdapter_cart(Context context, ArrayList<String> list_name, ArrayList<String> list_price, ArrayList<String> bitmapArray, ArrayList<String> list_model, ArrayList<String> list_productid,ArrayList<String> qty, ArrayList<Integer>ids ) {
this.context = context;
this.list_name = list_name;
this.list_price = list_price;
this.list_images = bitmapArray;
this.list_model = list_model;
this.list_productid = list_productid;
this.quant_items = qty;
this.cart_refresh = this;
this.ids = ids;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list_name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tv_name, tv_price, tv_model,tv_product,tv_id;
ImageView image;
Button delete;
EditText quantity;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View rowView = convertView;
if (convertView == null) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_items_cart, null);
holder.tv_name = (TextView) rowView.findViewById(R.id.name_cart);
holder.tv_price = (TextView) rowView.findViewById(R.id.price_cart);
holder.image = (ImageView) rowView.findViewById(R.id.image_cart);
holder.tv_model = (TextView) rowView.findViewById(R.id.model_cart);
holder.tv_product = (TextView) rowView.findViewById(R.id.product_cart);
holder.delete = (Button) rowView.findViewById(R.id.delete);
holder.quantity = (EditText) rowView.findViewById(R.id.quantity);
holder.tv_id = (TextView)rowView.findViewById(R.id.ids);
rowView.setTag(holder);
}
else
holder = (Holder) rowView.getTag();
holder.tv_name.setText(list_name.get(position));
name = holder.tv_name.getText().toString();
holder.tv_price.setText(list_price.get(position));
price = holder.tv_price.getText().toString();
holder.tv_model.setText(list_model.get(position));
model = holder.tv_model.getText().toString();
holder.tv_product.setText(list_productid.get(position));
product = holder.tv_product.getText().toString();
holder.quantity.setText(quant_items.get(position));
quant = holder.quantity.getText().toString();
holder.tv_id.setText(Integer.toString(ids.get(position)));
id = holder.tv_id.getText().toString();
id_final = Integer.parseInt(id);
holder.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
image_new = holder.image.toString();
final View finalRowView1 = rowView;
holder.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
value = s.toString();
quant.replace(quant, value);
updateTable();
Toast.makeText(finalRowView1.getContext(), "Updating Table", Toast.LENGTH_SHORT).show();
}
});
final View finalRowView = rowView;
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_item = ((TextView) finalRowView.findViewById(R.id.name_cart)).getText().toString();
String price_item = ((TextView) finalRowView.findViewById(R.id.price_cart)).getText().toString();
model_item = ((TextView) finalRowView.findViewById(R.id.model_cart)).getText().toString();
Intent in = new Intent(context, AddCart_FullImage.class);
in.putExtra("model", model_item);
in.putExtra("name", name_item);
in.putExtra("price", price_item);
context.startActivity(in);
}
});
return rowView;
}
private Bitmap loadImageFromStorage(String path) {
try {
File f = new File(path, "");
f.canRead();
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public void updateTable() {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db.updateContact(new Cart(id_final,name, price, image_new, model, product, value));
Log.v("LOG", "After text change value db " + value);
} catch (Exception e) {
}
}
}
Problem
When I try to update the edit text value, it gets updated in db but again it changes to default value "1".
I am not sure where I am going wrong.
Any help would be really greatfull.
Thanks.
Each time the system wants to redraw your ListView it calls the getView(...) method of your adapter. The following line sets the value of your quantity EditText:
holder.quantity.setText(quant_items.get(position));
When the user changes the value in the EditText you do the following:
quant.replace(quant, value);
updateTable();
As you can see, your adapter's datasource (quant_items) is not updated.
Since you are updating the database from within the adapter, you can just update the quant_items ArrayList and it should do the trick.
You need to notify your adapter if you change its data (and of, you need to update list_name with the new values).
The easiest way to notify your adapter is to use notifyDatasetChanged() after you updated your data.

getting listview row data

I have a listview in my application.I want to set the value of textview in that particular row when I click one of the textview in that row itself.so,I tried like below
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView t=(TextView)v;
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
}
});
the "likes" reference which I used is textview and I want to set the textview by getting the id of that particular row.
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
when I use this I am getting the id of the first visible row of the screen.
How can I get the id of textview of that particular row,on a textview click.
Thanks
I'm not sure how you are populating your list with data, however here is a method I use that works very well.
Data Models
public class Publication {
public String string1;
public String string2;
public Publication() {
}
public Publication(String string1, String string2) {
this.string1= string1;
this.string2= string2;
}
}
Create an array adapter
public class ContactArrayAdapter extends ArrayAdapter<ContactModel> {
private static final String tag = "ContactArrayAdapter";
private static final String ASSETS_DIR = "images/";
private Context context;
//private ImageView _emotionIcon;
private TextView _name;
private TextView _email;
private CheckBox _checkBox;
private List<ContactModel> contactModelList = new ArrayList<ContactModel>();
public ContactArrayAdapter(Context context, int textViewResourceId,
List<ContactModel> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contactModelList = objects;
}
public int getCount() {
return this.contactModelList.size();
}
public ContactModel getItem(int index) {
return this.contactModelList.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
Log.d(tag, "Starting XML Row Inflation ... ");
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.contact_list_entry, parent, false);
Log.d(tag, "Successfully completed XML Row Inflation!");
}
// Get item
final ContactModel contactModel = getItem(position);
Resources res = this.getContext().getResources();
//Here are some samples so I don't forget...
//
//_titleCount = (TextView) row.findViewById(R.id.category_count);
// _category.setText(categories1.Category);
//
//if (categories1.Category.equals("Angry")) {
//Drawable angry = res.getDrawable(R.drawable.angry);
//_emotionIcon.setImageDrawable(angry);
//}
_checkBox = (CheckBox) row.findViewById(R.id.contact_chk);
_email = (TextView) row.findViewById(R.id.contact_Email);
_name = (TextView)row.findViewById(R.id.contact_Name);
//Set the values
_checkBox.setChecked(contactModel.IsChecked);
_email.setText(contactModel.Email);
_name.setText(contactModel.Name);
_checkBox.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View view) {
if (contactModel.IsChecked) {
contactModel.IsChecked = false;
notifyDataSetChanged();
}
else {
contactModel.IsChecked = true;
notifyDataSetChanged();
}
}
});
return row;
}
}
Use the array adapter to fill your list
ContactArrayAdapter contactArrayAdapter;
//
List<ContactModel> contactModelList;
//Fill list with your method
contactModelList = getAllPhoneContacts();
//
contactArrayAdapter = new ContactArrayAdapter(getApplicationContext(), R.layout.contact_list_entry, contactModelList);
//
setListAdapter(contactArrayAdapter);
A sample method to fill data:
public List<ContactModel> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
List<ContactModel> arrContacts = new Stack<ContactModel>();
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Email.DATA1
,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
,ContactsContract.CommonDataKinds.Phone._ID}, null , null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String email= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (email != null)
{
ContactModel contactModel = new ContactModel();
contactModel.Name = name;
contactModel.Email = email;
contactModel.IsChecked = false;
arrContacts.add(contactModel);
}
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
Accessing the data on click
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
//Click handler for listview
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
ContactModel contact= getItem(position);//This gets the data you want to change
//
some method here tochange set data
contact.email = "new#email.com"
//send notification
contactArrayAdapter.notifyDataSetChanged();
}
});

Categories

Resources