2

I have tried to change a image view in android listview . If i have selecting any item row from the list., there are 2 images are there.they are attend , un-attend.

defaultly the item status was attend. if the user clicking the attend image ., the functionality is done then need to change the attend image to un-attend.

If the user clicking the un-sttend image., the functionality wll be done then need to change the un-attend image to attend image.

I have following the below code . The functionality is working fine . but the image didn't change on run time. Please check the code and give me a solution.

 public class Today_List_Adapter extends BaseAdapter {

private Activity activity;
static ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
AlertDialog.Builder alertDialog;
public ImageLoader imageLoader; 
String success,error;
JSONParser jsonParser = new JSONParser();
public Today_List_Adapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater =  (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
    return data.size();

}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.listof_today, null);

    TextView cartitle = (TextView)vi.findViewById(R.id.today_producttitle);
    ImageView carimage = (ImageView)vi.findViewById(R.id.today_productimage);
    TextView cardate = (TextView)vi.findViewById(R.id.today_productdate);
    TextView cartime = (TextView)vi.findViewById(R.id.today_producttime);
    TextView carddesc = (TextView)vi.findViewById(R.id.today_productdesc);
    final ImageView cardetails = (ImageView)vi.findViewById(R.id.today_productimage_detail);
    ImageView  carcheckin = (ImageView)vi.findViewById(R.id.today_productimage_attend);
    HashMap<String, String> Order = new HashMap<String, String>();
    Order = data.get(position);
    cartitle.setText(Order.get(TodayList.TAG_CAR_TITLE));
    cardate.setText(Order.get(TodayList.TAG_CAR_SDATE)+" "+"-"+" "+Order.get(TodayList.TAG_CAR_EDATE));
    cartime.setText(Order.get(TodayList.TAG_CAR_TIME));
    carddesc.setText(Order.get(TodayList.TAG_CAR_DESC));
    imageLoader=new ImageLoader(activity.getApplicationContext());
    imageLoader.DisplayImage(Order.get(TodayList.TAG_CAR_IMAGE), carimage);
    final String carid = Order.get(TodayList.TAG_CAR_ID);
    final String shareurl = Order.get(TodayList.TAG_CAR_EURL);
    final String plantoattend = Order.get(TodayList.TAG_CAR_STATUS);
    if ((!(LoginForm.GoogleId.equalsIgnoreCase("No user found")))
            || (!(LoginForm.FacebookId.equalsIgnoreCase("No user found")))
            || (!(CommonUtils.login_status
                    .equalsIgnoreCase("No user found")))) {  
        if(plantoattend.equalsIgnoreCase("N")){
        cardetails.setImageResource(R.drawable.attend);
    }
    else {
        cardetails.setImageResource(R.drawable.unattend);
    }
    }
    else {
        cardetails.setImageResource(R.drawable.attend);
    }
    cardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

                    if(plantoattend.equalsIgnoreCase("N")){
    alertDialog = new AlertDialog.Builder(activity);
               alertDialog.setMessage("You're going! Do you want to share the meet?");
    alertDialog.setPositiveButton("Share", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int which) {
           Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, shareurl);
                sendIntent.setType("text/plain");
         cardetails.setImageResource(R.drawable.unattend);
                activity.startActivityForResult(Intent.createChooser(sendIntent, "Share via"),1000);
       }
      });
    alertDialog.setNegativeButton("Not now", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    cardetails.setImageResource(R.drawable.unattend);
    new AttendMeet().execute(carid);

    }
    });
    alertDialog.show();
            }
                 else{
                    if (cd.isConnectingToInternet()) {
                     new UnAttendMeet().execute(carid);
                    cardetails.setImageResource(R.drawable.attend);
                    //Today_List_Adapter.this.notifyDataSetChanged();
                    }
                     else {
                    alert.showAlertDialog(activity, "Internet Connection Error",
                            "Please Try Again Later", false);
                    return;
                }
                 }   
        }   
            }   
         });
    carcheckin.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, shareurl);
            sendIntent.setType("text/plain");
            activity.startActivity(sendIntent);
        }
     });
    return vi;

   }
  public void onActivityResult(int requestCode, int resultCode, Intent data,String... args) {
    //super.onActivityResult(requestCode, resultCode, data);

    switch(requestCode) {
    case 1000:
      Today_List_Adapter.this.notifyDataSetChanged();
        break;

    }

}

class AttendMeet extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(String... args) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user_id", CommonUtils.login_status));
            params.add(new BasicNameValuePair("event_id", args[0]));
            JSONObject json = jsonParser.makeHttpRequest(url_attendmeet,
                    "POST", params);
            Log.d("Attend Meet", json.toString());
            success = json.getString("status");
             if (success.equalsIgnoreCase("ok")) {
                }
             else
             {
                 error = json.getString("error");
             }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
         if (success.equalsIgnoreCase("ok")) {

             cardetails.setImageResource(R.drawable.unattend);

                Toast.makeText(activity.getApplicationContext(),
                        "The meet was successfully added on attending meet", Toast.LENGTH_LONG).show();
            }
             else
             {
                 Toast.makeText(activity.getApplicationContext(),
                            error, Toast.LENGTH_LONG).show();
             }

    }

   }
     class UnAttendMeet extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(String... args) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user_id", CommonUtils.login_status));
            params.add(new BasicNameValuePair("event_id", args[0]));
            JSONObject json = jsonParser.makeHttpRequest(url_unattendmeet,
                    "POST", params);
            Log.d("UnAttend Meet", json.toString());
            success = json.getString("status");
             if (success.equalsIgnoreCase("ok")) {

            }
             else
             {
                 error = json.getString("error");
             }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
         if (success.equalsIgnoreCase("ok")) {
             cardetails.setImageResource(R.drawable.attend);

                Toast.makeText(activity,
                        "The meet was successfully removed from attending meet", Toast.LENGTH_LONG).show();
            }
             else
             {

                 Toast.makeText(activity,
                            error, Toast.LENGTH_LONG).show();
             }

             }
          }

         }

EDIT:

I have updated my code.

Now i have run the application.,am getting the results like :

If the user clicking the attend image., the functionality will be done good then image was changed from attend to un-attend image.But again i have clicking the un-attend image ., it's need to do call the UnAttned class.But it's calling Attend class only. Can you please check my code and give me a solutions.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Krishna Veni
  • 2,217
  • 8
  • 27
  • 53
  • Did you debug that `cardetails.setImageResource` code is being executed or not while you click image? – MysticMagicϡ Sep 25 '14 at 04:30
  • @MysticMagic Am getting the toast message " "The meet was successfully added on attending meet". But the image not yet changed. – Krishna Veni Sep 25 '14 at 05:09
  • Try calling `yourAdapter.notifyDataSetChanged();` after `setImageResource` is called. – MysticMagicϡ Sep 25 '14 at 05:20
  • @MysticMagic yes i have tried that also. but the screen is flashed(refreshed) . but the image not yet changing...But i have verified the functionality is done.because if i have refresh the whole activity, the image was changed. – Krishna Veni Sep 25 '14 at 05:25
  • Ohk.. Then check if [this](http://stackoverflow.com/questions/19462651/change-selected-list-view-item-image-issue-in-android) helps.. – MysticMagicϡ Sep 25 '14 at 05:26
  • @KrishnaVeni check this http://stackoverflow.com/questions/20611123/listview-subobject-clickable-confilct might help – Raghunandan Sep 27 '14 at 06:21

1 Answers1

1

The underlying data needs to be changed too, in case the views get repopulated for some reason (e.g. notifyDataSetChanged() was called, scrolled out of view etc). Change this to fix the immediate problem (Order needs to be final):

...
cardetails.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        if (plantoattend.equalsIgnoreCase("N")) {
            alertDialog = new AlertDialog.Builder(activity);
            alertDialog.setMessage("You're going! Do you want to share the meet?");
            alertDialog.setPositiveButton("Share", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, shareurl);
                    sendIntent.setType("text/plain");
                    cardetails.setImageResource(R.drawable.unattend);
                    activity.startActivityForResult(Intent.createChooser(sendIntent, "Share via"), 1000);
                }
            });
            alertDialog.setNegativeButton("Not now", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Order.put(TodayList.TAG_CAR_STATUS, "Y"); // CHANGE THE UNDERLYING DATA HERE
                    cardetails.setImageResource(R.drawable.unattend);
                     new AttendMeet().execute(carid);

                }
            });
            alertDialog.show();
        } else {
            if (cd.isConnectingToInternet()) {
                new UnAttendMeet().execute(carid);
                Order.put(TodayList.TAG_CAR_STATUS, "N"); // CHANGE THE UNDERLYING DATA HERE
                cardetails.setImageResource(R.drawable.attend);
                //Today_List_Adapter.this.notifyDataSetChanged();
            } else {
                alert.showAlertDialog(activity, "Internet Connection Error",
                              "Please Try Again Later", false);
                return;
            }
        }
    }
});
...

However, I wouldn't want to leave this answer, knowing that there are a lot more problems you're going to run into:

  1. You shouldn't directly manipulate the ImageView like you did in onPostExecute. By the time your AsyncTask finishes, the view might have been recycled and populated with other data. Rather, change the underlying data and call notifiedDataSetChanged if necessary.
  2. AsyncTask, not keeping a reference to the (multiple!) AsyncTasks means, you won't be able to cancel them when the user leaves the activity/fragment early. This means anything touching the UI will crash the app. While it is absolutely possible to perform REST requests using AsyncTasks it's painful and gets complicated very quickly if you are performing more than a handful requests. Look into libraries like Retrofit or Volley.
  3. Finding views using findViewById is slow and will result in scroll lag, try the ViewHolder pattern.
  4. Storing data in a Map like you did works "somewhat", but is very un-Java-ish and you'll have to sprinkle your code with null checks, or risking null pointer exceptions. Use POJOs instead
  5. Adhere to naming conventions and make it easier for yourself and everyone else to read your code.

I didn't look up links for these points, but I will add them if requested.

Batuhan Coşkun
  • 2,961
  • 2
  • 31
  • 48
Suau
  • 4,628
  • 22
  • 28
  • In your case you can't reassign a different HashMap to Order, but you can still make changes to the key-values inside the HashMap. – Suau Oct 01 '14 at 03:01
  • I see your problem. ``HashMap Order = new HashMap();`` ``Order = data.get(position);`` makes no sense, just use ``final HashMap Order = data.get(position)`` – Suau Oct 01 '14 at 03:01
  • yes got it ...Thanks for your help...thanks a lot... activity.startActivityForResult(Intent.createChooser(sendIntent, "Share via"), 1000); this functionality is not calling in my adapter file...if possible did you check that ? – Krishna Veni Oct 01 '14 at 05:20
  • resoled that issue..Thank u so much :) – Krishna Veni Oct 01 '14 at 06:38