Adding and removing the item into wish list like flipkart - android

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;
}
}

Related

listview effecting multiple rows 4th,7th,10th

i have a custom listview and custom adapter. each row has multiple items inside it, when i click on like button it change the color of imageview but it also effect the 4th,7th and 10th row.
after searching on internet i learned that i have to use getTag and setTag but i dont know how to use it.
please help me in understanding the concept of getTag and setTag and solving this error.
here is my code:-
package rj.osmthemes;
import java.util.ArrayList;
import android.content.Context;
import android.os.Build;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import static android.R.attr.data;
import static rj.osmthemes.R.id.downlink;
import static rj.osmthemes.R.id.likebtn;
import static rj.osmthemes.R.id.likecount;
public class ListAdapter extends ArrayAdapter<DataModel> {
customButtonListener customListner;
private ArrayList<DataModel> dataSet;
public String temp1;
public interface customButtonListener {
public void onButtonClickListner(int position,String value);
public void onImageClickListner(int position,String value);
public void onlikeImageClickListner(int position,String value);
public void ondislikeImageClickListner(int position,String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
//private ArrayList<String> data = new ArrayList<String>();
public ListAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.list_layout, data);
this.dataSet = data;
this.context = context;
}
private int lastPosition = -1;
// public ListAdapter(Context context, ArrayList<String> dataItem) {
// super(context, R.layout.list_layout, dataItem);
// this.data = dataItem;
// this.context = context;
// }
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final DataModel dataModel = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_layout, null);
viewHolder = new ViewHolder();
viewHolder.themename = (TextView) convertView.findViewById(R.id.themename);
viewHolder.madeby = (TextView) convertView.findViewById(R.id.madeby);
viewHolder.downcount = (TextView) convertView.findViewById(R.id.downcount);
viewHolder.likecount = (TextView) convertView.findViewById(likecount);
viewHolder.dislikecount = (TextView) convertView.findViewById(R.id.dislikecount);
viewHolder.ss1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder.ss2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder.ss3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder.likebtn = (ImageView) convertView.findViewById(likebtn);
viewHolder.dislikebtn = (ImageView) convertView.findViewById(R.id.dislikebtn);
viewHolder.btndownload = (Button) convertView.findViewById(downlink);
convertView.setTag(viewHolder);
final String temp = getItem(position).toString();
viewHolder.likebtn.setTag(temp);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
lastPosition = position;
//final String temp = getItem(position).toString();
// viewHolder.tempid = Integer.parseInt(dataModel.getId());
final String ss1link,ss2link,ss3link,downlink;
viewHolder.themename.setText(dataModel.getTheme_name());
viewHolder.madeby.setText(dataModel.getMade_by());
viewHolder.downcount.setText(dataModel.getDown_count());
viewHolder.likecount.setText(dataModel.getLike_count());
viewHolder.dislikecount.setText(dataModel.getDislike_count());
ss1link = dataModel.getSs1();
ss2link = dataModel.getSs2();
ss3link = dataModel.getSs3();
downlink = dataModel.getDown_link();
// viewHolder.text.setText(temp);
viewHolder.btndownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
int downcounttmp = Integer.parseInt(dataModel.getDown_count());
downcounttmp++;
viewHolder.downcount.setText(""+downcounttmp);
String name = downlink + "#" + dataModel.getTheme_name() + "#" + dataModel.getId() + "#" + downcounttmp;
customListner.onButtonClickListner(position,name);
}
}
});
viewHolder.ss1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss1link);
}
}
});
viewHolder.ss2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss2link);
}
}
});
viewHolder.ss3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss3link);
}
}
});
viewHolder.likebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
// Toast.makeText(context, dataModel.getId() + " { " ,Toast.LENGTH_LONG).show();
if(viewHolder.check == 0){
int likecount = Integer.parseInt(dataModel.getLike_count());
likecount++;
viewHolder.likecount.setText(""+likecount);
String name = likecount + "#" + dataModel.getId();
// Toast.makeText(context,position + " " + temp,Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.likebtn.setImageResource(R.drawable.ic_thumb_up_red_24dp);
//viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp));
viewHolder.check = 1;
}
customListner.onlikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
viewHolder.dislikebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
if(viewHolder.check == 0) {
int dislikecount = Integer.parseInt(dataModel.getDislike_count());
dislikecount++;
viewHolder.dislikecount.setText(""+dislikecount);
String name = dislikecount + "#" + dataModel.getId();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp));
viewHolder.check = 1;
}
customListner.ondislikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
Glide
.with(context)
.load(ss1link)
.into(viewHolder.ss1);
Glide
.with(context)
.load(ss2link)
.into(viewHolder.ss2);
Glide
.with(context)
.load(ss3link)
.into(viewHolder.ss3);
return convertView;
}
public class ViewHolder {
TextView themename,madeby,downcount,likecount,dislikecount;
Button btndownload;
ImageView ss1,ss2,ss3,likebtn,dislikebtn;
int check = 0, tempid = 0;
}
}
This is because of object reuse in your list view.
You can manage separate ArrayList or HashMap to maintain your likes.
And based on that you should update in your getView like this,
if([already selected]) {
viewHolder.likebtn.setBackground([your selected drawable]);
} else {
viewHolder.likebtn.setBackground([your non selected drawable]);
}

How to get position of checked checkbox from ListView in android

I created custom ListView with CheckBox next to title. I want to get checked
CheckBox from ListView
I created following function for get message from ListView and send it to another ListView with Intent but I cant get the particular CheckBox position to move.
public class SpamActivity extends AppCompatActivity {
List<Message> sms;
ArrayList<Message> sms1;
ArrayList<String> al;
ListView lv;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messagebox);
lv= (ListView) findViewById(R.id.lvMsg);
checkbox = (CheckBox) findViewById(R.id.checkBox);
sms = new ArrayList<>();
al=new ArrayList<>(0);
populateMessageList();
/* SpamActivity spamactivity = new SpamActivity();
al = spamactivity.al;
//InboxFragment inboxfragment = new InboxFragment();
//al = inboxfragment.list;
for (int i=0;i<sms.size();i++){
System.out.println("AddressSPS" + sms.get(i));
} */
Collections.reverse(sms);
}
public void populateMessageList() {
sms1 = new ArrayList<>();
fetchDatabaseMessage();
lv.setAdapter(new datalist(getApplicationContext(), sms1));
// to handle click event on listView item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// when user clicks on ListView Item , onItemClick is called
// with position and View of the item which is clicked
// we can use the position parameter to get index of clicked item
TextView textViewSMSSender = (TextView) v.findViewById(R.id.lblNumber);
TextView textViewSMSBody = (TextView) v.findViewById(R.id.lblMsg);
TextView textViewSMSDate = (TextView) v.findViewById(R.id.smsdate);
String smsSender = textViewSMSSender.getText().toString();
String smsBody = textViewSMSBody.getText().toString();
String smsDate = textViewSMSDate.getText().toString();
Intent intentspam = new Intent(getApplicationContext(), DisplaySpamsms.class);
intentspam.putExtra("number",smsSender);
intentspam.putExtra("msg",smsBody);
startActivity(intentspam);
}
});
}
// This method featch the message stored in database
public void fetchDatabaseMessage(){
DB_Message dbmessage = new DB_Message(this);
sms = dbmessage.ViewMessageData();
String addr = sms.get(0).getmAddress();
if (addr.equals(sms.get(0).getmAddress())) {
for (int i = 0; i < sms.size(); i++) {
al.add(sms.get(i).getmAddress());
//al.add(sms.get(i).getmBody());
}
}else {
System.out.println("SMS Not Displayed");
}
}
class datalist extends BaseAdapter {
Context context;
ArrayList<Message> arrayListsms;
public datalist(Context context, ArrayList<Message> arrayListsms) {
// TODO Auto-generated constructor stub
this.context = context;
this.arrayListsms = arrayListsms;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return sms.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return getItem(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
LayoutInflater inflator = getLayoutInflater();
View row;
row = inflator.inflate(R.layout.row, parent, false);
// ImageView img1 = (ImageView) row.findViewById(R.id.imageView1);
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
final TextView txt1 = (TextView) row.findViewById(R.id.lblMsg);
final TextView txt2 = (TextView) row.findViewById(R.id.lblNumber);
final TextView txt3 = (TextView) row.findViewById(R.id.smsdate);
//Long timestamp = Long.parseLong(sms.get(position).getmDate());
Calendar mcalendar = Calendar.getInstance();
//mcalendar.setTimeInMillis(timestamp);
DateFormat mformatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
txt1.setText(sms.get(position).getmBody());
txt2.setText(sms.get(position).getmAddress());
//+"\n"+mformatter.format(mcalendar.getTime())
txt3.setText(mformatter.format(mcalendar.getTime()));
final String msgBody = txt1.getText().toString();
final String msgAddr = txt2.getText().toString();
final String msgDate = txt3.getText().toString();
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Message msg = new Message();
if (isChecked) {
// selectedStrings.add(tv.getText().toString());
Toast.makeText(context, "" + msgBody, Toast.LENGTH_LONG).show();
System.out.println("Body" + msgBody);
System.out.println("Address" + msgAddr);
System.out.println("Date" + msgDate);
al.add(msgBody + msgAddr + msgDate);
// al.add(msgAddr);
// al.add(msgDate);
sms.remove(position);
ContentValues values = new ContentValues();
values.put("address", sms.get(position).getmAddress());
values.put("body", sms.get(position).getmBody());
String date = msg.getmDate();
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
notifyDataSetChanged();
} else {
// selectedStrings.remove(tv.getText().toString());
}
}
});
return row;
}
}
}
When I used above function for sending message but error is that when I click on any CheckBox to send that message then automatically Different Message is sent to another activity. so, I want to get particular message position to sent it.
You can set "setOnItemClickListener" on list view and get the position.
ListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here you can get the position
}
});
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class SharedContactListAdapter extends ArrayAdapter<ContactSynResponse> {
private Context context;
private ViewHolder viewHolder;
private SparseBooleanArray mSparseBooleanArray;
private List<ContactSynResponse> mList;
public SharedContactListAdapter(Context context, int resource,
List<ContactSynResponse> objects) {
super(context, resource, objects);
this.context = context;
mSparseBooleanArray = new SparseBooleanArray();
// mList = objects;
}
#Override
public ContactSynResponse getItem(int position) {
return super.getItem(position);
}
public ArrayList<ContactSynResponse> getCheckedItems() {
ArrayList<ContactSynResponse> mTempArry = new ArrayList<ContactSynResponse>();
for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
ContactSynResponse data = mList.get(i);
mTempArry.add(data);
}
}
return mTempArry;
}
class ViewHolder {
ImageView profilepic;
ChimmerTextView contactname;
ChimmerTextView contactno;
RelativeLayout completelayout;
CheckBox selectcheckbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.sharedcontactlistdata,
parent, false);
viewHolder = new ViewHolder();
viewHolder.profilepic = (ImageView) convertView
.findViewById(R.id.profilepic_image_view);
viewHolder.contactname = (ChimmerTextView) convertView
.findViewById(R.id.contactnameTV);
viewHolder.contactno = (ChimmerTextView) convertView
.findViewById(R.id.contactnoTV);
viewHolder.completelayout = (RelativeLayout) convertView
.findViewById(R.id.completeRL);
viewHolder.selectcheckbox = (CheckBox) convertView
.findViewById(R.id.contact_checkbox);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ContactSynResponse data = getItem(position);
viewHolder.contactname.setText(data.getName());
viewHolder.contactno.setText(data.getPhone());
viewHolder.selectcheckbox.setTag(position);
viewHolder.selectcheckbox.setOnCheckedChangeListener(new CheckListener(
data, viewHolder.selectcheckbox));
viewHolder.completelayout.setOnClickListener(new ClickListener(data,
viewHolder.selectcheckbox));
return convertView;
}
class CheckListener implements OnCheckedChangeListener {
private CheckBox checkbox;
public CheckListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
} else {
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
}
buttonView.setChecked(isChecked);
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
}
class ClickListener implements OnClickListener {
private CheckBox checkbox;
public ClickListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onClick(View v) {
if (checkbox.isSelected()) {
checkbox.setChecked(false);
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), false);
} else {
checkbox.setChecked(true);
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), true);
}
}
}
}

getActivity() gives context equal to null

I have developed and launched an Android application. It works fine on my Android phone, but it crashes on several devices.
*BugSense gives me the following error:*
0 java.lang.NullPointerException
1 at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
2 at android.widget.ArrayAdapter.(ArrayAdapter.java:128)
3 **at com.challenger.app.ChallengeAdapter.(ChallengeAdapter.java:27)**
4 at com.challenger.app.AllChallenges.fitChallenges(AllChallenges.java:142)
5 at com.challenger.app.AllChallenges$1.onSuccess(AllChallenges.java:108)
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class AllChallenges extends Fragment {
Button loginButton;
ListView listView2, listView1;
TextView textView;
int category = 0;
View view;
List<Challenge> challenge_data;
public AllChallenges(int cat) {
category = cat;
}
public AllChallenges() {
// TODO Auto-generated constructor stub
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
if(getActivity()!=null){
load();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.allchallenges, container, false);
if(getActivity()!=null){
load();
}
return view;
}
public void load() {
loadOld();
if (!AppSettings.refreshed[category + 1]) {
update();
}
}
public void loadOld() {
Log.d("Challenge", "Updating " + category);
JSONArray a = AppSettings.loadChallenges(category, getActivity());
if (a != null) {
fitChallenges(makeArray(a));
}
}
public void update() {
Log.d("Challenge", "getChallenges/" + category);
RequestParams a = new RequestParams();
if (AppSettings.logged) {
a.put("fb_id", AppSettings.facebookId);
a.put("fb_authkey", AppSettings.facebookAuthToken);
}
NetworkClient.receiveJSON("getChallenges/" + category, a,
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray chalList) {
Log.d("Challenge", "Downloaded " + category);
AppSettings.saveChallenges(category, chalList,
getActivity());
fitChallenges(makeArray(chalList));
AppSettings.refreshed[category + 1] = true;
}
});
}
public Challenge[] makeArray(JSONArray list) {
challenge_data = new ArrayList<Challenge>();
try {
for (int i = 0; i < list.length(); i++) {
JSONObject chal = (JSONObject) list.get(i);
String[] arr = {};
if (chal.has("friends"))
arr = JSONArrToArr(chal.getJSONArray("friends"));
Log.e("Boolean", chal.getString("active"));
challenge_data.add(new Challenge(chal.getInt("id"), chal
.getString("title"), chal.getInt("category"), chal
.getInt("taken_by"), arr, chal.getBoolean("active"),
chal.getString("text"), chal.getInt("streak"), chal
.getInt("percentage")));
}
return challenge_data.toArray(new Challenge[challenge_data.size()]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void fitChallenges(Challenge[] chalArray) {
**ChallengeAdapter adapter = new ChallengeAdapter(getActivity(),
R.layout.list_row, chalArray);** //
listView1 = (ListView) view.findViewById(R.id.listView1);
listView1.setAdapter(adapter);
OnItemClickListener listener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("listener", "am ID" + id + "position " + position);
int n = (int) id;
String title = challenge_data.get(n).toStringArray()[1];
Log.i("listener", "am ID" + id + "position " + position
+ " title " + title);
int people = challenge_data.get(n).peopleInt;
String category = challenge_data.get(n).toStringArray()[0];
String description = challenge_data.get(n).toStringArray()[5];
int streak = challenge_data.get(n).streak;
int percentage = challenge_data.get(n).percentage;
int chal_id = challenge_data.get(n).id;
boolean active = challenge_data.get(n).active;
((AllChallengesPager) getActivity()).showDetailed(chal_id,
title, "" + people, category, active, description, ""
+ streak, "" + percentage);
}
};
listView1.setOnItemClickListener(listener);
}
public String[] JSONArrToArr(JSONArray arr) {
String[] newArr = {};
try {
List<String> list = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
list.add(arr.getString(i));
}
newArr = list.toArray(new String[list.size()]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newArr;
}}
public class ChallengeAdapter extends ArrayAdapter<Challenge> {
Context context;
int layoutResourceId;
Challenge data[] = null;
Typeface a;
public ChallengeAdapter(Context context, int layoutResourceId,
Challenge[] data) {
**super(context, layoutResourceId, data);** //in this line code crashes
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
a = Typeface.createFromAsset(context.getAssets(),
"fonts/roboto_condensed.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChallengeHolder holder = null;
Challenge challenge = data[position];
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChallengeHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.list_image);
holder.txtTitle = (TextView) row.findViewById(R.id.challenge);
holder.txtPeople = (TextView) row.findViewById(R.id.peopleNumber);
holder.friendThumbs = (LinearLayout) row
.findViewById(R.id.friendThumbs);
row.setTag(holder);
} else {
holder = (ChallengeHolder) row.getTag();
}
holder.friendThumbs.removeAllViews();
for (int i = 0; i < challenge.friendIds.length; i++) {
holder.friendThumbs.addView(createIcon(challenge.friendIds[i],
context));
}
holder.txtTitle.setText(challenge.title);
holder.txtTitle.setTypeface(a);
holder.imgIcon.setImageResource(challenge.icon);
holder.txtPeople.setText(challenge.peopleString);
return row;
}
static class ChallengeHolder {
public LinearLayout friendThumbs;
ImageView imgIcon;
TextView txtTitle;
TextView txtPeople;
}
public ImageView createIcon(String friendID, Context cont) {
ImageView icon = new ImageView(context);
LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
(int) cont.getResources().getDimension(R.dimen.fbIconSize),
(int) cont.getResources().getDimension(R.dimen.fbIconSize));
par.setMargins(0, 0, 15, 0);
icon.setLayoutParams(par);
Log.e("ID " + friendID, "log");
final String myurl = AppSettings.profilePictureUrl(friendID);
icon.setImageResource(R.drawable.default_fb_icon_small);
((MyApplication) ((Activity) context).getApplication())
.loadImageSimple(myurl, icon);
return icon;
}
}
I guess that the cause of this problem is context equal to null got from the method getActivity, but don't know how to deal with this problem. Could anyone explain how to solve the problem?
I think onActivityCreated method override and implement for this code, and its working fine may be...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(getActivity()!=null){
load();
}
}
And Fragment lifecyle must read for this doc Documentation
Most likely your Fragment is detached from your activity at this stage as this is called in an external thread JsonHttpResponseHandler.
You have a good explanation here:
https://stackoverflow.com/a/11536337/891479
You should not call
if(getActivity()!=null){
load();
}
in onCreateView.
onViewCreated is called after onCreateView and as per the docs
The fragment's view hierarchy is not however attached to its parent
at this point.
I think if I remember correctly its better to use getActivity().getApplicationContext()

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().

Dynamic ListView - Refresh on Button Click

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);
}
});
}

Categories

Resources