Dynamic ListView - Refresh on Button Click - android

Android 2.3.3
I have seen few questions at stackoverflow, regarding refreshing the listview. But none of them worked for me.
I have a dynamic listview and I have a button inside it. The data is being populated from database and each listview row is a custom layout. On press of the (Clear) button, the database is cleared(which works fine) and the listview should get refreshed(the part to be figured out).
Below is the code...
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.mobilevoiceapps.advancedvoicecalculatorfree.R;
public class History extends ListActivity {
ListView lvHistory;
ArrayAdapter<String> adHistory;
ArrayList<String> alHistoryCopy = new ArrayList<String>();
String[] emptyList = { "Your Calculations History is Empty. Please Perform Some Calculations and visit again." };
Database db;
Cursor c;
String expression = "";
String result = "";
boolean isEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// setContentView(R.layout.history);
lvHistory = getListView();
final MyCustomAdapter myad = new MyCustomAdapter();
db = new Database(this);
c = db.retrieve_history();
if (!((c.moveToFirst()) || c.equals(null) || c.getCount() == 0)) {
} else if (c.getCount() > 0) {
c.moveToFirst();
}
LayoutInflater header = getLayoutInflater();
View header_View = header.inflate(R.layout.history_header, null);
lvHistory.addHeaderView(header_View);
View second_Header_View = header.inflate(
R.layout.history_second_header, null);
lvHistory.addHeaderView(second_Header_View);
Button btnClearHistory = (Button) second_Header_View
.findViewById(R.id.btnClearHistory);
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
});
lvHistory.setAdapter(myad);
}
class MyCustomAdapter extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return c.getCount();
}
#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;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
HistoryViewHolder viewHolder;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
convertView = li.inflate(R.layout.history_row, null);
viewHolder = new HistoryViewHolder();
viewHolder.txtcnt = (TextView) convertView
.findViewById(R.id.txtView_History_Count);
viewHolder.txtexp = (TextView) convertView
.findViewById(R.id.txtView_History_Expression);
viewHolder.txtres = (TextView) convertView
.findViewById(R.id.txtView_History_Result);
convertView.setTag(viewHolder);
} else {
viewHolder = (HistoryViewHolder) convertView.getTag();
}
viewHolder.txtcnt.setText(String.valueOf(position + 1));
System.out.println("Position"
+ viewHolder.txtcnt.getText().toString());
c.moveToPosition(position);
expression = c.getString(c.getColumnIndex("expression"));
result = c.getString(c.getColumnIndex("result"));
viewHolder.txtexp.setText(expression);
System.out.println("Expression"
+ viewHolder.txtexp.getText().toString());
viewHolder.txtres.setText(result);
System.out.println("Result"
+ viewHolder.txtres.getText().toString());
return convertView;
}
public class HistoryViewHolder {
TextView txtcnt;
TextView txtexp;
TextView txtres;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (db != null) {
db.close();
}
if (c != null) {
c.close();
}
}
}
EDIT ::: With ScreenShots :::

Try to extend your MyCustomAdapter from BaseAdapter and use notifyDataSetChanged to refresh ListView.
The better way to display database content is CursorAdapter (or CursorLoader) - such adapters listen for update notifications and reloads the content automatically.

try this, You need to refresh you ListView after delete one item using myad.notifyDataSetChanged();
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
YourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
myad.notifyDataSetChanged();
}
});
}
});

Try add c = db.retrieve_history(); after db.clear_history();.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
c = db.retrieve_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
Hope this helped you.

Just restart your activity..
ActivityName.this.finish();
Intent intent=new Intent(this, ActivityName.class);
startActivity(intent);

#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_loja, container, false);
listatividade = (ListView) view.findViewById(R.id.listservico);
String[] valueatividade = new String[] { "atividade 1",
"atividade 2",
"atividade 3" };
adapteratividade = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
listaatividade.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
String itemValue = (String) listaatividade.getItemAtPosition(position);
Toast.makeText(getActivity(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG) .show();
updateData();
}
});
return view;
}
private void updateData() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String[] valueatividade = new String[] { "atividade 4", "atividade 5", "atividade 6" };
adapteratividade = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
}
});
}

Related

Adding and removing the item into wish list like flipkart

I want to add / remove the item into wishlist. I am getting one response from Api, so in that i have one tag is_wishlist=true/false, when I am launching an application based on that value I am showing its in wishlist by changing an icon, but now issue is if am changing that wishlist status like from adding to remobing to adding, in Api i am getting response sucessfully, but i am unable to change the icons. This is my code. can any one help me how to remove or add items into wishlist
package com.example.user.smgapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
public class Prd_grid_adapter extends BaseAdapter {
List<HashMap<String, String>> Category_listData;
HashMap<String, String> map;
Context context;
Typeface face;
String wishList_url, remove_wishList_url;
Cursor cursor;
NavigationDrawer nav = new NavigationDrawer();
private static LayoutInflater inflater = null;
public Prd_grid_adapter(Activity context, List<HashMap<String, String>> aList) {
// TODO Auto-generated constructor stub
Category_listData = aList;
/*/for(int i=1;i<aList.size();i++)
{
Category_listData.add(aList.get(i));
}*/
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Category_listData.size();
}
#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 name, price, original_price;
ImageView img, wish_list;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
final View rowView;
this.face = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
rowView = inflater.inflate(R.layout.grid_item_view, null);
holder.name = (TextView) rowView.findViewById(R.id.p_name);
holder.img = (ImageView) rowView.findViewById(R.id.p_img);
holder.wish_list = (ImageView) rowView.findViewById(R.id.wish_list);
holder.price = (TextView) rowView.findViewById(R.id.p_price);
holder.original_price = (TextView) rowView.findViewById(R.id.orginal_p);
map = Category_listData.get(position);
holder.name.setTypeface(face);
holder.name.setText(map.get("product_name"));
Log.e("wish list staus..", "wishlist status.." + map.get("is_wishlist"));
if (map.get("is_wishlist").equals("0")) {
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
} else {
holder.wish_list.setImageResource(R.drawable.wishlist);
}
holder.wish_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SingletonActivity.custidstr.isEmpty()) {
Toast.makeText(context, "Ur not logged in,Please Login", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert!");
builder.setMessage("Ur not logged in")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, Login.class);
context.startActivity(intent);
}
});
// Create the AlertDialog object and return it
builder.show();
} else {
wishList_url = SingletonActivity.API_URL + "api/add_wishlist.php?customer_id=" + SingletonActivity.custidstr + "&product_id=" + Category_listData.get(position).get("product_id");
remove_wishList_url = SingletonActivity.API_URL + "api/remove_item_wishlist.php?customerid=" + SingletonActivity.custidstr + "&productid=" + Category_listData.get(position).get("product_id");
Log.e("wishlist api..", "wish list api.." + wishList_url);
Log.e("remove wishlist api..", "remove wish list api.." + remove_wishList_url);
v.setActivated(!v.isActivated());
String wish_status = map.get("is_wishlist");
Log.e("wish status..", "wish status.." + wish_status);
int stat = Integer.parseInt(wish_status);
// notifyDataSetChanged();
/*if (wish_status=="Product already exists in wishlist"){
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}
else
{
nav.addTowishList(wishList_url);
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
}*/
if (stat == 0) {
nav.addTowishList(wishList_url);
Toast.makeText(context, "addedd..", Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
// notifyDataSetChanged();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
//
} else {
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
Toast.makeText(context, "removed....", Toast.LENGTH_SHORT).show();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
// notifyDataSetChanged();
}
/* v.setActivated(!v.isActivated());
if (v.isActivated()){
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
nav.addTowishList(wishList_url);
}
else {
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}*/
}
}
});
if (map.get("special_price").equals("0.00")) {
holder.price.setVisibility(View.INVISIBLE);
// holder.o_price.setVisibility(View.INVISIBLE);
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setTextAppearance(context, R.style.product_price_txt);
} else {
holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
/* holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs."+map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);*/
Picasso.with(context).load(map.get("product_image")).placeholder(R.drawable.loading)
.fit().into(holder.img);
return rowView;
}
}
Change this line
holder.wish_list.setImageResource(R.drawable.wishlist);
to this
Resources resources = getResources();
holder.wish_list.setImageDrawable(resources.getDrawable(R.drawable.wishlist));
and do the same in else part and check the output..
Note :
getResources().getDrawable is deprecated.
You can try ContextCompat.getDrawable:
holder.wish_list.setImageDrawable(ContextCompat.getDrawable(context,
R.drawable.wishlist));
UpDate :
check this way.
if(state == true){
// here is default icon and set api value and send it
}else{
// here is click wishlist icon and set api value and send it
}
UpDate 2 :
public class FragmentOne_Adapter extends CursorAdapter {
FragmentOne_DbAdapter dbHelper;
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
dbHelper = new FragmentOne_DbAdapter(context);
dbHelper.open();
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// TODO Auto-generated method stub
final ViewHolder holder = (ViewHolder) view.getTag();
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
holder.txtTitle.setText(title);
holder.txtArtist.setText(artist);
holder.txtVolume.setText(volume);
holder.txtNumber.setText(number);
if (favorite.matches("0")) {
holder.buttonHeart.setImageResource(R.drawable.heart);
} else {
if (favorite.matches("1")) {
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else {
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
holder.buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database = new FragmentOne_DbAdapter(context);
database.open();
if (favorite.matches("0")) {
database.updateItemFavorite(_id, "1");
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else if (favorite.matches("1")) {
database.updateItemFavorite(_id, "0");
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
FragmentOne_Adapter.this.changeCursor(dbHelper.fetchAllPlayer1());
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
// View rowView = ((LayoutInflater) context
// .getSystemService("layout_inflater")).inflate(
// R.layout.fragment_fragment_one_slview, parent, false);
View rowView = LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
ViewHolder holder = new ViewHolder();
holder.txtTitle = (TextView) rowView.findViewById(R.id.title);
holder.txtArtist = (TextView) rowView.findViewById(R.id.artist);
holder.txtVolume = (TextView) rowView.findViewById(R.id.volume);
holder.txtNumber = (TextView) rowView.findViewById(R.id.number);
holder.buttonHeart = (ImageButton) rowView.findViewById(R.id.heart);
rowView.setTag(holder);
return rowView;
}
class ViewHolder {
TextView txtTitle;
TextView txtArtist;
TextView txtVolume;
TextView txtNumber;
ImageButton buttonHeart;
}
}

Changing the default listViews item clicked to StringBuffer instead (displays popup by default)

I have a ListView that displays a list of items and I want to display further more details when any item is clicked using StringBuffer. But I'm having an issue because android default setOnItemClickListener bypasses the StringBuffer view that I'm defining inside the click event, and just displays the the item view in a popup.
Here is my code and I will include some screen shots in order to clarify my point a bit more
import android.app.AlertDialog;
import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class SummerJobsFragmnet extends Fragment {
public SummerJobsFragmnet() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static Fragment getInstance() {
Fragment fragment = new SummerJobsFragmnet();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void showMessage (String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final MainActivity activity = (MainActivity) getActivity();
String [] places = activity.getAllPositionsNamesPhone().toArray(
new String[activity.getAllPositionsNamesPhone().size()]);
final ListView list = (ListView) getView().findViewById(R.id.joblistView);
int prgmImages=R.mipmap.ic_launcher;
list.setAdapter(new CustomListAdapter(activity,places,prgmImages));
// OnClick listner for the individual cells of the listView
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the IDs of each column in the database
String [] IDs = activity.getAllColumnsIDs().toArray(
new String[activity.getAllColumnsIDs().size()]);
// loop throught the IDs and see if they match the listView
// item ids. if yes, display the detail
DataBaseHelper summerJobDB;
summerJobDB = new DataBaseHelper(activity);
for (int i = 0; i >= IDs.length; i++) {
if (i == id) {
Cursor res = summerJobDB.getAllData();
if (res.getCount() ==0){
// show some message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
// append the values from the database to the buffer.
// this is based on the index number of the columns
while (res.moveToNext()) {
buffer.append(res.getString(1)+ "/" + res.getString(2) +"\n");
buffer.append("Starts on " + res.getString(3)+"\n\n");
buffer.append("Address: \n"+ res.getString(5)+"\n\n");
buffer.append("Phone: \n"+ res.getString(6)+"\n\n");
buffer.append("Hours: \n"+ res.getString(4)+"\n\n");
}
// show all data here
showMessage("Data",buffer.toString());
}
}
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.displayjobs, container, false);
}
}
and here is the CustomListAdapter.java
import android.widget.BaseAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomListAdapter extends BaseAdapter {
String [] result;
Context context;
int imageId;
private static LayoutInflater inflater=null;
public CustomListAdapter(MainActivity mainActivity, String[] places, int prgmImages) {
// TODO Auto-generated constructor stub
result=places;
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();
View rowView;
rowView = inflater.inflate(R.layout.display_job_cell_view, null);
holder.tv=(TextView) rowView.findViewById(R.id.Itemname);
holder.img=(ImageView) rowView.findViewById(R.id.icon);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId);
/*
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();
}
});
*/
return rowView;
}
}
first image
Here is what I get
here is the logcat error after making the modifications
You have defined onClickListener on your list-items (rowView.setOnClickListener) - this is what gets called instead of the listView's setOnItemClickListener. You need to remove (comment out) this in the CustomListAdapter class:
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();
}
});
You need to also call listView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); so that only the listView's item click listener can be invoked even if the row item of list are set as focusable or clickable.
Then the dialog should show as you'd expect. Please try this and let us know if it works or what errors you get.

ListView remember only the position of old list after Filtering

i created an app that show a listview with clickable items. i have an edit text to make the search. everything is working great but when im searching for an item, the app give my a new list, the probleme is when im clicking on any item on thisnew list items it redirect me to the link of the item in old list.here is my code:
-For ReaderListAdapter.java :
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ReaderListAdapter extends BaseAdapter {
private List<Reader> listReader = null;
LayoutInflater layoutInflater;
Context context;
private int lastPosition = -1;
// constructeur
public ReaderListAdapter(Context context, List<Reader> listFood) {
this.listReader = listFood;
layoutInflater = LayoutInflater.from(context);
this.listReader = listFood;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView
.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position)
.getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.up_from_bottom);
convertView.startAnimation(animation);
lastPosition = position;
return convertView;
}}
For MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] listNames = { "site1", "site2", "site3"};
int[] listPrices = { 1, 2, 3};
ArrayList<Reader> listReader;
ListView lv;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {
getResources().getDrawable(R.drawable.a1),
getResources().getDrawable(R.drawable.a2),
getResources().getDrawable(R.drawable.a3)};
listReader = new ArrayList<Reader>();
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i],
listPrices[i]));
}
lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReader));
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
filtrer();
} });
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.google.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.quranf.com")) ;break;
}
if (intent != null) {
startActivity(intent);
}} });}
public void filtrer() {
// retourner la chaine saisie par l'utilisateur
String name = search.getText().toString();
// créer une nouvelle liste qui va contenir la résultat à afficher
final ArrayList<Reader> listReaderNew = new ArrayList<Reader>();
for (Reader reader : listReader) {
// si le nom du food commence par la chaine saisie , ajouter-le !
if (reader.getName().toLowerCase().toString().contains(name)) {
listReaderNew.add(reader);
}
}
// vider la liste
lv.setAdapter(null);
if (listReaderNew.size() == 0) {
listReaderNew.add(new Reader(100, "Pas d'élements.. réessayer !",
getResources().getDrawable(R.drawable.error), 0));
}
// ajouter la nouvelle liste
lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReaderNew));
}}
Any help would be appreciated from you. thank you If you need any clarification plz let me know
public class ReaderListAdapter extends BaseAdapter {
private List<Reader> listReader = null;
LayoutInflater layoutInflater;
Context context;
private int lastPosition = -1;
ArrayList<Reader> arrayList;
// constructeur
public ReaderListAdapter(Context context, List<Reader> listFood) {
this.listReader = listFood;
layoutInflater = LayoutInflater.from(context);
this.listReader = listFood;
this.context = context;
this.arrayList=listFood;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView
.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position)
.getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.up_from_bottom);
convertView.startAnimation(animation);
lastPosition = position;
return convertView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
listFood.clear();
if (charText.length() == 0) {
listFood.addAll(arraylist);
} else {
for (Reader cp : arraylist) {
if (cp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
listFood.add(cp);
}
}
}
notifyDataSetChanged();
}
}
*******************your MainActivity**********************
public class MainActivity extends Activity {
String[] listNames = { "site1", "site2", "site3"};
int[] listPrices = { 1, 2, 3};
ArrayList<Reader> listReader;
ListView lv;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {
getResources().getDrawable(R.drawable.a1),
getResources().getDrawable(R.drawable.a2),
getResources().getDrawable(R.drawable.a3)};
listReader = new ArrayList<Reader>();
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i],
listPrices[i]));
}
ReaderListAdapter readerListAdapternew ReaderListAdapter(getApplicationContext(), listReader)
lv.setAdapter(readerListAdapternew);
search.addTextChangedListener(new TextWatcher() {
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
String text = search.getText().toString()
.toLowerCase(Locale.getDefault());
readerListAdapternew .filter(text);
} });
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.google.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.quranf.com")) ;break;
}
if (intent != null) {
startActivity(intent);
}} });}
}

Remove item from custom listview on button click

I have a custom listview, that has 2 textviews and 2 buttons (play and delete button)
I want when I click the delete button to delete the current line.
My adapter class
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class SunetePreferateAdaptor extends BaseAdapter {
class ob {
String titlu, descriere;
public ob(String titlu, String descriere) {
this.titlu = titlu;
this.descriere = descriere;
}
}
ArrayList<ob> lista;
Context context;
public SunetePreferateAdaptor(Context context) {
this.context = context;
lista = new ArrayList<ob>();
for (int i = 1; i <= 20; i++) {
lista.add(new ob("text", "text2"));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return lista.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return lista.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_favsound_row, arg2, false);
Button b2 = (Button) row.findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// here, i want to delete the current row of the listview
//
//
}
});
TextView titlu = (TextView) row.findViewById(R.id.singleText2);
titlu.setText(lista.get(arg0).titlu);
titlu.setTextColor(Color.WHITE);
titlu.setTypeface(Global.font1);
TextView descriere = (TextView) row.findViewById(R.id.singleText1);
descriere.setText(lista.get(arg0).descriere);
descriere.setTextColor(Color.WHITE);
descriere.setTypeface(Global.font1);
return row;
}
}
Well how can I do that?
I've tried making the arraylist static and delete its items on click.. but no success..
You need not make ArrayList static.
You need to delete the data from the list which populates listview. You call notifyDataSetChanged(); to refresh the lsitview.
You can remove the static key word and use
Button b2 = (Button) row.findViewById(R.id.button1);
b2.setTag(arg0);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (int)arg0.getTag();
lista.remove(pos);
SunetePreferateAdaptor.this.notifyDataSetChanged(); }
});
Alternative :
You can pass the list to the constructor of adapter class.
ListView lv = (ListView) this.findViewById(R.id.listView1);
ArrayList<ob> lista = new ArrayList<ob>();
for (int i = 1; i <= 20; i++) {
lista.add(new ob("text", "text"+i));
}
lv.setAdapter(new SunetePreferateAdaptor(this,lista));
Then have this in a separate .java file
class ob {
String titlu, descriere;
public ob(String titlu, String descriere) {
this.titlu = titlu;
this.descriere = descriere;
}
}
Then
public class SunetePreferateAdaptor extends BaseAdapter {
ArrayList<ob> lista;
Context context;
public SunetePreferateAdaptor(Context context, ArrayList<ob> lista ) {
this.context = context;
this.lista= lista;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return lista.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return lista.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.fg, arg2, false);
Button b2 = (Button) row.findViewById(R.id.button1);
b2.setTag(arg0);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (int)arg0.getTag();
lista.remove(pos);
SunetePreferateAdaptor.this.notifyDataSetChanged(); }
});
TextView titlu = (TextView) row.findViewById(R.id.textView1);
titlu.setText(lista.get(arg0).titlu);
titlu.setTextColor(Color.WHITE);
TextView descriere = (TextView) row.findViewById(R.id.textView2);
descriere.setText(lista.get(arg0).descriere);
return row;
}
}
try this
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
lista.remove(position);
SunetePreferateAdaptor.notifyDataSetChanged();
}
});
You can done it by using your ArrayList lista. First remove the item in current position and the call adapter.notifyDataSetChanged() function.
This code worked absolutely fine for me.
public class CustomAdapter extends ArrayAdapter<String>
{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt = (Button) v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
v.setVisibility(View.GONE);
notifyDataSetChanged();
int positionToRemove = (int)v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(position);
String[] s = new String[a.size()];
s=a.toArray(s);
s1 = s;
notifyDataSetChanged(); //refresh your listview based on new data
}
public int getCount() {
return s1.length;
}
public String getItem(int position) {
return s1[position];
}}

How to solve a ResourcesNotFoundException in Android

This is my code , I have a problem ,error message about ResourcesNotFoundException this is a piece of code to view employees it has 2 buttons one to do delete and the other to do update.
I don't know the reason of this exception.
package com.example.task_9;
import java.util.ArrayList;
import com.example.task_9.my_dataBase.employees_con;
import com.example.task_9.my_dataBase.my_database;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class manage extends Activity {
ListView listview;
TextView totalrecords,tv;
//my_database db;
public ArrayList<employees> emp_list ;
employees_con con;
//Button logout;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
setContentView(R.layout.manage);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Employees Record:");
totalrecords = (TextView) findViewById(R.id.textView2);
listview = (ListView) findViewById(R.id.listView1);
// logout=(Button) findViewById(R.id.button1);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
emp_list = new ArrayList<employees>();
emp_list.clear();
con = new employees_con(this);
// db = new my_database(getApplicationContext());
// db.getWritableDatabase();
ArrayList<employees> e_list =con.getAllData() ;
for (int i = 0; i < e_list.size(); i++) {
Log.d("for_getall ", "ok ");
int e_id = e_list.get(i).getId();
Log.d("fun_getall ", "ok ");
// System.out.println("tidno>>>>>" + tidno);
String e_name = e_list.get(i).getUser_name();
String e_password = e_list.get(i).getPassword();
int e_age = e_list.get(i).getAge();
int e_status = e_list.get(i).getStatus();
Log.d("fun_getall ", "ok ");
employees emp_model = new employees();
emp_model.setId(e_id);
emp_model.setUser_name(e_name);
emp_model.setPassword(e_password);
emp_model.setAge(e_age);
emp_model.setStatus(e_status);
Log.d("addlist ", "ok ");
emp_list.add(emp_model);
}
Log.d("out for ", "ok ");
totalrecords.setText("Total Records :-" + emp_list.size());
listview.setAdapter(new ListAdapter(this));
con.close();
}
private class ListAdapter extends BaseAdapter {
//ArrayList<employees> data=new ArrayList<employees>();
Context contxt;
TextView id;
TextView user_name;
TextView password;
TextView age;
TextView status;
ImageView img;
employees obj;
LayoutInflater inflater;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
contxt=context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emp_list.size();
}
#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;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
/*if (v == null) {
v = inflater.inflate(R.layout.view, null);}*/
if (v == null)
{
LayoutInflater vi = (LayoutInflater)contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.view, null); // album_list.xml this layout of the custom listview
Log.d("view if", "ok ");
}
id=(TextView) v.findViewById(R.id.textView6);
user_name=(TextView) v.findViewById(R.id.textView7);
password=(TextView) v.findViewById(R.id.textView8);
age=(TextView) v.findViewById(R.id.textView9);
status=(TextView) v.findViewById(R.id.textView10);
img =(ImageView) v.findViewById(R.id.imageView1);
Log.d("out if", "ok ");
obj = emp_list.get(position);
user_name.setText(obj.getUser_name());
id.setText(obj.getId());
password.setText(obj.getPassword());
age.setText(obj.getAge());
status.setText(obj.getStatus());
Log.d("view else ", "ok ");
final int temp = position;
(v.findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int emp_id=emp_list.get(temp).getId();
String emp_name = emp_list.get(temp).getUser_name();
String emp_password = emp_list.get(temp).getPassword();
int emp_age=emp_list.get(temp).getAge();
int emp_status=emp_list.get(temp).getStatus();
Intent intent = new Intent(manage.this,update.class);
Bundle bundle = new Bundle();
bundle.putInt("id", emp_id);
bundle.putString("name", emp_name);
bundle.putString("password", emp_password);
bundle.putInt("age", emp_age);
bundle.putInt("status", emp_status);
intent.putExtras(bundle);
startActivity(intent);
}
});
(v.findViewById(R.id.button2))
.setOnClickListener(new OnClickListener() {
employees_con con=new employees_con(contxt);
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(manage.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
con.DeleteEmp(emp_list.get(temp).getUser_name().toString());
con.close();
manage.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Toast.makeText(
getApplicationContext(),
"No Clicked...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
}
});
return v;
}
}
}
}
Change
id.setText(obj.getId());
with
id.setText(String.valueOf(obj.getId()));
if you pass an int as argument for a TextView android will look for a String with id the int you provide. If it does not found throws an exception
One important this is that you should use Activity.onCreate() method in place of Activity.onStart().

Categories

Resources