ListView won't refresh using notifyDataSetChanged - android

I'm trying to refresh the listview from the adapter class ( non activity class) I tried notifyDataSetChanged() but it wont work , I also tried to call the displayListView() in the adapter class but it crashes as well
this is my displayListView() Method in The ActivityClass
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[]{
DBAdapter.qty,
DBAdapter.price,
DBAdapter.PRODUCT_NAME
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.qtyL,
R.id.priceL,
R.id.PRODUCT_NAMEL
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.country_inf,
cursor,
columns,
to,
0);
HorizontalListView listView = (HorizontalListView) findViewById(R.id.cartCeckOutList);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
And this is the Adapter Class I use
package com.abdullahadhaim.finegrillresturant.adater;
public class CustomListAdapter extends BaseAdapter {
Context c;
// DBHelper myDataBaseHelper ;
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
DBAdapter myADapterDB;
WaiterActivity waiterAct;
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#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.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
final TextView title = (TextView) convertView.findViewById(R.id.title);
TextView price = (TextView) convertView.findViewById(R.id.rating);
// myDataBaseHelper=new DBHelper(activity, "CDB", null, 1);
myADapterDB = new DBAdapter(activity);
myADapterDB.open();
waiterAct = new WaiterActivity();
// getting movie data for the row
final Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// price
price.setText("Price: " + "SR " + String.valueOf(m.getPrice()));
Button add = (Button) convertView.findViewById(R.id.button1);
Button plus = (Button) convertView.findViewById(R.id.plus_butt);
Button minus = (Button) convertView.findViewById(R.id.minus_butt);
final EditText qty = (EditText) convertView
.findViewById(R.id.editText1);
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String the_qty = qty.getText().toString();
int my_qty = Integer.parseInt(the_qty) + 1;
qty.setText(my_qty + "");
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String the_qty = qty.getText().toString();
int my_qty = Integer.parseInt(the_qty) - 1;
qty.setText(my_qty + "");
}
});
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int myQTY = Integer.parseInt(qty.getText().toString());
String myTitle = m.getTitle().toString();
String myCategory = m.getCategory().toString();
int myCategoryN = m.getOrderNum();
double myPrice = m.getPrice() * myQTY;
if (myQTY == 0)
Toast.makeText(activity, "Orders Must be 1 Atleast",
Toast.LENGTH_SHORT).show();
else {
myADapterDB.checkIfExcist(activity, "productName", myTitle,
myQTY, myPrice, m.getPrice(), myTitle, myCategory,
myCategoryN + "", myQTY);
myADapterDB.deleteZeroOrLessValues();
}
}
});
return convertView;
}
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
}

take a look at Loaders. I think this is the prefered way to load data from datebase into views. With Loaders you get callbacks if the data has changed and the view is updated for you.
http://developer.android.com/guide/components/loaders.html
Here is a good tutorial I think:
http://code.tutsplus.com/tutorials/android-fundamentals-properly-loading-data--mobile-5673

Related

Android custom listview layout

im new to android and java programming. Im having trouble getting my custom layout (currently with only one textview in it to work with my code. I have followed many tutorials and look and many examples but still Im getting confused as to how I would integrate it with my existing code.
Any help would be appreciated.
Here is my code:
public class checkListActivity extends MainActivity {
static String filename = "checkList";
String currentList;
SharedPreferences checkListData;
SharedPreferences.Editor checkListEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist);
Button bAddItem = (Button) findViewById(R.id.bAddItem);
final EditText etItemName = (EditText) findViewById(R.id.etItemName);
final TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckLists);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String selectedItem = extras.getString("selectedItem");
// get the value based on the key
currentList = selectedItem;
}
tvTitle.setText(currentList);
checkListData = getSharedPreferences(filename, 0);
updateListView();
// Button Click Listener
bAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String checkListStringData = etItemName.getText().toString();
checkListData = getSharedPreferences(filename, 0);
SharedPreferences.Editor checkListEditor = checkListData.edit();
checkListEditor.putString(currentList + "ItemName",
checkListStringData);
checkListEditor.commit();
String checkListDataReturned = checkListData.getString(
currentList + "ItemName", currentList);
tvTitle.setText(checkListDataReturned);
updateListView();
etItemName.setText("");
};
});
}
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String, ?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getValue() instanceof String) {
if (entry.getKey().equals(currentList + "ItemName")) {
checkListStrings.add((String) entry.getValue());
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, R.layout.single_listview_item);
lvCheckList.setAdapter(checkListArrayAdapter);
}
}
}
first create this custom adapter class...
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public Context con;
public String[] sms;
public EfficientAdapter(Context context,String[] rssFeed) {
mInflater = LayoutInflater.from(context);
this.con=context;
this.sms=rssFeed;
}
public int getCount() {
return sms.length;
}
public Object getItem(int position) {
return sms[position];
}
public long getItemId(int position) {
return position;
}
#SuppressLint({ "SdCardPath", "InflateParams", "ResourceAsColor" })
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text_list_f);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text2.setText(sms[position]);
}
return convertView;
}
}
static class ViewHolder {
TextView text2;
}
then use it in your activity ...
list.setAdapter(new EfficientAdapter(this, your array));

ListView disappears after reloading it again

I have 3 arraylist that i have combined to show in listview. Wehen i click on to generate listview, it works fine the first time but when i hit back and then click the button again, the listview shows nothing. Not sure what is cause it. I checked other post but couldnt find an answer. I am not too good with Arraylist so any details would be greatly appreciated.
I have also noticed this message in Log cat. not sure what it means.
onVisibilityChanged() is called, visibility : 0
public class Edit extends Activity implements OnItemClickListener {
private int pic;
public String filename ="User Info";
//Declaring SHareddPreference as userprofile
static SharedPreferences userprofile;
ListView listView;
List<RowItem> rowItems;
// String[] titles, descriptions;
File imgpath=null;
Context context=this;
CustomListAdapter adapter;
private List<String> Titles = new ArrayList<String>();
private List<String> Actions = new ArrayList<String>();
private List<Bitmap> Images = new ArrayList<Bitmap>();
int x;
int y=1;
int z=1;
static int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aname);
listView = (ListView)findViewById(R.id.listing);
userprofile = getSharedPreferences(filename,0);
Intent pdf=getIntent();
pic= userprofile.getInt("lastpic",pic);
x=pic;
Log.d("editpic",new Integer(pic).toString());
while(y!=x){
String comment = commentresult();
Titles.add(comment);
y++;
Log.d("y",new Integer(y).toString());
}
while(z!=x){
String act = actionresult();
Actions.add(act);
z++;
Log.d("z",new Integer(z).toString());}
while(a!=x){
Bitmap photo = getbitmap();
Images.add(photo);
a++;
Log.d("a",new Integer(a).toString());}
Titles.toArray();
Actions.toArray();
Images.toArray();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < Images.size(); i++) {
RowItem item = new RowItem(Images.get(i), Titles.get(i),Actions.get(i));
rowItems.add(item);
}
Log.d("TAG", "listview null? " + (listView == null));
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.aname_list_item, rowItems);
Log.d("TAG", "adapter=null? " + (adapter == null));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
public static Bitmap getbitmap() {
String photo1 =userprofile.getString("picpath"+a, "");
File imgpath=new File(photo1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp=DecodeImage.decodeFile(imgpath, 800, 1000, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Bitmap photo2=bmp;
return photo2;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public String commentresult()
{
// String com2 = null;
// while(y!=x){
String comment=userprofile.getString("comment"+y, "");
String com1=comment;
String com2=com1;
// }
return com2;
}
public String actionresult()
{
// String act2 = null;
// while(y!=x){
String action=userprofile.getString("action"+z, "");
String act1=action;
String act2=act1;
// }
return act2;
}
private static final long delay = 2000L;
private boolean mRecentlyBackPressed = false;
private Handler mExitHandler = new Handler();
private Runnable mExitRunnable = new Runnable() {
#Override
public void run() {
mRecentlyBackPressed=false;
}
};
#Override
public void onBackPressed() {
//You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
if (mRecentlyBackPressed) {
mExitHandler.removeCallbacks(mExitRunnable);
mExitHandler = null;
super.onBackPressed();
}
else
{
mRecentlyBackPressed = true;
Toast.makeText(this, "press again to exit", Toast.LENGTH_SHORT).show();
mExitHandler.postDelayed(mExitRunnable, delay);
}
}
#Override
public void onDestroy() {
// Destroy the AdView.
super.onDestroy();
}
Custom List Adapter:
public class CustomListAdapter extends ArrayAdapter<RowItem> {
Context context;
List<RowItem> items;
public CustomListAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public RowItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.aname_list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.rab);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// String name=items.get(position).getDesc();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageBitmap(rowItem.getImageId());
// holder.imageView.setImageResource(Images.get(position) .getPlaceholderleft());
return convertView;
}
}
It looks like this is because you've made your variables x, y, z and a all static, which means there is a single instance of the variables shared by all instances of the class. Therefore, when you call onCreate the second time, all your while loop termination conditions are already met, so the while loops never execute. It's unclear to me why you've made these static, so unless you need them to be, you should remove the static keyword for these variables.
Why are you creating another object of ListView in onCreate() and onResume()
Remove code from onResume()
Also replace this line in onCreate()
old line ListView listView = (ListView)findViewById(R.id.listing);
New line listView = (ListView)findViewById(R.id.listing);

Custom BaseAdapter wont add new Data - Android

I have a custom baseadapter that creates comment boxes. Everything works great on it until I want to add data. When I try to add the data it deletes the previous data and adds the new data. How do I make it so it keeps all the data? Is my Add method incorrect? Here is my baseadapter,
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
Setting the adapter:
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
This is what how I call the add method,
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
In your add method you're setting the arrays to new values listComments = comments; That's replacing your old data with the new data.
You could use System.arrayCopy() to resize your listArrays to the new size and append the new items. A much less tedious approach, however, would be to store your arrays as List<String>, allowing you to add more items without worrying about resizing lists.
The result would look something like this...
public class CommentsAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private List<String> comments;
private List<String> numbers;
private List<String> usernames;
public CommentsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
comments = new ArrayList<String>();
numbers = new ArrayList<String>();
usernames = new ArrayList<String>();
}
public void add(String[] comments, String[] numbers, String[] usernames)
{
this.comments.addAll(Arrays.asList(comments));
this.numbers.addAll(Arrays.asList(numbers));
this.usernames.addAll(Arrays.asList(usernames));
notifyDataSetChanged();
}
#Override
public int getCount()
{
if (comments == null)
return 0;
return comments.size();
}
#Override
public String getItem(int position)
{
return comments.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.commentView.setText(comments.get(position));
//Other view bind logic here...
return convertView;
}
private static class ViewHolder
{
public TextView commentView;
public TextView numbersView;
public TextView usernamesView;
public Button usernameButton;
public Button numberButton;
public ViewHolder(View v)
{
commentView = (TextView) v.findViewById(R.id.listComment);
numbersView = (TextView) v.findViewById(R.id.listNumber);
usernamesView = (TextView) v.findViewById(R.id.listPostedBy);
usernameButton = (Button) v.findViewById(R.id.listUsernameButton);
numberButton = (Button) v.findViewById(R.id.listNumberButton);
}
}
}
I also highly recommend reading this page on the Android Developer's site: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Your current adapter implementation is very inefficient, and that page should help you iron out some kinks.
You probably need to add the String[] array to the existing one, instead of replacing it.
Add this function which joins two arrays (Sadly there is no already-implemented method for Java):
String[] concat(String[] A, String[] B) {
String[] C= new String[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
Credits: Sun Forum
And then change the add method to this:
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = concat(listComments, comments);
listUsernames = concat(listUsernames, usernames);
listNumbers = concat(listNumbers, numbers);
}
And you had a typo in your code. In the add method, the listUsernames and listNumbers should be swapped I think.. I fixed it for you.

Unable to refresh database after deleting a row

I am using SQLiteDatabase in android. I am not able to refersh my listview after deleting a row.
My code is as follows:
public void delete(String i) {
// TODO Auto-generated method stub
String [] columns= new String[]{KEY_ROW_ID,KEY_FHR,KEY_ID,KEY_NAME,KEY_AGE};
Cursor c= our_db.query(KEY_TABLE, columns, null, null,null, null, null);
our_db.delete(KEY_TABLE, KEY_NAME+ "="+"\'"+i+"\'", null) ;
c.requery();
}
I call it from a viewholder in efficientadapter. Below is the code where I call it:
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
}
});
Can anyone help me finding out the problem. It doesn't give any error. it just deleted the row but doesn't update the view.
Here is the adapter i used:
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2;
private Bitmap mIcon3;
private Bitmap mIcon4;
Context c;
int window;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.c=context;
// Icons bound to the rows.
mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_2);
mIcon3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.del1);
mIcon4 = BitmapFactory.decodeResource(context.getResources(), R.drawable.edit);
}
public int getCount() {
return DATA.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
//int i=0;
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.del=(ImageView)convertView.findViewById(R.id.icon1);
holder.edit=(ImageView)convertView.findViewById(R.id.icon2);
window=position;
holder.text.setOnClickListener(new OnClickListener() {
private int pos=position;
//private int pos = position;
public void onClick(View v) {
System.out.println(window);
sql_get db = new sql_get(c);
db.open();
String ret_id= db.getid(DATA[pos]);
String ret_name = db.getname(DATA[pos]);
String ret_age= db.getage(DATA[pos]);
String ret_fhr= db.getfhr(DATA[pos]);
String[] result = {ret_id,ret_name,ret_age,ret_fhr};
db.close();
Bundle b=new Bundle();
b.putStringArray("key",result);
Intent i =new Intent(c,Tabs.class);
i.putExtras(b);
c.startActivity(i) ;
Toast.makeText(c, getItemId(position)+""+" Click- text " +pos+" "+ret_name, Toast.LENGTH_SHORT).show();
}
});
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
Toast.makeText(c, "deleting " + DATA[pos], Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
}
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
holder.del.setImageBitmap(mIcon3);
holder.edit.setImageBitmap(mIcon4);
return convertView;
static class ViewHolder {
ImageView del;
TextView text;
ImageView icon;
ImageView edit;
}
}
You need to delete the row also from the object holding the data for the list view..
I think you also have to remove the same data from adapter and then use your_adapter.notifyDataSetChanged() method. That worked for me...
I found the solution. As said above, I had to change the DATA object.
I used the following commands to achieve it.
db.open();
db.delete(DATA[pos]);
DATA=db.getdata();
DATA_NAME=db.getname();
DATA_AGE=db.getage();
DATA_FHR=db.getfhr();
db.close();

My ListView consist an ImageView and a TextView i need to get the Text from the TextView

My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..

Categories

Resources