我在我的
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();
? - ρяσѕρєя KonPostExecute
中访问adapter
。 - chility