我是 android 的菜鸟,试图学习如何正确实现进度对话框。我从一些在 OnCreate 期间填充列表视图之前查询和解析 twitter 结果的代码开始。这工作得很好。我想添加一个进度条,因为它需要几秒钟,但是自从我添加了进度条后,我的代码就停止了工作。我在解析过程中遇到空指针错误,并且我的应用程序由于错误说“只有创建视图层次结构的原始线程才能触及其视图”而崩溃。非常感谢任何解决此问题的帮助。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialog = new ProgressDialog (MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Loading... please wait");
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setProgress(0);
dialog.show();
Runnable runnable = new Runnable() {
@Override
public void run() {
tweets = new ArrayList<Tweet>();
try {
JSONObject jArray = JSONfunctions.getJSONfromURL("http://search.twitter.com/search.json?q=gold%20silver%20news&rpp=15");
JSONArray parsedTwitter = jArray.getJSONArray("results");
if(parsedTwitter.equals("") ){
Toast.makeText(MainActivity.this, "No nearby locations", Toast.LENGTH_LONG).show();
}else{
for (int i = 0; i < parsedTwitter.length(); i++) {
JSONObject parsedspecific = parsedTwitter.getJSONObject(i);
if (i == 0){
String from_user = parsedspecific.getString("from_user");
String text = parsedspecific.getString("text");
String profile_image_url = parsedspecific.getString("profile_image_url");
Tweet tweet0 = new Tweet(from_user, text, profile_image_url );
tweets.add(tweet0);
}
dialog.setProgress(50);
if (i == 1){
String from_user = parsedspecific.getString("from_user");
String text = parsedspecific.getString("text");
String profile_image_url = parsedspecific.getString("profile_image_url");
Tweet tweet1 = new Tweet(from_user, text, profile_image_url );
tweets.add(tweet1);
}
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
ListView listView = (ListView) findViewById(R.id.ListViewId);
listView.setAdapter(new UserItemAdapter(MainActivity.this, R.layout.listitem, tweets));
dialog.setProgress(100);
dialog.dismiss();
}
};
new Thread(runnable).start();
}