I am a noob to android trying to learn how to properly implement a progress dialog. I started with some code that queried and parsed twitter results before populating a listview during OnCreate. this worked perfectly. I wanted to to add a progress bar since it takes a few seconds, but ever since i added the progress bar my code has stopped working. I get nullpointer errors during parsing and my app crashes due to an error saying ” Only the original thread that created a view hierarchy can touch its views. ” Any help to resolve this is greatly appreciated.
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();
}
This means the Dialog is in a different Thread and you need a handler to mess with it, try adding the next line before the OnCreate() method:
Then on the OnCreate method, instantiate the handler so it is in the same thread as the dialog
Last, to update the dialog from a different thread you need to use the handler like this:
Hope this helps