1

How can I pass an Image resource Id to my custom adapter? I have a check box in an activity called routedetails . When the checkbox is checked I want to display a check mark next to that item in the listview. But to do this I need to pass the imageId to the custom adapter. I tried doing it with an intent putExtra. But that does not work.

Heres my RouteDetails.java with the checkbox code

public class RouteDetails extends AppCompatActivity {

ImageView routeImage;
String routeName;
CheckBox routeCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_details);

    //back button for route details view
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    ///////checkbox///////////////////////////////////////////
   routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);
  //////  final ImageView checkImageView = (ImageView) findViewById(R.id.checkImageView);
    routeCheckBox.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view)
    {
      if (routeCheckBox.isChecked())
      {
          //checkImageView.setImageResource(R.drawable.checkmark);
          Intent check = new Intent(RouteDetails.this,CustomAdapter.class);
          check.putExtra("checkImageResource", R.drawable.checkmark);
          startActivity(check);
        /////////////////////////////////////////////


//sets actionbar title
routeName = getIntent().getExtras().getString("routeName");
getSupportActionBar().setTitle(routeName);

//TextView for route details
final TextView routeDetailsView = (TextView) findViewById(R.id.routeDetailsView);
routeDetailsView.setText(getIntent().getExtras().getCharSequence("route"));

//ImageView for route details
routeImage = (ImageView) findViewById(R.id.routeImage);
final int mImageResource = getIntent().getIntExtra("imageResourceId", 0);
 routeImage.setImageResource(mImageResource);

And here's the custom adapter

  class CustomAdapter extends ArrayAdapter<CharSequence>{

   public CustomAdapter(Context context, CharSequence[] routes) {
    super(context, R.layout.custom_row ,routes);
   }

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}

CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);

////////trying to set checkmark/////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
checkImageView.setImageResource(((Activity)    getContext()).getIntent().getIntExtra("checkImageResource",0));
 ////////////////////////////////////////

return customView;
} 

And here's the adapter being used in my main activity

  list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);

//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);

Any help would be appreciated

zsh5032
  • 141
  • 1
  • 10
  • paste your log cat error when you run the code – ctu Dec 02 '16 at 17:48
  • I won't be able to do that until later tonight I'm away from my computer now. But it says customAdapter is not an activity so I can't use this line of code: checkImageView.setImageResource(((Activity) getContext()).getIntent().getIntExtra("checkImageResource",0)); I have no idea if I'm even on the right track with trying to do what I'm doing. Is there a simpler way? – zsh5032 Dec 02 '16 at 17:55
  • That's exactly the point I wanted to highlight . You can't call startactivity() method on a non-actvitvy class. You can check this [tutorial](http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html). I guess this what you want to do. – ctu Dec 02 '16 at 18:21
  • Thanks. Listviewcheckbox isn't exactly what I'm looking for. I'll try and explain better. When you click on a listview item it opens a new activity. In the new activity there's a checkbox. When I check the box and then hit the back button I want a check mark image to display Nex to that listview item. I placed an image view in each listview row. I want to be able to control the image based on the checkbox – zsh5032 Dec 02 '16 at 18:39
  • Do you want to set a check mark on your list item once you click on the details page? Or will the details page decide what kind of image to use back in the list? – Hahn Dec 02 '16 at 19:02
  • The details page will decide what image is used on the list. – zsh5032 Dec 02 '16 at 19:04
  • I will post an answer shortly. – ctu Dec 02 '16 at 20:44
  • check my answer and give me your feedback – ctu Dec 02 '16 at 22:22

1 Answers1

0

Basically you create two activities. Let say, MyListViewActivity containing a ListView whose items are nothing but custom views which hold an ImageView and a TextView; then a CheckBoxActivity holding the CheckBox elements. When a list item is clicked in MyListViewActivity, you start the CheckboxAtivity using startActivityForResult() method.

Finaly, in the CheckBoxActivity when a checkBox item is checked its textValue is send back to MyListViewActivity for updating the corresponding imageView. See below code snippets:

Layout file for MyListViewActivity : activity_my_list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_my_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="YourPackageNameHere.MyListViewActivity" >

<ListView
 android:id="@+id/list"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" >
</ListView>

</RelativeLayout>

Layout file for custom list item: list_single.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/img"
            android:layout_width="40dp"
            android:layout_height="40dp"/>

        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_gravity="center_horizontal|center_vertical" />

    </LinearLayout>


</TableRow>
</TableLayout>

Layout file for CheckBoxActivity: activity_checkbox.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_checkbox"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="YourPackageNameHere.CheckboxActivity">

<CheckBox
    android:text="CheckBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:id="@+id/checkBox1" />
<CheckBox
    android:text="CheckBox2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/checkBox2" />
 </LinearLayout>

code for MyListViewActivity :

package YourPackageNameHere;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyListViewActivity extends AppCompatActivity {
ImageView img;
ListView list;
private static final int MY_REQUEST_CODE= 1;
String[] itemNames = {
        "Google Plus",
        "Twitter",
        "Windows",
        "Bing",
        "Itunes",
        "Wordpress",
        "Drupal"
} ;
Integer[] imageId = {
        R.drawable.ic_home_black_18dp,
        R.drawable.ic_account_circle_black_18dp,
        R.drawable.ic_fingerprint_black_18dp,
        R.drawable.ic_help_black_18dp,
        R.drawable.ic_settings_black_18dp,
        R.drawable.ic_power_settings_new_black_18dp,
        R.drawable.ic_directions_run_black_18dp

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_list_view);

    CustomList adapter = new CustomList(MyListViewActivity.this, itemNames, imageId);
    list=(ListView)findViewById(R.id.list);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Toast.makeText(MyListViewActivity.this, "You Clicked at " + itemNames[+ position], Toast.LENGTH_SHORT).show();

            //get the image that has been clicked
            img= (ImageView) view.findViewById(R.id.img);

            //Starting the CheckBoxAtivity for  result
            Intent mIntent = new Intent(getBaseContext(), CheckboxActivity.class);
            startActivityForResult(mIntent, MY_REQUEST_CODE);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MY_REQUEST_CODE) {

        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
            switch (result){
                case "CheckBox1":
                    img.setImageResource(R.drawable.ic_gps_fixed_black_18dp);
                    break;
                case "CheckBox2":
                    img.setImageResource(R.drawable.cast_ic_notification_0);
                    break;
            }
        }

    }
}//onActivityResult

public class CustomList extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] itemNames;
    private final Integer[] imageId;
    public CustomList(Activity context, String[] itemNames, Integer[] imageId) {
        super(context, R.layout.list_single, itemNames);
        this.context = context;
        this.itemNames = itemNames;
        this.imageId = imageId;

    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView= inflater.inflate(R.layout.list_single, null, true);
        TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);

        ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
        txtTitle.setText(itemNames[position]);

        imageView.setImageResource(imageId[position]);
        return rowView;
    }
}
}

code for ChecboxActivity:

package YourPackageNameHere
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class CheckboxActivity extends AppCompatActivity {

CheckBox mCheckBox1;
CheckBox mCheckBox2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_checkbox);

    mCheckBox1 = (CheckBox) findViewById(R.id.checkBox1);
    mCheckBox2 = (CheckBox) findViewById(R.id.checkBox2);

    mCheckBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(mCheckBox1.isChecked()){
                sendResultToLisViewActivity((String) mCheckBox1.getText()); //send the text string of mCheckBox1 to MyListViewActivity
            }
        }
    });

    mCheckBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(mCheckBox2.isChecked()){
                sendResultToLisViewActivity((String) mCheckBox2.getText()); //send the text string of mCheckBox1 to MyListViewActivity
            }
        }
    });

}

public void sendResultToLisViewActivity(String  mStringExtra){
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result",mStringExtra);
    setResult(Activity.RESULT_OK,returnIntent);
    finish();
}
}

Lastly in your MainActivity onCreate() method you start MyListViewActivity as follows:

Intent i = new Intent(MainActivity.this, MyListViewActivity.class);
startActivity(i);

Ps: I referred to this link for creating the Custom ListView with Images and Text.

ctu
  • 308
  • 4
  • 12
  • Wow thanks for such a detailed response. I'm not my computer right now. I'll try and work on it later tonight and report back. So I guess I need to move my custom adapter into my main activity. Because right now it's in a seperate java file. – zsh5032 Dec 02 '16 at 22:32
  • Yes, your custom adapter should be called in the activity in which you have the listView. Just follow carefully the logic in the code I wrote and adapt it to your use case. [It does exactly what you explained in the comment above -:) ] – ctu Dec 02 '16 at 23:18
  • Hey so I followed your answer and I got it to mostly work! The only issue I'm having is that the check marks are showing up next to every listview item regardless of which item I'm checking the box from. But I should be able to get that worked out since I only had like 30min tonight to look at it. Thanks again for your help – zsh5032 Dec 03 '16 at 04:35