Android Json 获取数据并保存到列表视图

Android Gson getch data and save into listview

我有这个简单的代码来使用 GSON 获取数据并保存到列表视图中:

protected void onPostExecute(List<behzad> beh) {
    mcountryx = tours;
    if (mcountryTours != null) {
        ListView listView1 = (ListView) findViewById(R.id.listView1);
        String[] items = { "Milk", "Butter", "Yogurt", "Toothpaste", "Ice Cream" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, items);
        listView1.setAdapter(adapter);
    }
}

此代码导致错误,消息框:

Can not resolve Constructor ArrayAdaptor...

而使用以下代码:

ListView listView1 = (ListView) findViewById(R.id.listView1);
String[] items = { "Milk", "Butter", "Yogurt", "Toothpaste", "Ice Cream" };

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, items);
listView1.setAdapter(adapter);

进入onCreateMethod,那个messageBox不显示! 你能解释一下发生了什么吗?感谢您关注我的问题。

我的 Class 是:

import com.google.gson.annotations.SerializedName;

public class behzad {

    @SerializedName("tourcountryname")
    public String CountryNamme;
    public TourCountry() {

    }

}

对于未来的用户,

您需要将 context 传递给 Adapter 构造函数。

你的onCreate()里面的

this指的是Activity,而onPostExecute()里面的this指的是AsyncTask(不是上下文),这就是为什么你有 Can not resolve Constructor ArrayAdaptor...

更改此行:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, items);

至:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(AcivityName.this,android.R.layout.simple_expandable_list_item_1, items);