progressDialog not dismissing after progressDialog.dismiss(); - java

I have a method which gets a string from a file and puts it inside String variable named username, because the reading from the file takes time, I want a progressDialog to appear untill the function is finished, the preogress dialog does appear but is not dismissed when I use progressDialog.dismiss();
This is the code:
public String loadUserFromFile(){
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Loading User");
progressDialog.show();
String username = "default";
String fileName = "savedUserFile.txt";
FileInputStream fis;
try {
fis = openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(inputStreamReader);
username = br.readLine();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
username = username.replaceAll("\\s+","");
progressDialog.dismiss();
return username;
}

The 1st thing to make sure that dialog is not null.
ProgressDialog mProgressDialog;
mProgressDialog = new ProgressDialog(thisActivity);
mProgressDialog.setCancelable(false);
//If you want to show progress dialog
public void showProgressDialog(String message) {
if (mProgressDialog != null) {
mProgressDialog.setMessage(message);
mProgressDialog.show();
}
}
//To dismiss progress dialog
public void dismissProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
Usage:
showProgressDialog("Loading");
or
dismissProgressDialog();

Related

Asking the user for a URL to receive a JSON

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.
I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response..... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
This is the thread where i got that code from:
Get JSON Data from URL Using Android?
Create a constructor in your async Task
private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}
use the url string in place of params[0]
And wherever you call your async task do it like this
new JSONTask(textView.getText()).execute()
This should solve it.
Else you can directly use the do in background variable params.
So the problem is that you are using a TextView. TextView does not recieve inputs.
EditText does.
Make these Changes:
TextView txtJson;
In your OnCreate change this:
txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute(txtJson.getText());
}
});
Now in your xml file change the Button to EditText.
Hope this helps.

OnClick event only works second time

I have a button that when used to run a asyntask class, I use it for set into a value in a textView. When he returns to the class that called the method, the value of the TextView caught and put in a Toast but the first time I click the Toast not appear any message, in the second works. What to do?
This is the method that calls the button
btnDadosPessoais.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pega = TextAux.getText().toString();
Toast.makeText(getActivity(), pega, Toast.LENGTH_SHORT).show();
gravarDadoss(view);
}
});
TV is my TextView, I'm putting a simple string
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}
Asyntask here
`public class BackgroudCadPessoa extends AsyncTask {
ProgressDialog dialog;
Context ctx;
String pega;
ConnectivityManager connectivityManager;
TextView tv;
BackgroudCadPessoa(Context ctx, View v) {
this.ctx = ctx;
dialog = new ProgressDialog(ctx);
tv = (TextView) v.findViewById(R.id.textAux);
}
#Override
protected void onPreExecute() {
connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
dialog.setMessage("Aguarde...");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
if (connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isAvailable() && connectivityManager.getActiveNetworkInfo().isConnected()) {
String urls = "my URL";
String nome = params[0];
try {
URL url = new URL(urls);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
return "Sem acesso à Internet";
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}
public void valida(String js)
{
JSONArray jsonArray;
if (js.equals(null)) {
tv.setText("Erro ao Cadastrar");
} else {
try {
JSONObject jo = new JSONObject(js);
jsonArray = jo.getJSONArray("Resposta");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
pega = jsonObject.getString("resposta");
count++;
}
if (pega == null)
{
tv.setText("Erro ao Cadastrar");
}
else if (pega.equals("Dados Cadastrados"))
{
tv.setText("Dados Cadastrados");
}
else if (pega.equals("Erro ao Cadastrar"))
{
tv.setText("Erro ao Cadastrar");
}
else
{
tv.setText("Dados Cadastrados");
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
}
`
You want your Toast to appear AFTER your AsyncTask finishes its output to TextAux?
Then you need to put your toaster in the onPostExecute
#Override
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
Toast.makeText(getActivity(), resposta, Toast.LENGTH_SHORT).show();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}

How do i set an ImageView to show an image from an image url?

When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.

OnPostExecute not getting string

The contents of the string descript is showing up in logcat with no problems but won't display on the textview in the dialog located in OnPostExecute. It's a nullpointer exception. I'm not sure why since the episode string works just fine. Can anyone tell me why?
class getDescContent extends AsyncTask<Void, Void, Void> {
FileInputStream input = null;
String episode = null;
String descript = null;
#Override
protected Void doInBackground(Void... arg0) {
try {
input = new FileInputStream(descFile);
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
if (line.length() < 50) {
episode = line;
continue;
}
descript = line;
Log.i("", descript);
}
input.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) findViewById(R.id.dialog_text);
descrip.setText(descript);
dialog.show();
}
}
You should use
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) dialog.findViewById(R.id.dialog_text); //change in this line
descrip.setText(descript);
dialog.show();
Since the textview is not in the layout of the activity but in the layout of the dialog.
In your code, descrip is null, because it cannot be found.

Android progress dialog not closing

I want to show progress dialog in the page layout. I implemented in the following code. Progress Dialog is not closed and it keeps running.When I click an image in the previous page it will navigate to the next layout and I want this layout to show progress dialog before all the data is downloaded from server and show it in the list of the current layout. Progress dialog is displayed and list is displayed in the background but progress dialog keeps on running and it does not get closed. I don't know where i am going wrong. Help please.
ProgressDialog pg;
String[] ar;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filename);
pg=ProgressDialog.show(this, "ABC", "Downloading .....",true);
Thread dt= new Thread(new Runnable()
{
public void run()
{
try
{
String addr=Util.url;
URL url = new URL(urlname);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String x = "";
String total = "";
int i=0;
ArrayList<String> content = new ArrayList();
while((x = r.readLine()) != null)
{
content.add(x);
}
in.close();
r.close();
ar= content.toArray(new String[content.size()]);
}
catch(Exception e1){
handler.sendEmptyMessage(0);
}
}
});
dt.start();
try{
dt.join();
}catch(Exception e){
handler.sendEmptyMessage(0);
}
try{
if(ar[0].toString().trim()!="")
{
android.view.Display display1 = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
TableLayout tbl1 = (TableLayout)findViewById(R.id.tableLayout2);
TableRow newRow1 = (TableRow) new TableRow(this);
TextView txt=(TextView) new TextView(this);
txt.setText("No");
txt.setGravity(Gravity.LEFT);
txt.setTextColor(Color.RED);
txt.setTextSize(18);
TextView txt1=(TextView) new TextView(this);
txt1.setText("NAME");
txt1.setTextColor(Color.RED);
txt1.setTextSize(18);
txt1.setGravity(3);
TextView txt2=(TextView) new TextView(this);
txt2.setText("DATE");
txt2.setTextColor(Color.RED);
txt2.setTextSize(18);
txt.setGravity(3);
TextView txt3=(TextView) new TextView(this);
txt3.setText("VALUE");
txt3.setTextColor(Color.RED);
txt3.setTextSize(18);
txt3.setGravity(Gravity.RIGHT);
txt.setWidth((int)(display1.getWidth()/4));
txt1.setWidth((int)(display1.getWidth()/4));
txt3.setWidth((int)(display1.getWidth()/4));
txt2.setWidth((int)(display1.getWidth()/4));
newRow1.addView(txt2);
newRow1.addView(txt);
newRow1.addView(txt1);
newRow1.addView(txt3);
tbl1.addView(newRow1);
for(int t=0;t<(ar.length);t++)
{
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
TableLayout tbl = (TableLayout)findViewById(R.id.tableLayout1);
TableRow newRow = (TableRow) new TableRow(this);
newRow.setClickable(true);
TextView tx=(TextView) new TextView(this);
String temp=ar[t].toString();
tx.setText(temp);
tx.setTextColor(Color.WHITE);
tx.setGravity(Gravity.LEFT);
tx.setTextSize(15);
t=t+1;
TextView tx1=new TextView(this);
tx1.setText(ar[t].toString());
tx1.setGravity(Gravity.LEFT);
tx1.setTextColor(Color.WHITE);
tx1.setTextSize(15);
t=t+1;
TextView tx2=new TextView(this);
tx2.setText(ar[t].toString());
tx2.setGravity(Gravity.LEFT);
tx2.setTextColor(Color.WHITE);
tx2.setTextSize(15);
t=t+1;
TextView tx3=new TextView(this);
tx3.setText(ar[t].toString());
tx3.setGravity(Gravity.RIGHT);
tx3.setTextColor(Color.WHITE);
tx3.setTextSize(15);
tx3.setWidth((int)(display.getWidth()/4));
tx.setWidth((int)(display.getWidth()/4));
tx1.setWidth((int)(display.getWidth()/4));
tx2.setWidth((int)(display.getWidth()/4));
newRow.addView(tx);
newRow.addView(tx2);
newRow.addView(tx1);
newRow.addView(tx3);
newRow.setId(t);
tbl.addView(newRow);
}
}
}
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Toast.makeText(this,"Network not available!.... ", Toast.LENGTH_LONG).show();
}
};
Add this line to where ever you want to dismiss your dialog.
if(pg.isShowing())pg.dismiss();
You are closing the ProgressDialog on Exception of Try clause
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
That's why without Exception this won't close
replace this :
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
to this :
catch(Exception e){
handler.sendEmptyMessage(0);
}
pg.dismiss();
try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Sample code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
//Show UI
//Start your progress bar
showProgress();
}
#Override
protected Void doInBackground(Void... arg0) {
// do your bg process
return null;
}
#Override
protected void onPostExecute(Void result) {
//Show UI
//dismiss your progress bar
hideProgress();
}
};
task.execute((Void[])null);
Show and hide progress dialog code
public void showProgress() {
progressDialog = ProgressDialog.show(this, "",
"Loading. Please wait...");
progressDialog.setCancelable(false);
}
public void hideProgress() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
I have go through your code, your progress dialog will exit if and only if your program throws an exception. put it out side of the catch block(after the catch block)
following code
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
should be changed to
catch(Exception e){
handler.sendEmptyMessage(0);
}finally{
pg.dismiss();
}
if above is not working try to shift the finally block to inside the thread's run method as shown in following..
Thread dt= new Thread(new Runnable()
{
public void run()
{
try
{
String addr=Util.url;
URL url = new URL(urlname);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String x = "";
String total = "";
int i=0;
ArrayList<String> content = new ArrayList();
while((x = r.readLine()) != null)
{
content.add(x);
}
in.close();
r.close();
ar= content.toArray(new String[content.size()]);
}
catch(Exception e1){
handler.sendEmptyMessage(0);
}finally{
pg.dismiss();
}
}
});
Use an AsyncTask and move all the network related code in doInBackground(). Show the ProgressDialog in onPreExecute() of AsyncTask and hide it in onPostExecute().
public class DownloadTask extends AsyncTask<String, Void, Response> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog(R.string.please_wait);
}
#Override
protected Response doInBackground(String... params) {
try {
// Do the network stuff here
} catch (Exception ex) {
// Handle exception
}
return result;
}
#Override
protected void onPostExecute(Response result) {
super.onPostExecute(result);
hideProgressDialog();
// Do the response handling here
}
}
private void showProgressDialog(int resId) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.setMessage(getString(resId));
} else {
progressDialog = ProgressDialog.show(this, "", getString(resId), false);
}
}
private void hideProgressDialog() {
try {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage(), ex);
}
}
Hope it helps.
I finally found the solution. I preferred to go for threads since the data to fetch from the server is huge and need to be dynamically assigned to fields.
Thread thread = new Thread() {
public void run () {
try
{
pg.show();
//long running task
}
catch(){
}
handler.post(new Runnable() {
#Override
public void run() {
//code for Update UI after the long running task
// dismiss the progress dialog on UI thread
pg.dismiss();
}
});
}
};
thread.start();

Categories

Resources