Reputation: 3201
Now I am doing an Android application.In my application I have to get the data from json page.This operation is taking time delay.So I have to show a progressbar until the fetching process is completed.I used the following code to show progressbar.
public void onCreate(Bundle savedInstanceState) {
//somecode
ProgressDialog progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading");
progressBar.show();
Thread thread = new Thread(this);
thread.start();
}
public void run() {
flag=GetFixtureDetailsJsonFunction();
handler.sendEmptyMessage(0);
}
protected boolean GetFixtureDetailsJsonFunction() {
//json parsing code
return true
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (flag==true) {
progressBar.dismiss();
}
}
};
Using this code I am getting exception.android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Upvotes: 2
Views: 2251
Reputation: 4670
AsyncTask is best way for getting response from xml or database. try like this,
private class DownloadQuestion extends AsyncTask<String, Void, String>
{
@Override
protected void onPreExecute()
{
pd = ProgressDialog.show(Activity_SplashScreen.this, "","Please wait...", true,false);
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls)
{
//Write background code here Code
return "";
}
@Override
protected void onPostExecute(String response1)
{
//Some Code.....
if (pd != null && pd.isShowing())
pd.dismiss();
}
}
Upvotes: 5
Reputation: 5157
You are trying to access the UI View from another thread which is not eligible.In this case this is your handler.
Instead of trying to access UI thread like this you should use an AsyncTask and do your progressDialog logic in it.
Upvotes: 1
Reputation: 43098
This is a bit strange way to implement this functionality. Instead of fixing that code I suggest you using AsyncTask, which was implemented right for that purpose. See here.
Upvotes: 1
Reputation: 128428
Instead i would suggest you to implement AsyncTask, which is known as Painless Threading in android.
Using this AsyncTask, you don't need to bother about managing Threads. And its easy!!
FYI, do as follows:
onPreExecute()
method.doInBackground()
method.onPostExecute()
method. You can also do display kinds of operation in this method.Upvotes: 1