【发布时间】:2014-02-09 12:04:07
【问题描述】:
我的 onCreate 方法中有这个:
String[] myStringArray = {"a","b","c","a","b","c","a","b","c","a","b","c","a","b","c","a","b","c"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_jokes);
new loadJson().execute();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myStringArray);
ListView listView = (ListView) findViewById(R.id.topJokesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
上面的代码用myStringArray的内容填充了一个listView,现在一切正常。当我调用new loadJson().execute(); 时,问题就来了,它执行得很好,这里是方法的代码:
public class loadJson extends AsyncTask<Void, Integer, String>{
@Override
protected String doInBackground(Void... params) {
URL u;
StringBuffer buffer = new StringBuffer();
try {
u = new URL("https://website.com/content/showContent.php");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
protected void onPostExecute(String buffer) {
JSONArray jsonArray = new JSONArray();
try {
jsonArray = new JSONArray(buffer);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JSONarray: " + jsonArray);
String[] newArray = null;
for (int i = 0; i < jsonArray.length(); i++) {
try {
newArray[i] = jsonArray.getJSONObject(i).toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
myStringArray = newArray;
}
}
如您所见,我正在使用提取到newArray 的新值更新myStringArray 的硬编码内容。现在我无法看到新内容。我知道它在那里,但我如何告诉当前活动:“嘿,我更新了你的数组,请显示!” ?
我知道我遗漏了一些非常小的东西,但作为初学者,我无法发现它。
【问题讨论】:
-
你在哪里打电话
adapter.notifyDataSetChanged();? -
我无法加入
adapter内部的onPostExecute -
为什么你不能访问只需将适配器实例声明为全局并在 onCreate 方法中初始化,然后你就可以访问整个类,包括内部类
-
我做不到:(
标签: java android android-asynctask android-activity