Delete row view from custom list using base Adapter solution - android

Hi I can not delete a row from list View i don't know how to delete it i search a lot from Internet i try out many examples but yet i can't solve the issue . when i click the hldr.delete button the complete row of list View delete from the list solution pls.
PlaceOrder Activity
public class PlaceOrder extends Activity {
String [] pIds;
String [] pNames;
String [] pPrizes;
static ListView lv;
ImageView bck;
String [] listImages;
String food_id;
String userdata[];
Intent i;
TextView totalprze;
float tprize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
lv=(ListView)findViewById(R.id.cart_list);
bck=(ImageView) findViewById(R.id.placeholder_bg_btn);
totalprze =(TextView) findViewById(R.id.place_order_price);
i=new Intent(this,Menu.class);
bck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle=new Bundle();
//bundle.putStringArray("images", ListImages);
bundle.putString("food_id", food_id);
bundle.putStringArray("images", listImages);
bundle.putStringArray("userData",userdata);
i.putExtras(bundle);
startActivity(i);
}
});
if(this.getIntent().getExtras()!=null)
{
Bundle b=this.getIntent().getExtras();
pIds=b.getStringArray("pId");
pNames=b.getStringArray("PName");
pPrizes=b.getStringArray("pPrize");
userdata=b.getStringArray("userData");
tprize=b.getFloat("totalprize");
food_id=b.getString("food_id");
listImages=b.getStringArray("images");
String prz=Float.toString(tprize);
totalprze.setText("$"+prz);
lv.setAdapter(new cartAdapter(PlaceOrder.this, pIds, pNames, pPrizes,userdata));
pIds=null;
pNames=null;
pPrizes=null;
}
}
public void onBackPressed() {
pIds=null;
pNames=null;
pPrizes=null;
}
}
CartAdapter
public class cartAdapter extends BaseAdapter{
String [] pIdz;
String [] pNamz;
String [] pPrizs;
String [] userData;
// List<String> imges;
Context context;
// private ShopingCartHelper obj;
private static LayoutInflater inflater=null;
JSONArray jCat = null;
int count=0;
ProgressDialog pDialog;
public cartAdapter(PlaceOrder ctx,
String[] pIds,String[] pNams, String[] pprise,String [] userdata) {
pIdz=pIds;
pNamz=pNams;
context=ctx;
pPrizs=pprise;
userData=userdata;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
if(pIdz==null){
Toast.makeText(context, "There is issue with net connection.", Toast.LENGTH_LONG).show();
//Intent i=new Intent(context,WelcomeActivity.class);
//context.startActivity(i);
return count ;
}else{
return pIdz.length;
}
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class holder{
TextView pid;
TextView pname;
TextView pprise;
Button delete;
ListView lv;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final holder hldr=new holder();
View rowView = null;
Bitmap bitmap = null;
rowView = inflater.inflate(R.layout.place_order_item_list, null);
hldr.pid=(TextView) rowView.findViewById(R.id.item_id);
hldr.pname=(TextView) rowView.findViewById(R.id.item_name);
hldr.pprise=(TextView) rowView.findViewById(R.id.item_price);
hldr.delete=(Button) rowView.findViewById(R.id.delete);
hldr.pid.setText(pIdz[position]);
hldr.pname.setText(pNamz[position]);
hldr.pprise.setText(pPrizs[position]);
/* convertView.setTag(hldr);
hldr.delete.setTag(hldr);*/
//
// Picasso.with(context).load(imgs[position]).into(hldr.img);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// rowView.remove(position); //removing from your List
//Toast.makeText(context, "Delete",Toast.LENGTH_LONG).show();
int pid=Integer.parseInt(hldr.pid.getText().toString());
//Toast.makeText(context, "pid"+pid, Toast.LENGTH_LONG).show();
new ShopingCartHelper(context).delProduct(pid);
//PlaceOrder.lv.removeViewAt(position);
notifyDataSetChanged();
}
});
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// // TODO Auto-generated method stub
// cartAdapter.this.pIdz.remove[position];
// Toast.makeText(context, "hi",Toast.LENGTH_LONG).show();
}
});
return rowView;
// TODO Auto-generated method stub
}
}

You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3. And if you want to delete from the listview the array which you are used should be dynamic(Adding & Deleting). So make the pIdz; pNamz;pPrizs;userData into some Modal Object, and prepare the list of Modal Objects and pass it to adapter and make the life easier
You'd be better off with a List, e.g. an ArrayList:
hldr.delete.setTag(position);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position = (int)v.getTag();
list.remove(position);
notifyDataSetChanged();
}
});

First.
You should make a object that stores all your different strings instead of using multiple arrays for each value.
Ej:
class MyClass
{
String id;
String name
String price;
public MyClass(String id, String name, String price)
{
this.id = id;
this.name = name;
this.price = price;
}
}
That way you wouldnt have to delete the position of each of the arrays.
And finally to answer your question, just delete the value of position you want to delete for each of the arrays.
Since they are Array and not ArrayList you will need to recreate it with the correct new dimension (Note it will be much easier with ArrayList).
Then just call notifyDataSetChanged() on your Adapter class.
Hope this helps.

Related

Custom ListViews,ArrayLists,ArrayAdapters

I'm trying to build an Attendance Manager app for students and am using a custom ListView to display subject names and minimum attendance when tapped on.
These are the Issues I'm facing::
1) I want my first list item to be an "Add a subject item" and on tapping on that it goes to AddSubjectActivity and stores everything via SharedPreferences.
2)Once the submit button is pressed in the AddSubjectActivity i want the next list item to say "Tap to add a subject" and so on.
3) Basically ,suppose the ListView has 5 items, tapping on each item takes me to the AddSubject Activity, but information corresponding to the respective list Item being tapped is displayed in it.
This is my Code:
Class CustomAdapter
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(SecondActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
SecondActivity second=new SecondActivity();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView);
holder.img=(ImageView) rowView.findViewById(R.id.statsImageView);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
context.startActivity(new Intent(context, AddSubject.class));
}
});
return rowView;
}
}
SecondActivity: The Activity that contains the ListView
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle=getIntent().getExtras();
String fullNameFinal = bundle.getString("fullName");
String courseFinal = bundle.getString("course");
int avgAttendanceFinal= bundle.getInt("avgAttendance");
boolean logInStatusFinal = bundle.getBoolean("logInStatus");
nameTextView=(TextView)findViewById(R.id.nameTextView);
courseTextView=(TextView)findViewById(R.id.courseTextView);
nameTextView.setText(fullNameFinal);
courseTextView.setText(courseFinal);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
ListView lv;
Context context;
ArrayList prgmName;
int [] prgmImages={R.drawable.listblockgold,R.drawable.listblockindigo,R.drawable.listblocklime,R.drawable.listblockorange,R.drawable.listblockpink,R.drawable.listblockred,R.drawable.listblocksilver,R.drawable.listblocktan,R.drawable.listblockteal};
String [] prgmNameList={"Maths","P.Comm.","IOT","Operating Systems","Web Programming","DSP","PHP","Jquery","JavaScript"};
context=this;
lv=(ListView) findViewById(R.id.testListView);
lv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages));
`AddSubject Activity`
public class AddSubject extends AppCompatActivity {
//Buttons
Button missedMinus;
Button missedPlus;
//ButtonsEnd
//TextViews
TextView safeBunksNumber;
TextView missedLectures;
TextView totalLecturesTextView ;
TextView percentageTextView;
//TextViewsEnd
EditText missedLecturesTextView;
ProgressBar progressBar;
static String s= Integer.toString(10);
public void missedMinusClick(View view)
{
totalLecturesTextView=(TextView)findViewById(R.id.totalLecturesTextView);
int totalLectures= Integer.parseInt(totalLecturesTextView.getText().toString());
missedLecturesTextView=(EditText)findViewById(R.id.missedLecturesTextView);
int missedLectures= Integer.parseInt(missedLecturesTextView.getText().toString());
missedLecturesTextView.setText(Integer.toString(missedLectures-1));
safeBunksNumber=(TextView)findViewById(R.id.safeBunksNumber);
int safeBunksNumber;
}
public void missedPlusClick(View view2)
{
missedLecturesTextView=(EditText)findViewById(R.id.missedLecturesTextView);
int missedLectures= Integer.parseInt(missedLecturesTextView.getText().toString());
missedLecturesTextView.setText(Integer.toString(missedLectures+1));
}
public void submitOnClick1(View view3)
{
EditText subName = (EditText)findViewById(R.id.subName);
EditText totalLecturesTextView = (EditText)findViewById(R.id.totalLecturesTextView);
EditText missedLecturesTextView =(EditText)findViewById(R.id.missedLecturesTextView);
String subjectName = subName.getText().toString();
int totalLectures = Integer.parseInt(totalLecturesTextView.getText().toString());
int missedLectures = Integer.parseInt(missedLecturesTextView.getText().toString());
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.yashrandive.attendancemanager", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("subName",subjectName);
sharedPreferences.edit().putInt("totalLectures",totalLectures);
sharedPreferences.edit().putInt("missedLectures",missedLectures);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_subject);
}
}

Is there way to delete complete row from getView?

Hi there I am facing issue when deleting row view from list. I just create a place order activity and there I register list and then create a class of cart Adapter.
When I delete the row it generates the exception can't delete the row. Is there any solution?
PlaceOrder.java
public class PlaceOrder extends Activity {
String [] pIds;
String [] pNames;
String [] pPrizes;
static ListView lv;
ImageView bck;
String [] listImages;
String food_id;
String userdata[];
Intent i;
Intent intent;
TextView totalprze;
float tprize;
ProgressDialog pDialog;
TableRow p_order;
AlertDialog.Builder builder;
List<String> cart=new ArrayList<String>();
String [] pId;
String [] PName;
String [] pPrize;
Intent intent_one;
String userid;
String status,message;
String [] delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
lv=(ListView)findViewById(R.id.cart_list);
bck=(ImageView) findViewById(R.id.placeholder_bg_btn);
totalprze =(TextView) findViewById(R.id.place_order_price);
p_order=(TableRow)findViewById(R.id.p_order);
intent=new Intent(this,Food.class);
builder = new AlertDialog.Builder(this);
p_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
builder.setMessage(Html.fromHtml("<b>Place Order</b>"+"<br>Do you want to continue ?"))
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Cursor cursor = new ShopingCartHelper(PlaceOrder.this).getData(userid);
// Toast.makeText(getApplicationContext(), "View Cart",Toast.LENGTH_LONG).show();
if (cursor .moveToFirst()) {
while (cursor.isAfterLast() == false) {
String pid = cursor.getString(cursor
.getColumnIndex("id"));
String pName = cursor.getString(cursor
.getColumnIndex("product_name"));
String prize = cursor.getString(cursor
.getColumnIndex("price"));
cart.add(pid);
cart.add(pName);
// System.out.print("Product Name "+pName+"Price"+prize+"id"+id+"\n");
cart.add(prize);
cursor.moveToNext();
}
int length=cart.size();
pId=new String[cart.size()/3];
PName=new String[cart.size()/3];
pPrize=new String[cart.size()/3];
//System.out.print(length+"\n\n\n\n Values of List \n\n\n\n");
int k=0;
String[] values=cart.toArray(new String[cart.size()]);
// System.out.print("Values are :\n\n"+values);
int count=0;
for(int j=0;j<values.length/3;j++){
pId[j]=values[count];
count=count+1;
PName[j]=values[count];
count=count+1;
pPrize[j]=values[count];
count=count+1;
}
for(int i=0;i<pPrize.length;i++){
System.out.println(pPrize[i]);
}
}
// Toast.makeText(getApplicationContext(), "Yes",Toast.LENGTH_SHORT).show();
new place_order().execute();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
);
AlertDialog d = builder.create();
// d.setTitle("Are you sure");
d.show();
TextView messageText = (TextView)d.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
}
});
i=new Intent(this,Menu.class);
bck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle=new Bundle();
//bundle.putStringArray("images", ListImages);
bundle.putString("food_id", food_id);
bundle.putStringArray("images", listImages);
bundle.putStringArray("userData",userdata);
i.putExtras(bundle);
startActivity(i);
}
});
if(this.getIntent().getExtras()!=null)
{
Bundle b=this.getIntent().getExtras();
pIds=b.getStringArray("pId");
pNames=b.getStringArray("PName");
pPrizes=b.getStringArray("pPrize");
userdata=b.getStringArray("userData");
tprize=b.getFloat("totalprize");
food_id=b.getString("food_id");
listImages=b.getStringArray("images");
String prz=Float.toString(tprize);
totalprze.setText("$"+prz);
delete=new String[pIds.length];
for(int m=0;m<pIds.length;m++){
delete[m]="Delete";
}
lv.setAdapter(new cartAdapter(PlaceOrder.this, pIds, pNames, pPrizes,userdata,delete));
userid=userdata[0];
pIds=null;
pNames=null;
pPrizes=null;
}
}
public void onBackPressed() {
pIds=null;
pNames=null;
pPrizes=null;
}
}
Cart Adapter.java
public class cartAdapter extends BaseAdapter{
String [] pIdz;
String [] pNamz;
String [] pPrizs;
String [] userData;
String [] del;
// List<String> imges;
Context context;
DrawerLayout dLayout;
// private ShopingCartHelper obj;
//ListView dList;
private static LayoutInflater inflater=null;
JSONArray jCat = null;
int count=0;
ProgressDialog pDialog;
public cartAdapter(PlaceOrder ctx,
String[] pIds,String[] pNams, String[] pprise,String [] userdata, String[] delete) {
pIdz=pIds;
pNamz=pNams;
context=ctx;
pPrizs=pprise;
userData=userdata;
del=delete;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
if(pIdz==null){
Toast.makeText(context, "There is issue with net connection.", Toast.LENGTH_LONG).show();
//Intent i=new Intent(context,WelcomeActivity.class);
//context.startActivity(i);
return count ;
}else{
return pIdz.length;
}
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class holder{
DrawerLayout dLayout;
TextView pid;
TextView pname;
TextView pprise;
Button delete;
ListView lv;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final holder hldr=new holder();
View rowView = null;
rowView = inflater.inflate(R.layout.place_order_item_list, null);
//hldr.dLayout= (DrawerLayout)rowView.findViewById(R.id.btn_drawer_layout);
// hldr.dLayout=(DrawerLayout)rowView.findViewById(R.id.btndrawerLayout);
hldr.pid=(TextView) rowView.findViewById(R.id.item_id);
hldr.pname=(TextView) rowView.findViewById(R.id.item_name);
hldr.pprise=(TextView) rowView.findViewById(R.id.item_price);
hldr.delete=(Button) rowView.findViewById(R.id.delete);
hldr.pid.setText(pIdz[position]);
hldr.pname.setText(pNamz[position]);
hldr.pprise.setText(pPrizs[position]);
hldr.delete.setText(del[position]);
hldr.delete.setTag(position);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pid=Integer.parseInt(hldr.pid.getText().toString());
new ShopingCartHelper(context).delProduct(pid);
pIdz[position]=null;
pNamz[position]=null;
pPrizs[position]=null;
del[position]=null;
// new PlaceOrder().updateAdapter(context,pIdz,pNamz,pPrizs,del);
//
notifyDataSetChanged();
}
});
return rowView;
// TODO Auto-generated method stub
}
}
Your problem is in CartAdapter.java, you have:
pIdz[position]=null;
pNamz[position]=null;
pPrizs[position]=null;
del[position]=null;
You don't delete the item in list, you only set it to 'null' value. So when call 'notifyDataSetChanged' you made a NullPointerException.
To fix this bug, change all String[] to ArrayList, and easy call Java.util.ArrayList.remove(index)
As you want to remove the row from the list so you have to delete that explicitly for that you should declare Pidz like this
ArrayList<String> Pidz;
And in your cartAdapter constructor
Pidz = Arrays.asList(pIds);
Please modify your onclicklistener like this,
public void onClick(View v) {
int pid=Integer.parseInt(hldr.pid.getText().toString());
new ShopingCartHelper(context).delProduct(pid);
pIdz[position]=null;
pNamz[position]=null;
pPrizs[position]=null;
del[position]=null;
pIdz.remove(position);
notifyDataSetChanged();
}
});

How to update values in database using an update image button in custom list adapter?

This is my custom list adapter. I want to update the values in table using the update ImageButton in the list. On clicking it, the old values should be shown in a new activity and then the edited value must be stored in the database. However, I am unable to pass an intent inside the onClick() method.
Please suggest me a solution
public class CustomListAdapter extends BaseAdapter implements ListAdapter
{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
OnItemSelectedListener onItemSelectedListener;
public int pos;
String pass,pass2,edit,epass;
public CustomListAdapter(List list, Context context) {
this.list = (ArrayList<String>) list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
//pass2 = list.toString();
return list.get(pos);
}
//#Override
//public Long getItemId(int pos) {
//
// //just return 0 if your list items do not have an Id variable.
//}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_custom_list, null);
}
//Handle TextView and display string from your list
final TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
ImageButton editBtn = (ImageButton)view.findViewById(R.id.edit_btn);
//Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position);
pass = listItemText.getText().toString();
notifyDataSetChanged();
pass2 = pass.substring(0,pass.indexOf(' '));
System.out.println(pass2);
Moneydb.delete(pass2);
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
edit=listItemText.getText().toString();
epass = listItemText.getText().toString();
edit = epass.substring(0,epass.indexOf(' '));
Moneydb.edit(edit);
}
});
return view;
}
protected Context getContext() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return list.get(position).getId();
return 0;
}
public void clear() {
//CustomListAdapter collection = null;
// TODO Auto-generated method stub
list.clear();
notifyDataSetChanged();
}
I suggest you to assign and ContextMenu to your list view with two MenuItem, Edit and Delete and write associated code outside of adapter
or you can start Activity by :
Intent new_intent = new Intent(v.getRootView().getContext(),edit_activity.class);
new_intent.putExtra("Key","Value");
v.getRootView().getContext().startActivity(new_intent);
i think the first method is best ;)

How do I get my CustomListAdapter to update on notifyDatasetChange?

This is the first time I am building a Listview with a custom layout, so in case I have missed something obvious please just point it out.
The problem I am having that I cannot get the listview to update itself with new information after the Oncreate(); has been used. So the list is very static.
I am trying to create a custom listview adapter that looks as such:
public class MainListCustomBaseAdapter extends BaseAdapter {
static ArrayList<ListItems> DataSomething;
static Context Cont;
public MainListCustomBaseAdapter (ArrayList<ListItems> data, Context c){
DataSomething = data;
Cont = c;
}
public int getCount() {
// TODO Auto-generated method stub
return DataSomething.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return DataSomething.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)Cont.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.mainlistlayout, null);
}
ImageView image = (ImageView) v.findViewById(R.id.ListImage);
TextView titleView = (TextView)v.findViewById(R.id.title);
TextView DetailItemView = (TextView)v.findViewById(R.id.DetailItem);
ListItems msg = DataSomething.get(position);
image.setImageResource(msg.icon);
titleView.setText(msg.title);
DetailItemView.setText("ItemDetails: "+msg.ItemDetails);
return v;
}
public void updateResults(ArrayList<MainListCustomBaseAdapter> results){
notifyDataSetChanged();
}
}
My Oncreate looks like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecipeList = (ListView) findViewById(R.id.mainListView);
ShoppingItems = new ArrayList<ListItems>();
RecipeList.setAdapter(new MainListCustomBaseAdapter(ShoppingItems, this));
ListItems Detail;
Detail = new ListItems();
Detail.setIcon(R.drawable.food);
Detail.setName("Food Stuff");
Detail.setItemDetails("ItemDetailsComp");
ShoppingItems.add(Detail);
}
and listitem looks like this:
public class ListItems {
public int icon ;
public String title;
public String ItemDetails;
public String getName() {
return title;
}
public void setName(String from) {
this.title = from;
}
public String getItemDetails() {
return ItemDetails;
}
public void setItemDetails(String ItemDetailsComp) {
this.ItemDetails = ItemDetailsComp;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
}
How do I get the listview to update dynamically? with maybe a SetInvalidatedViews() or notifyDatasetchanged()?
Any help is deeply appreciated.
Use the below
MainListCustomBaseAdapter adapter = new MainListCustomBaseAdapter(ShoppingItems, this)
RecipeList.setAdapter(adapter);
To refresh or update listview
adapter.notifyDataSetChanged();
public void notifyDataSetChanged ()
Added in API level 1
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.
put this line after adding the element in the arraylist
RecipeList.setAdapter(new MainListCustomBaseAdapter(ShoppingItems, this));

save editbox values in the custom listview

am having a two editbox. the values enter in that has to placed in the custom listview its working fine for this...
but i want to save this values in the list view permanently.so that if the phones switches off and again run the app then the values have to be saved ..like phone contact number and name have to be saved..
here am ataching the code
public class Editcard extends Activity{
EditText cardname,cardDescription ;
MyApplication app;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editcredit);
app = ((MyApplication) getApplicationContext());
cardname =(EditText)findViewById(R.id.cardash);
cardDescription =(EditText)findViewById(R.id.editdescription);
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
app.carddata =cardname.getText().toString();
System.out.println("Gotcardname"+app.carddata);
app.descriptiondata =cardDescription.getText().toString();
System.out.println("gotDescription"+app.descriptiondata);
app.arryList.add(app.carddata);
app.arryList1.add(app.descriptiondata);
Intent saveIntent =new Intent(Editcard.this,Newcard.class);
startActivity(saveIntent);
}
});
}
}
public class MyApplication extends Application{
ArrayList<String> arryList = new ArrayList<String>();
ArrayList<String> arryList1 = new ArrayList<String>();
String carddata,descriptiondata,=null;
}
public class Newcard extends Activity {
MyAdapter adapter;
ListView listView;
LayoutInflater lay;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newcard);
app = ((MyApplication) getApplicationContext());
TextView newcard =(TextView)findViewById(R.id.newcard);
newcard.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent card = new Intent(Newcard.this,Editcreditcard.class);
startActivity(card);
}
});
listView = (ListView) findViewById(R.id.cardlist);
adapter =new MyAdapter(this, app.arryList,app.arryList1);
listView.setAdapter(adapter);
}
public class MyAdapter extends BaseAdapter {
Context context = null;
ArrayList<String> items= null;
ArrayList<String> items1= null;
public MyAdapter(Newcard newcard, ArrayList<String> items,
ArrayList<String> items1) {
// TODO Auto-generated constructor stub
this.items = items;
this.items1 = items1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items;
//return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View layout = null;
TextView produ = null;
TextView desc = null;
if (convertView == null) {
lay = LayoutInflater.from(getApplicationContext());
layout = lay.inflate(R.layout.customlist, null);
} else {
layout = convertView;
}
produ = (TextView) layout.findViewById(R.id.card);
produ.setText("" +app.arryList.get(position));
desc= (TextView) layout.findViewById(R.id.descrip);
desc.setText("" +app.arryList1.get(position));
return layout;
}
}
}
use can use SharedPreferences, that will save your values permanently, untill they are changed(by changing values in editbox) or user reinstall (clear data) application. Shared Preferences works like this
// save string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("some_key", string); // here string is the value you want to save
editor.commit();
// restore string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
string = settings.getString("some_key", "");

Categories

Resources