简体   繁体   中英

Passing value from MainActivity to custom listview adapter class

I want to pass a String value to my custom listview adapter class. I did it as according to the code below but it's not working.

MainActivity.java

private ArrayList<Item> generateData(String book_name)
{    
    MyAdapter adapter=new MyAdapter(getApplicationContext(),null);
    adapter.message = "hello"; 

MyAdapter.java

public class MyAdapter extends ArrayAdapter<Item> {

    public String message;

and then in the getView

@Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {            
        title.setText(itemsArrayList.get(position).getTitle());
        if(message == "hello")
        {
            //do something here
        }

Thanks for the help

What I think is happening is that your creating the adapter which calls getView before the message is set. So in your custom adapter you change the constructor so it takes the message.

public MyAdapter(Context context, Int resource, ArrayList<value> values, String message) {
    //your current code
    this.message = message 
}

The problem is that your string comparision is wrong. You should use equals method instead of == . So the comparision line should looks like this:

if ("hello".equals(message)) {
    //your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM