2

I am using separate thread to get the json object from the url. but the problem is I would like to show the progress dialog while getting the result. I have create a progress dialog and called show and dismiss before and after thread execution. but progress dialog is not displaying. here is the way I have called my thread.

    private void getRecordsByCount(final String data) {
        try {
            // btnSelectall.setText(" ");
            int color=Color.BLACK;
            showProgressDialog();
            tableLayoutGrid.removeAllViews();
            final String[] details = data.split("_");
            SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            String formattedDate = df.format(new Date());
            String url = ipaddress + "/GrantLeavesList?Companyid=" + user_info.get("CompanyId") + "&divisionid=" + details[3] + "&userid=" + user_info.get("userid") + "&roleid="
                    + user_info.get("RoleId") + "&Employeeid=" + user_info.get("EmployeeId") + "&leavetypeid=" + staticDetails.get(details[0]) + "&strStatus=" + staticDetails.get(details[1])
                    + "&type=" + staticDetails.get(details[2]) + "&Date=" + formattedDate;
            JsonThread thread = new JsonThread(url);
            thread.start();
            // thread.setPriority(Thread.MAX_PRIORITY);
            thread.join();
            JSONObject obj = thread.returnResult();
            btnGrantSubmit.setVisibility(View.GONE);
            if (obj != null) {

                leaveforwardcounts = obj.getJSONArray("Table1");

                ScrollView scrollGrid = new ScrollView(this);
                TableRow datarow = new TableRow(this);
                datarow.setWeightSum(100);
                TableLayout table = new TableLayout(this);
                for (int i = 0; i < leaveforwardcounts.length(); i++) {
                    btnGrantSubmit.setVisibility(View.VISIBLE);
                    JSONObject record = leaveforwardcounts.getJSONObject(i);
                    String applicantname = record.getString("Applicant");
                    String toDate = record.getString("ToDate");
                    String noofdays = record.getString("NumberOfDays");
                    String LOP = record.getString("LOP");
                    if(LOP!=null && LOP.trim().length()!=0)
                    {
                        color=Color.RED;
                    }
                    final int id = i;
                    final Button gridbutton = new Button(this);
                    gridbutton.setText(status);
                    gridbutton.setTextColor(Color.BLACK);
                    gridbutton.setBackgroundResource(R.drawable.grdbutton_30x30);
                    gridbutton.setGravity(Gravity.CENTER);
                    gridbutton.setPadding(2, 0, 2, 0);
                    gridbutton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            changeRadioButtonState(gridbutton, id, data);
                        }
                    });
                    gridbutton.setOnLongClickListener(new OnLongClickListener() {

                        @Override
                        public boolean onLongClick(View v) {
                            setSelection(gridbutton);
                            return true;
                        }
                    });

                    TextView tvApplicantName = new TextView(this);

                    TextView tvToDate = new TextView(this);
                    TextView tvNoOfDays = new TextView(this);
                    TextView empty = new TextView(this);
                    TextView empty2 = new TextView(this);
                    if (applicantname.trim().length() >= 18) {
                        applicantname = applicantname.substring(0, 18);
                    }

                    tvApplicantName.setText(applicantname);
                    tvApplicantName.setTypeface(font2);
                    tvApplicantName.setWidth(70);
                    tvApplicantName.setTextColor(color);
                    tvApplicantName.setPadding(5, 0, 0, 0);

                    tvToDate.setText(toDate);
                    tvToDate.setTypeface(font2);
                    tvNoOfDays.setText(noofdays);
                    tvNoOfDays.setTypeface(font2);
                    tvNoOfDays.setGravity(Gravity.RIGHT);

                    Button ivDetails = new Button(this);
                    ivDetails.setText(" ");
                    ivDetails.setPadding(2, 0, 2, 0);
                    ivDetails.setBackgroundResource(R.drawable.detailsbutton_30x30);
                    ivDetails.setGravity(Gravity.CENTER);

                    ivDetails.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            leaveDetails = new PopupWindow(showLeaveDetails(id, leaveforwardcounts,data), (int) (width * 0.8), height / 2, true);
                            leaveDetails.showAtLocation(mainlayout, Gravity.CENTER, 0, 0);
                        }
                    });

                    TableRow row = new TableRow(this);

                    row.setPadding(0, 3, 0, 3);
                    row.setWeightSum(100);
                    row.addView(tvApplicantName, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 55));
                    row.addView(tvNoOfDays, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 5));
                    row.addView(empty2, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20));
                    row.addView(ivDetails, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
                    row.addView(empty, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
                    row.addView(gridbutton, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 5));
                    table.addView(row);
                }
                scrollGrid.addView(table);
                datarow.addView(scrollGrid, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 100));
                tableLayoutGrid.addView(datarow);
                dialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



package com.MobJax.dashboard;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONObject;


public class JsonThread extends Thread{
    boolean running=false;
    String url;
    JSONObject jobj=null;

    public JsonThread(String url)
    {
        this.url=url;
    }
    @Override
    public void run() {
        int k=0;

        URL url1;
        try {

            url1 = new URL(url);
            InputStream input=url1.openStream();
            BufferedInputStream bis=new BufferedInputStream(input);
            ByteArrayBuffer baf=new ByteArrayBuffer(1000);
            while((k=bis.read())!=-1)
            {
            baf.append((byte)k);

            }
            String results=new String(baf.toByteArray());
              jobj=new JSONObject(results);
            } 
        catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    public JSONObject returnResult()
    {
        return jobj;
    }

}
Pragnani
  • 20,075
  • 6
  • 49
  • 74
  • It is showing black screen while getting data – Pragnani Dec 19 '12 at 07:19
  • what is the use of `showProgressDialog();` and `tableLayoutGrid.removeAllViews();` in your code – Ram kiran Pachigolla Dec 19 '12 at 07:21
  • @Ramkiran I have a count.. when I click on that count corresponding number of records will populate in tablelayout, so what I am doing is removing the previous records of tablelayout. i have write a code to build progress dialog in showProgressDialog() method. – Pragnani Dec 19 '12 at 07:48
  • Also you can use _interface_ for this: here is an example: http://stackoverflow.com/a/14129332/1342413 – laplasz Jan 02 '13 at 21:33

2 Answers2

5

You can do it using AsyncTask..by adding the thread part into the doInBackground method..show the progress dialog in onPreExecute and dismiss it in onPostExecute..

ex:

public class MyTask extends AsyncTask<String, Void, String> {

private Context context;
private ProgressDialog progressDialog;

public MyTask (Context context) {
    this.context = context;
}

@Override
protected void onPreExecute() {
        progressDialog = ProgressDialog.show(context, "", "Loading...", true);
}

/* 
 * @see android.os.AsyncTask#doInBackground(Params[])
 */
@Override
protected String doInBackground(String... arg0) {
    //your json thread part
}

@Override
protected void onPostExecute(final String result) {
        progressDialog.dismiss();
}
}
Nermeen
  • 15,883
  • 5
  • 59
  • 72
  • By the way, the reason the original solution isn't working at the moment is because it calls Thread.start(), and immediately after that Thread.join(). So although you succeeded in putting your download work on a worker thread (thereby bypassing the exception you would get thrown if you were to do this on the main thread), you are still waiting for this download task to finish. This is actually equally bad ;-) since you are keeping the main thread occupied as long as your download is busy. For the rest, use Nunu's answer. – baske Dec 19 '12 at 07:31
  • @baske ,If I haven't called Thread.join(), the execution continues and the Json thread returning null, I need build the page based on the data from services....means I need to make use of data before starting screen. so I have called those services in onCreate...How to I show progressDialog before actually building the screen – Pragnani Dec 19 '12 at 07:45
  • @user: I understand the reason for calling Thread.join() and why you did that. However, you must understand that you are running this join() on the main thread, on which you should not perform blocking calls like that. This is because the main thread is not only used by you, but also for all sorts of other tasks, like putting your dialog on the screen. Never put (possibly) long running tasks on the main thread (including blocking calls) since they are just ANRs waiting to happen and make your UI sluggish. A utility class that can help you is the AsyncTask Nunu mentioned. Cheers! – baske Dec 20 '12 at 08:13
  • @baske thank you,, please see this question I have already tried asynctask but the result is same http://stackoverflow.com/questions/13966343/progress-dialog-is-not-displaying-in-async-task-when-asynctask-is-called-from-se/13966461#13966461 – Pragnani Dec 20 '12 at 08:36
0

Instead of you creating and handling a separate thread by yourself, use Asynctask. It will make your job easier. You can have a progress dialog displayed through out the execution of this async task and you can update the progress dialog from asynctask using publishProgress()

Karthik Andhamil
  • 848
  • 1
  • 13
  • 22
  • yeah but the problem is, I need to get the data from about 30 services... how do I make use of code reusability.. – Pragnani Dec 19 '12 at 07:21
  • AsyncTask is nothing but a thread. It is useful because Android takes care of what to call when. That's all. And do you want to get the data from 30 services 1 by 1? or 30 parallel threads? – Karthik Andhamil Dec 19 '12 at 07:33
  • One by one... and I need build the page based on the data from services....means I need to make use of data before starting screen. so I have called those services in onCreate...How to I show progressDialog before actually building the screen. – Pragnani Dec 19 '12 at 07:43
  • Create an empty activity without any data. call asynctask execute. have a for loop inside background method for 30 iterations. for each iteration call a publishprogress. from onprogressupdate(), update the UI. – Karthik Andhamil Dec 19 '12 at 07:46
  • sorry actually I haven't got what said.. please post any code snippet if available.. thank you – Pragnani Dec 19 '12 at 07:51
  • I don't have code right now. You just look at Nunu's answer, then google some examples for "android asynctask publishprogress()" then read my above comment for the steps to be followed. I think you will be able to write the code. – Karthik Andhamil Dec 19 '12 at 07:55