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.
Related
I am working on a grocery list app and having trouble refreshing the list view after adding a new item. After I add a new item in the database the ListView is not refreshed. If I go in the item details page and then come back to main activity the onCreate is called again and it refreshes it correctly.
If I call the refresh method in the addItemToDb() (on button clicked) method it duplicates my items but does not add them to the database.
Has anyone had this problem before???
Here is the code:
The list view adapter
public class ItemListViewAdapter extends ArrayAdapter<ItemModel> {
Activity activity;
int layoutResource;
ArrayList<ItemModel> itemModelArrayList = new ArrayList<>();
public ItemListViewAdapter(Activity act, int resource, ArrayList<ItemModel> data) {
super(act, resource, data);
activity = act;
layoutResource = resource;
itemModelArrayList = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return itemModelArrayList.size();
}
#Override
public ItemModel getItem(int position) {
return itemModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null || (row.getTag()) == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource, null);
holder = new ViewHolder();
holder.hItemName = (TextView) row.findViewById(R.id.custom_row_productName);
holder.hItemPrice = (TextView) row.findViewById(R.id.custom_row_productPrice);
holder.hItemType = (TextView) row.findViewById(R.id.custom_row_productType);
holder.hCheckBox = (CheckBox) row.findViewById(R.id.custom_row_checkBox);
holder.hItemEdit = (ImageView) row.findViewById(R.id.custom_row_edit);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.hModel = getItem(position);
holder.hItemName.setText(holder.hModel.getItemName());
holder.hItemPrice.setText(String.valueOf(holder.hModel.getItemPrice()));
holder.hItemType.setText(holder.hModel.getItemType());
holder.hItemEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemID = holder.hModel.getItemId();
String itemName = holder.hModel.getItemName();
String itemPrice = String.valueOf(holder.hModel.getItemPrice());
String itemType = holder.hModel.getItemType();
String itemDate = holder.hModel.getItemDate();
Intent intent = new Intent(activity, ItemDetail.class);
intent.putExtra("id", itemID);
intent.putExtra("product", itemName);
intent.putExtra("price", itemPrice);
intent.putExtra("type", itemType);
intent.putExtra("date", itemDate);
startActivity(activity, intent, null);
}
});
return row;
}
public class ViewHolder {
ItemModel hModel;
TextView hItemName;
TextView hItemPrice;
TextView hItemType;
TextView hItemDate;
CheckBox hCheckBox;
ImageView hItemEdit;
}
}
And main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHandler = new DatabaseHandler(getApplicationContext());
itemNameText = (EditText) findViewById(R.id.activity_main_productName);
itemPriceText = (EditText) findViewById(R.id.activity_main_productPrice);
itemTypeSpinner = (Spinner) findViewById(R.id.activity_main_spinner);
addButton = (Button) findViewById(R.id.activity_main_addButton);
saveListButton = (FloatingActionButton) findViewById(R.id.activity_main_fab);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.productTypes, R.layout.spinner_item);
itemTypeSpinner.setAdapter(spinnerAdapter);
//USE BUTTONS
addButton.setOnClickListener(this);
saveListButton.setOnClickListener(this);
//LIST_VIEW
listView = (ListView) findViewById(R.id.activity_main_listView);
//calling methods
refreshData();
}
public void refreshData() {
modelArrayListContainer.clear();
//GET ITEMS FROM DB
ArrayList<ItemModel> modelArrayListFromDB = dbHandler.getAllItems();
for (int i = 0; i < modelArrayListFromDB.size(); i++) {
int ditemID = modelArrayListFromDB.get(i).getItemId();
String dItemName = modelArrayListFromDB.get(i).getItemName();
double dItemPrice = modelArrayListFromDB.get(i).getItemPrice();
String dItemType = modelArrayListFromDB.get(i).getItemType();
String dItemDate = modelArrayListFromDB.get(i).getItemDate();
ItemModel newModel = new ItemModel();
newModel.setItemId(ditemID);
newModel.setItemName(dItemName);
newModel.setItemPrice((int) dItemPrice);
newModel.setItemType(dItemType);
newModel.setItemDate(dItemDate);
modelArrayListContainer.add(newModel);
}
//setup Adapter
itemListViewAdapter = new ItemListViewAdapter(MainActivity.this, R.layout.custom_product_layout_activity_main, modelArrayListContainer);
listView.setAdapter(itemListViewAdapter);
itemListViewAdapter.notifyDataSetChanged();
}
public void addItemToDb() {
ItemModel model = new ItemModel();
String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
model.setItemName(itemNameText.getText().toString().trim()); model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);
dbHandler.addItem(model);
dbHandler.close();
Log.v(TAG, "::addItemToDb - itemAdded");
}
}
You need to call refreshData() in your addItemToDb function like:
public void addItemToDb() {
ItemModel model = new ItemModel();
String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
model.setItemName(itemNameText.getText().toString().trim()); model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);
dbHandler.addItem(model);
dbHandler.close();
Log.v(TAG, "::addItemToDb - itemAdded");
refreshData();
}
But if you need to update data automatically from database, you need to use CursorAdaptor and use Content Providers
UPDATE
Also change your getAllItems() function in dbhandler and include the following statement in the first line of the function:
modelArrayList.clear();
I have implemented a customized listview with name,price,quantity etc,
By default the quantity is 1 in all the list items.
If user changes one of the list item's quantity from 1 to 2 , then the changed quantity has to updated in the Sqlite database.
Problem
I tried using addTextChangedListener to get the updated data from user input and update it in the sqlite database as well. But addTextChangedListener is not working .
I am unable to update the required field in the database.
Below is the code where I use addTextChangedListener.
#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);
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.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
image_new = holder.image.toString();
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().trim();
quant.replace(holder.quantity.getText().toString(), value);
updateTable();
}
});
final Holder finalHolder = holder;
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHandler db = new DatabaseHandler(context);
//SQLiteDatabase db1 = db.getWritableDatabase();
// db.onUpgrade(db1,0,1);
deleteUser(finalHolder.tv_model.getText().toString());
ListView list = (ListView)parent;
cart_refresh.notifyDataSetChanged();
list.setAdapter(cart_refresh);
// db.deleteContact(new Cart(holder.tv_name.getText().toString(),holder.tv_price.getText().toString()
// ,holder.image.toString(),holder.tv_model.getText().toString()));
}
});
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 deleteUser(String userName)
{
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try
{
db1.delete("cart", "model = ?", new String[]{userName});
//cart_refresh.notifyDataSetChanged();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
public void updateTable() {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db.updateContact(new Cart(name, price,image_new,model, product,value));
} catch (Exception e) {
}
}
Any help would be really appreciable.
Thanks.
Your biggest issue is, that you're using fields instead of local variables.
quant = holder.quantity.getText().toString();
updates quant with every call to getView() so
#Override
public void afterTextChanged(Editable s) {
value = s.toString().trim();
quant.replace(holder.quantity.getText().toString(), value);
updateTable();
}
will use the text field last bound to data and not the the one you added the listener to.
You need to take care of the scope of the variables you're using and introduce consistency to your model.
I would recommend a complete rewrite of the adapter without using any fields.
My ListView has set of rows with Delete Button in each row.
On Click of the delete button must delete particular row from Sqlite Database and refresh the listview.
Problem
I am able to delete row from database. But I am not able to refresh the page after deleting the row.
For refreshing I tried using notifyDatasetChanged(), but no luck.
I could able to see the new list if i got back to previous activity and come back to same activity.
Please find the adapter and class codes below.
MainClass:
public class AddToCart extends AppCompatActivity {
ListView cart_list;
DatabaseHandler db = new DatabaseHandler(this);
Cursor todoCursor;
Context context;
String name, price, image, model;
ArrayList<String> bitmapArray = new ArrayList<String>();
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
Toolbar toolbar;
Button checkout;
static CustomAdapter_cart customAdapter_cart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addtocart);
context = this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
cart_list = (ListView) findViewById(R.id.listview_cart);
checkout = (Button) findViewById(R.id.checkout);
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(AddToCart.this, Signup.class);
startActivity(in);
}
});
Intent i = getIntent();
// Get access to the underlying writeable database
// Query for items from the database and get a cursor back
// todoCursor = db1.rawQuery("SELECT id as _id, * from cart ", null);
// db1.execSQL("DELETE FROM cart");
// Reading all contacts
List<Cart> contacts = db.getAllContacts();
cart_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
for (Cart cn : contacts) {
name = cn.getName();
list_name.add(name);
price = cn.getPhoneNumber();
list_price.add(price);
image = cn.getImage_list();
bitmapArray.add(image);
model = cn.getModel();
list_model.add(model);
}
customAdapter_cart = new CustomAdapter_cart(this, list_name, list_price, bitmapArray, list_model);
cart_list.setAdapter(customAdapter_cart);
}
public static class MyLovelyOnClickListener implements View.OnClickListener
{
CustomAdapter_cart contextnew;
String myLovelyVariable;
Context context;
public MyLovelyOnClickListener(Context contextnew, CustomAdapter_cart context, String tv_model) {
this.contextnew = context;
this.context = contextnew;
this.myLovelyVariable = tv_model;
}
#Override
public void onClick(View v) {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db1.delete("cart", "model = ?", new String[]{myLovelyVariable});
customAdapter_cart.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
}
CustomAdapter.class
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>();
CustomAdapter_cart cart_refresh;
Bitmap b;
View rowView;
Context context;
AddToCart cart;
private static LayoutInflater inflater = null;
Cursor cu;
Context contextnew;
AddToCart.MyLovelyOnClickListener listener;
String model_item;
public CustomAdapter_cart(Context context, ArrayList<String> list_name, ArrayList<String> list_price, ArrayList<String> bitmapArray, ArrayList<String> list_model) {
this.context = context;
this.list_name = list_name;
this.list_price = list_price;
this.list_images = bitmapArray;
this.list_model = list_model;
this.cart_refresh = this;
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;
ImageView image;
Button delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final Holder holder = new Holder();
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.delete = (Button) rowView.findViewById(R.id.delete);
holder.tv_name.setText(list_name.get(position));
holder.tv_price.setText(list_price.get(position));
holder.tv_model.setText(list_model.get(position));
String n = holder.tv_model.getText().toString();
holder.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
// holder.delete.setTag(holder.tv_model);
listener = new AddToCart.MyLovelyOnClickListener(context,CustomAdapter_cart.this,n);
holder.delete.setOnClickListener(listener);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_item = ((TextView) rowView.findViewById(R.id.name_cart)).getText().toString();
String price_item = ((TextView) rowView.findViewById(R.id.price_cart)).getText().toString();
model_item = ((TextView) rowView.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;
}
Any Help would be really helpfull.
Thanks.
you are just deleting a row from database. Your adapter is still having the same set of data. So first update the data set of the adapter and than call notifydatasetchanged()
In my app i have a ListView. Data is populated in ListView using SimpleCursorAdapter. I want ListView to be refreshed automatically whenever there is change in database or when i click button. I have tried adapter.notifyDataSetChanged() but its not effective.i couldn,t findout a good solution. I want ListView to be refreshed whenever user enters value in EditText and then press Send Button and save entered data in SQLite database. Here is my Code :
public class chatCursor extends Activity {
static MyListAdapter adapter;
ArrayList<String> item_id;
ArrayList<String> item_phone_num;
ArrayList<String> item_msg_body;
ArrayList<String> item_time;
ArrayList<String> item_flag;
ArrayList<String> items;
private Button btn_send;
DbManager manager;
Cursor Cursor;
//ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";
ListView lv_chat;
String[] from = new String[]{"Message_body","Time"};
int[] toIDs = new int[]{R.id.msg_body,R.id.time};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Bundle bundle = getIntent().getExtras();
contact_for_chat = bundle.getString("contact_name");
contact_for_chat = contact_for_chat.replace(" ", "");
contact_no = Util.getContactNumber(contact_for_chat, chatCursor.this);
Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
manager = new DbManager(this);
Cursor = manager.Return_SMS(contact_for_chat);
c = Calendar.getInstance();
sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
time = sdf.format(c.getTime());
item_id = new ArrayList<String>(Cursor.getCount());
item_phone_num = new ArrayList<String>(Cursor.getCount());
item_msg_body = new ArrayList<String>(Cursor.getCount());
item_time = new ArrayList<String>(Cursor.getCount());
item_flag = new ArrayList<String>(Cursor.getCount());
findViews();
showList();
//setActionBar();
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SendSMS();
showList();
}
});
lv_chat.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
int itemId = Integer.valueOf(String.valueOf(position));
}});
}
private void showList() {
showEvents(Cursor);
adapter = new MyListAdapter(this,R.layout.activity_chat,
Cursor,
from,
toIDs);
lv_chat.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void findViews() {
et_chat = (EditText)findViewById(R.id.et_chat);
btn_send = (Button)findViewById(R.id.button1);
lv_chat = (ListView)findViewById(R.id.list);
lv_chat.setDivider(this.getResources().getDrawable(android.R.color.transparent));
}
protected void SendSMS() {
SmsManager sms_manager = SmsManager.getDefault();
message_body = et_chat.getText().toString();
ArrayList<String> parts = sms_manager.divideMessage(message_body);
sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
flag = "1";
manager.Insert_sms_data(time, contact_for_chat, message_body,flag);
if(message_body.length()>0)
{
et_chat.setText("");
}
showList();
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_LONG).show();
private void showEvents(Cursor cursor) {
int i=0;
while (cursor.moveToNext()) {
item_id.add(i+"");
item_time.add(cursor.getString(1));
item_msg_body.add(cursor.getString(3));
item_phone_num.add(cursor.getString(2));
item_flag.add(cursor.getString(4));
i++;
}
}
public class MyListAdapter extends SimpleCursorAdapter {
Cursor myCursor;
Context myContext;
public MyListAdapter(Context context, int layout,
Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
myCursor = c;
myContext = context;
}
public int getCount() {
return item_msg_body.size();
}
public Object getItem(int position) {
return item_msg_body.get(position);
}
public long getItemId(int position) {
return item_msg_body.get(position).hashCode();
}
public View getView(final int position, View arg1, ViewGroup arg2) {
View v = arg1;
ViewHolder holder = null;
if (v == null) {
LayoutInflater layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_chat, null);
holder = new ViewHolder();
// holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
holder.tv_time = (TextView) v.findViewById(R.id.time);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
if(item_flag.get(position).equals("1"))
{
RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
RelativeLayout.LayoutParams dateparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dateparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
dateparams.addRule(RelativeLayout.BELOW, R.id.msg_body);
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);
holder.tv_sms_body.setLayoutParams(params);
holder.tv_time.setLayoutParams(dateparams);
}
else if(item_flag.get(position).equals("0"))
{
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);
}
//holder.tv_contact.setText("" + item_phone_num.get(position));
holder.tv_sms_body.setText(item_msg_body.get(position));
holder.tv_time.setText(item_time.get(position));
return v;
}
}
public class ViewHolder {
private TextView tv_contact;
private TextView tv_sms_body;
private TextView tv_time;
}
}
Any help will will be appreciated .Thanks in advance
call adapter.notifydatasetchanged() method to refresh listview
i am fetching the menunames from mysql database and append to edittext in custom listview using base adapter.now i am change some menunames in editext values. now i want get all editext from first to last
Eg:x,y,z,.... are menunames coming from database it append editext(cusom listview)
i am change editext value y to b
now i want x,b,z...... values in arraylisst..
my base adapger class
public class EditMainMenulistview extends BaseAdapter {
public final ArrayList<String> arr = new ArrayList<String>();
protected static Context Context = null;
int i;
public String editnewmainmenu, menuname, edittext;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, itemcode;
public String[] itemnames, itemcodes;
HashMap<String, String> map = new HashMap<String, String>();
public EditMainMenulistview(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.itemcodes = new String[imageArrayJson.length()];
try {
for (i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("menuimage");
itemname = image.getString("menuname");
itemcode = image.getString("menucode");
itemnames[i] = itemname;
itemcodes[i] = itemcode;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(itemnames[i]);
} catch (Exception e) {
// TODO: handle exception
}
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.editmainmenulist, null);
holder.caption = (EditText) convertView
.findViewById(R.id.editmaimenu);
holder.caption1 = (ImageView) convertView
.findViewById(R.id.menuimage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Fill EditText with the value you have in data source
holder.caption.setText(itemnames[position]);//i append menunames here
holder.caption.setId(position);
holder.caption1.setImageBitmap(bmps[position]);
// we need to update adapter once we finish with editing
arr.add(holder.caption.getText().toString());//here i am try to get all values change and without edit text values but it get only menunames values
return convertView;
}
}
class ViewHolder {
EditText caption;
ImageView caption1;
}
class ListItem {
String caption;
}
please help me
I think you will need to Use OnTouch for EditText to get it Id and add TextWatcher to get Editext in that EditText.
Here is Example for Touch Listener in EditText
OnTouchListener mEdittextTouchListener = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int childPosition = v.getId;
Log.i("Log_tag", "Edittext Position is " + childPosition);
//Here you will get your EditText Position.
//saveData=true;
//setChildPosition(childPosition);
return false;
}
};
Now implements TextWatcher in your Activity and add modification like this in getView of your BaseAdapter.
holder.caption.removeTextChangedListener(ExpandableListPage.this);
holder.caption.setOnTouchListener(mEdittextTouchListener);
holder.caption.addTextChangedListener(ExpandableListPage.this);
now make sure to first remove TextWatcher from EditText and add it .Because when your listview view is going to show EditText will call TextWather Method ,to prevent this we always need to Remove it and then add it.
#Override
public void afterTextChanged(Editable s) {
Log.v("Log_tag", "After TextChanged" + s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
Log.i("Log_tag", "Before TextChanged" + s.toString());
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.e("Log_tag", "ontext Changed"+ s.toString());
if(count!=0){
if(saveData){
//Add your EditText Change Value here
arr.add(s.toString());
}
}
}
}