Dynamically Increase the text count on click in BaseAdapter - android

I have Like Button In Layout and set the text "like 0" , i Have Set in Base Adapter , When I click on Like Buttton, the text will increase without refresh the whole Activity Like in facebook app , I am stuck on three days , i have read and implements almost every answer of stackoverflow , but not get the solution. I hope i will get the answer. Here is My Base Adapter <------->
public class FeedAdaptorView extends BaseAdapter{
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
String UserID;
public FeedAdaptorView(Context context,
ArrayList<HashMap<String, String>> arraylist, String uSERid2) {
this.context = context;
data = arraylist;
}
public class ViewHolder {
TextView name,time,status,likecount;
ImageView userimage,postimage;
Button like,comment,share;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.feed_item, null);
holder=new ViewHolder();
pos=getItemViewType(position);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.status=(TextView)convertView.findViewById(R.id.txtStatusMsg);
holder.userimage=(ImageView)convertView.findViewById(R.id.profilePic);
holder.postimage=(ImageView)convertView.findViewById(R.id.feedImage1);
holder.like=(Button)convertView.findViewById(R.id.like);
holder.comment=(Button)convertView.findViewById(R.id.comment);
holder.pos=position;
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.like.setTag(pos);
/* inflater = (LayoutInflater) context
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
}); .getSystemService(Context.LAYOUT_INFLATER_SERVICE);*/
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
holder.postimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
holder.like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Liked The Post", Toast.LENGTH_SHORT).show();
holder.like.setText("Like"+"4");
notifyDataSetChanged();
// here i am calling the web services for like button update
new likepost().execute();
}
});
<--------------------------------->
webservice callin method
class likepost extends AsyncTask<Void, Void, Void>
{
int flag=0;
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(context);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String Status="1";
String ID=feedid;
params.add(new BasicNameValuePair("UserID",UserID));
params.add(new BasicNameValuePair("FeedId",ID));
params.add(new BasicNameValuePair("like_status",Status));
JSONObject json = jsonParser.makeHttpRequest(AppControllerClass.FeedLike,"POST", params);
Log.d("Create Response", json.toString());
try{
if(json!=null)
{
String status=json.getString("status");
if(status.equals("Success"))
{
flag=1;
// Toast.makeText(context, "You Liked The Post", Toast.LENGTH_SHORT).show();
}
else
{
flag=2;
//Toast.makeText(context, "Check The Connection", Toast.LENGTH_SHORT).show();
}
}
else{
flag=2;
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
mProgressDialog.dismiss();
if(flag==1)
{
Toast.makeText(context, "You Liked The Post", Toast.LENGTH_SHORT).show();
}
else if (flag==2)
{
Toast.makeText(context, "Check The Connection", Toast.LENGTH_SHORT).show();
}
}

Dynamically Increase the text count on click in BaseAdapter
Do it as using getTag/setTag:
#Override
public void onClick(View c) {
int count=0;
if(v.getTag()==null)
count=0;
else{
count=Integer.parseInt(v.getTag().toString());
}
count++;
((TextView)v).setText("Like"+count);
v.setTag(count);
}

Try this..
#Override
public Object getItem(int position) {
return data.get(position);
}
instead of
#Override
public Object getItem(int position) {
return null;
}

This is my first time answering questions on StackOverflow and I hope that my answer is able to help you solve your problem.
PROBLEM :
holder.like.setText("Like"+"4");
notifyDataSetChanged();
The problem is here. You have manually set it to setText("Like"+"4"). In BaseAdapter's notifyDataSetChanged() function, it refers to an ADAPTER of information.
In your case, it will be the reference of resulttp. It is referencing to the data ArrayList you have passed in. And when you call notifyDataSetChanged(), it will refer back to the resulttp and display WHAT is in the ArrayList.
SOLUTION :
1) Remove this line
holder.like.setText("Like"+"4");
2) Add in a new function called update() in your BaseAdapter class
public void updateAdapter(ArrayList<HashMap<String, String>> newData)
{
this.data.clear();
this.data = data;
notifyDataSetChanged();
}
3) On your like button / image onClickListener, call the function updateAdapter() and pass in an UPDATED ArrayList.
It should be alright already. Good Luck!

Related

Multiple choice listview not showing all objects

I am following a tutorial about multiple choice listview in android.
When executing the app, the listview shows some items, not all of them. After clicking on the listview, it shows all items.
I want to know where is the reason of that issue.
This is the code for MainActivity class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
ListView list;
TextView txt_menu;
String dipilih;
private static final String TAG = MainActivity.class.getSimpleName();
Adapter adapter;
ProgressDialog pDialog;
List<Data> itemList = new ArrayList<Data>();
// Sesuaikan dengan IP Address PC/LAptop atau ip emulator bawaan android 10.0.2.2
private static String url = "https://.../test/menu.php";
public static final String TAG_NAMA = "nama";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
list = (ListView) findViewById(R.id.list_menu);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
callVolley();
adapter = new Adapter(this, (ArrayList<Data>) itemList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);
txt_menu.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void callVolley(){
itemList.clear();
// menapilkan dialog loading
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
showDialog();
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NAMA));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And this is the Adapter class:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
viewHolder.menu.setText(items.getMenu());
}
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
If you need other code parts to detect the problem, please let me know.
EDIT
First launch
After clicking on the listview
The problem is this bit of your code in your adapter's getView() callback:
if(view == null) {
...
}else {
...
viewHolder.menu.setText(items.getMenu());
}
What's happening here is that you're only caling setText() when the item view is recycled by the ListView. The reason everything shows up after you click a checkbox is that the ListView rebinds everything when you call notifyDataSetChanged().
You should call this method outside of the if/else statement so that it is executed every time.
if(view == null) {
...
}else {
...
}
viewHolder.menu.setText(items.getMenu());
I think the issue you are having is coming from the getView() method in your Adapter class.
Since you are using a ViewHolder to recycle objects you are first checking if the exist first before creating them if(view == null). But, you are only creating them and not assigning the TextView objects a String value. You only do that once the object has already been created. So, when you click on an item, you are calling notifyDataSetChanged causing the list to be updated. Then the values are set in the `TextView.
So try this instead: put the line viewHolder.menu.setText(items.getMenu()); outside the conditional statement:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
try this once
adapter = new Adapter(this, (ArrayList) itemList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
list.setAdapter(adapter);
}
set adapter at the end

notifyDataSetChanged not working in AsyncTask inside BaseAdapter class

i have created a list of ads in listview using BaseAdapter and i want to delete a single ad from list. To delete a single ad i have to request a web api using asynchronous task, so i have added the notifyDataSetChanged() in onPostExecute method. ads was deleted successfully but notifydatasetchnaged not working .my custom BaseAdapter class is given below please help to solve this problem.
public class AdsListAdapter extends BaseAdapter{
private Activity activity;
ArrayList<String> title;
ArrayList<Long> adsIds;
SessionManager sessions;
AlertDialogManager alert = new AlertDialogManager();
private static LayoutInflater inflater=null;
String MYTAG="AdLIst";
long userID=0;
public AdsListAdapter(Activity a,ArrayList<String> titlelist,ArrayList<Long> adsId,long userid) {
activity = a;
title=titlelist;
adsIds=adsId;
userID=userid;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
sessions=new SessionManager(activity.getApplicationContext());
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView titles,editicon,delicon;
}
#SuppressLint("NewApi") public View getView(int position, View convertView, ViewGroup parent) {
final int id=position;
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.adscustomlist, null);
holder = new ViewHolder();
holder.titles = (TextView) vi.findViewById(R.id.titles);
holder.editicon= (TextView) vi.findViewById(R.id.editicon);
holder.delicon= (TextView) vi.findViewById(R.id.delicon);
vi.setTag( holder );
}
else
{ holder=(ViewHolder)vi.getTag(); }
holder.titles.setText(title.get(position));
holder.delicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DeleteAd(userID,adsIds.get(id)).execute();
}
});
return vi;
}
class DeleteAd extends AsyncTask<String,Void,Void>
{
AlertDialogManager alert = new AlertDialogManager();
private String Error = null,Message=null;
long UserID =0,AdId=0;
boolean Status=false;
private ProgressDialog Dialog = new ProgressDialog(activity);
protected void onPreExecute() {
Dialog.setMessage("Loading ...");
Dialog.setCanceledOnTouchOutside(false);
Dialog.show();
}
public DeleteAd(long UserID,long AdId) {
this.UserID=UserID;
this.AdId=AdId;
}
#Override
protected Void doInBackground(String... arg0) {
JSONObject json;
try {
json = new JSONObject(postDataAdDelete());
Message=json.getString("Message");
Status = json.getBoolean("Status");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
alert.showAlertDialog(activity, "Ad Delete", Message, Status);
notifyDataSetChanged();
}
}
}
Try to call notifyDataSetChanged() method like this
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
you must remove value at position you want to delete in list title. Try title.remove(position)
AdsListAdapter adapter = new AdsListAdapter (Activity ,ArrayList<String> ,ArrayList<Long> ,long );//pass the value
adapter.notifyDataSetChanged();

Onitem long click not working for listvview

I have a activity which implements onitemlongclicllstener to a list view. I use parse.com as my back end for retrieving data into listvview. Everything works fine but onitemlongclicllstener don't work on list view. Nothing happens when list item is long clicked
my main activity
public class InterActivity extends Activity implements OnItemLongClickListener
{
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
FinalAdapter adapter;
List<CodeList> codelist = null;
SharedPreference shrdPreference;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.inter_layout);
shrdPreference = new SharedPreference();
//Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(InterActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Please wait loading ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist = new ArrayList<CodeList>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
ob = query.find();
for (ParseObject inter : ob) {
ParseFile video = (ParseFile) inter.get("demovideo");
// ParseFile downloadfile = (ParseFile) inter.get("download");
CodeList map = new CodeList();
map.setListHeading((String) inter.get("listheading"));
map.setSingleItemHeading((String) inter.get("heading"));
map.setDownloadCode((String) inter.get("download"));
map.setDailogdemovideo(video.getUrl());
// map.setDownloadCode(downloadfile.getUrl());
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.inter_layoutListView);
// Pass the results into ListViewAdapter.java
adapter = new FinalAdapter(InterActivity.this,
codelist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemLongClickListener(InterActivity.this);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3)
{
ImageView fvrtebutton = (ImageView) view.findViewById(R.id.favbtn);
String tag = fvrtebutton.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
shrdPreference.addFavorite(InterActivity.this, codelist.get(position));
Toast.makeText(InterActivity.this, getString(R.string.fav_added),
Toast.LENGTH_SHORT).show();
fvrtebutton.setTag("yes");
fvrtebutton.setImageResource(R.drawable.favorite);
} else {
shrdPreference.removeFavorite(InterActivity.this, codelist.get(position));
fvrtebutton.setTag("no");
fvrtebutton.setImageResource(R.drawable.unfavorite);
Toast.makeText(InterActivity.this,
getString(R.string.fav_removed),
Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
final adapter.java
public class FinalAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ImageLoader imgLoader;
private List<CodeList> codeList = null;
private ArrayList<CodeList> arraylist;
SharedPreference shrdprfrnce;
public FinalAdapter(Context context,
List<CodeList> codeList) {
this.context = context;
this.codeList = codeList;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<CodeList>();
this.arraylist.addAll(codeList);
shrdprfrnce = new SharedPreference();
imageLoader = new ImageLoader(context);
}
public class ViewHolder{
TextView listHeading;
TextView listHash;
ImageView alphabetList;
ImageView favariteImage;
}
#Override
public int getCount()
{
return codeList.size();
}
#Override
public Object getItem(int position)
{
return codeList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent)
{
final ViewHolder holder;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.beg_list_item,null);
holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
//holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
holder.favariteImage = (ImageView) view.findViewById(R.id.favbtn);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
CodeList codes = (CodeList) getItem(position);
holder.listHeading.setText(codeList.get(position).getListHeading());
imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
holder.alphabetList);
if (checkFavoriteItem(codes)) {
holder.favariteImage.setImageResource(R.drawable.favorite);
holder.favariteImage.setTag("yes");
} else {
holder.favariteImage.setImageResource(R.drawable.unfavorite);
holder.favariteImage.setTag("no");
}
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return view;
}
public boolean checkFavoriteItem(CodeList checkCodes) {
boolean check = false;
List<CodeList> favorites = shrdprfrnce.getFavorites(context);
if (favorites != null) {
for (CodeList codes : favorites) {
if (codes.equals(checkCodes)) {
check = true;
break;
}
}
}
return check;
}
public void add(CodeList codes) {
(
codeList.add(codes);
notifyDataSetChanged();
}
public void remove(CodeList codes) {
codeList.remove(codes);
notifyDataSetChanged();
}
}
plz remove
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
bcoz it Get Full view Click Thats y ur OnLongClick is not working yet
try with return true;
#Override
public boolean onItemLongClick(AdapterView < ? > arg0, View arg1,
int pos, long id) {
Log.v("long clicked", "pos: " + pos);
return true;
}

Reload ImageView by URI on ListView

I have a ListView of elements composed with ImageView. I get a new image using an AsyncTask and in the onPostExecute(Object result) method I set the image using setImageUri(Uri uri) but it doesn't gets updated.
If I change of activity or between apps, image is shown perfectly, but I want to show the image immediately.
I tried calling invalidate() with all the combinations of the ImageView, the extended BaseAdapter, the parent ListView, but nothing worked. I tried many other techniques like calling setImageResource(0), setImageUri(null), but no results...
EDITED:
Here, part of the code:
public class ThingItemAdapter extends BaseAdapter {
protected List<Thing> things;
LayoutInflater inflater;
public ThingItemAdapter(Context context, List<Thing> things) {
this.things = things;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return things.size();
}
#Override
public Thing getItem(int position) {
return things.get(position);
}
#Override
public long getItemId(int position) {
return things.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.thing_list_item, parent, false);
holder.thingImageView = (ImageView) convertView.findViewById(R.id.thing_preview);
holder.button = (ImageButton) convertView.findViewById(R.id.apply_button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Thing thing = things.get(position);
final long thingId = thing.getId();
final Uri thingUri = thing.getPicture();
holder.thingImageView.setImageURI(thingUri);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// generate new file
final TypedFile typedFile = new TypedFile("multipart/form-data", new File(thingUri.getPath()));
new ReadAndStorePictureTask()
.execute(new Object[] { typedFile, holder.thingImageView, thing });
}
});
// item detailed view listener
holder.thingImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent((ThingApplication) ThingApplication.getContext(), ThingActivity.class);
intent.putExtra(ThingActivity.EXTRA_THING_ID, thingId);
context.startActivity(intent);
}
});
return convertView;
}
private class ViewHolder {
ImageView thingImageView;
ImageButton button;
}
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
Thing thing;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
thing = (Thing) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
thing.setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(thing);
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
imageView.setImageURI(thing.getPicture());
// force redraw. FIXME not working
/*
* ANSWER HERE, PLEASE
*/
}
}
}
How can I show the updated URI immediately inside onPostExecute(Object result) method?
onPostExecute you update the list of images that it's linked to the ListView adapter and after that you notify the adapter that you changed the items in the list by calling:
adapter.notifyDataSetChanged();
You can do something like this:
-Change third parameter in asynctask call.
new ReadAndStorePictureTask().execute(
new Object[] { typedFile, holder.thingImageView, pos });
-Then, modify the list items inside asynctask and refresh.
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
int position;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
position = (Integer) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
things.get(position).setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(things.get(position));
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
notifyDataSetChanged();
}
}
Good luck!

How to set Text in Textview when Click on selected item in Listview?

I am using Listview with ViewHolder, and setText in Textview then display error. How to setText in Textview in Listview? Whenever I click on Like Button then I get the total count for Like but I am not able to setText on TextView for every item. whenever click on selected item then Its TextView Increment by 1 Its Successfully. get strCount is Successfully but how to setText for Selected TextView when Click on Selected Image and My code is,
My Screenshot is which is Listview and set Multiple Items in Listview Like,
My Adapter Class,
public class Adapter1 extends BaseAdapter {
public ArrayList<HashMap<String, String>> arr = null;
Context context = null;
LayoutInflater layoutInflater = null;
HashMap<String, String> getData = new HashMap<String, String>();
String url = null, urlCount = null;
String strId = null, strCount = null;
ViewHolder viewHolder = null;
public Adapter1(Context context, ArrayList<HashMap<String, String>> arr) {
this.context = context;
this.arr = arr;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int position) {
return arr.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null);
/** initialize ViewHolder */
viewHolder = new ViewHolder();
/** Initialize Widgets */
/** Imageview */
viewHolder.img = (ImageView) convertView.findViewById(R.id.img);
/** TextView */
viewHolder.txtId = (TextView) convertView.findViewById(R.id.txtId);
viewHolder.txt = (TextView) convertView.findViewById(R.id.txt);
getData = arr.get(position);
viewHolder.txtId.setText(getData.get(Fragment1.TAG_ID));
viewHolder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strId = arr.get(position).get(Fragment1.TAG_ID);
System.out.println("!!!!!!!!!! strId======"+ strId);
url = "http://example.com/createpost.php?id="+ strId + "&user_id="+ myDetail.getUserId();
new sendData().execute();
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
/** ViewHolder Class */
#SuppressLint("NewApi")
public class ViewHolder {
ImageView img = null,
TextView txtId = null
txt = null;
}
public class sendData extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlLike, ServiceHandler.GET);
System.out.println("!!!!!!!!!!!!!!!jsonStr in Do in===" + jsonStr);
Log.d("Response : Like", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
urlCount = "http://example.com/getalldata.php?id="+ strId;
new getCountData().execute();
};
}
/** Count the Total Like for Selected Items. */
private class getCountData extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonobject = JSONFunctions.getJSONfromURL(urlCount);
try {
strCount = jsonobject.getString("countdata");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("!!!!!!!!strCount====" + strCount);
viewHolder.txt.setText(String.valueOf(strCount));
}
}
}
Thanks in advance.
In onClick() function you have to get instance of textview and pass it to AsyncTask
// if text and img have same parent the you can find textview like this is
TextView tv =(TextView)v.getParent().findViewById(R.id.txt);
// if not then apply call getParent() function multiple time as per your layout
new sendData(tv).execute();
//Create constructor in sendData
public class sendData extends AsyncTask {
private TextView tv;
public sendData(TextView v){
tv=v;
}
...
protected void onPostExecute(Void result) {
super.onPostExecute(result);
urlCount = "http://example.com/getalldata.php?id="
+ strId;
new getCountData(tv).execute();
};
}
private class getCountData extends AsyncTask {
private TextView v;
public sendData(TextView v){
tv=v;
}
....
// in onPostExecute use
tv.setText(String.valueOf(strCount));
}
Edit: you can get correct position by tag position to view and get it inside onClick
// add this line before return
viewHolder.img.setTag(position);
// get position inside onClick()
int position =(Integer)v.getTag();

Categories

Resources