-1

I am using OkHttpClient to get the Staff List (in JSON form) as response using AsyncTask Function. After getting the response in AsyncTask funtion, while inserting staff list in database, I want to show the count on the screen. but it gives following error. I tried many solutions, but couldn't resolve.

Following is the synchronizeStaffList Activity that calls SenkronizeEt Funtion using handler. public class synchronizeStaffList extends AppCompatActivity {

DatabaseHelper gksDatabase;

TextView txtrecordValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_synchronize_staff_list);


    gksDatabase = new DatabaseHelper(this);
    txtrecordValue = (TextView) findViewById(R.id.txtrecordValue);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms
            SenkronizeEt();
        }
    }, 500);

    final Handler handler2 = new Handler();
    handler2.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms
            AlertDialog.Builder builder;
            builder = new AlertDialog.Builder(synchronizeStaffList.this);
            builder.setCancelable(false);
            if (progressStaffListInfo == 0) {
                builder.setMessage("Sunucu ile iletişim yok");
            } else if (progressStaffListInfo == 1) {
                builder.setMessage("Sicil/Personel listesi güncellendi");
            }
            builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // if user pressed "MINIMIZE", cancel this dialog & minimize the application
                    // while attendance process will keep working in the back
                    // finish();
                    startActivity(new Intent(synchronizeStaffList.this, synchronize.class));
                    finish();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }, 5000);
}

I uses second handler to show an alertbox.

Following the SenkronizeEt Function that call OkHttpHandler AsyncTask function to get the okHttpResponse/result public int progressStaffListInfo = 0; // 0: List no updated, 1: List updated,

private void SenkronizeEt() {
    progressStaffListInfo = 0;

    // Updating Staff List in device by calling webservices
    HashMap<String, String> Parametre = gksDatabase.GetParameter();
    final String urlStaffList = "http://127.0.0.1:8080/JAXRSJsonCRUDExample/rest/employees/" + Parametre.get("DeviceNo");

    OkHttpHandler handler = new OkHttpHandler();

    String jsonEmployeesList = null;
    try {
        jsonEmployeesList = handler.execute(urlStaffList).get();
    } catch (Exception e) {
        //tv.setText("sorry, something went wrong !");
    }


    if (progressStaffListInfo == 0) {
        Toast.makeText(synchronizeStaffList.this, "List Not Updated", Toast.LENGTH_SHORT).show();
    } else if (progressStaffListInfo == 1) {
        Toast.makeText(synchronizeStaffList.this, "List updated in database", Toast.LENGTH_SHORT).show();
    }
}

Here is the OkHttpHandler AsyncTask function that call the URL to get the response and then update it in database.

public class OkHttpHandler extends AsyncTask<String, Integer, String> {

    OkHttpClient client = new OkHttpClient();

    @Override
    protected String doInBackground(String... params) {

        Request.Builder builder = new Request.Builder();
        builder.url(params[0]);
        Request request = builder.build();

        try {
            Response response = client.newCall(request).execute();
            // return response.body().string();
            String jsonData = response.body().string();
            //JSONObject Jobject = new JSONObject(jsonData);
            //JSONArray Jarray = Jobject.getJSONArray("employees");
            JSONArray Jarray = new JSONArray(jsonData);

            //get the length of the json array
            int limit = Jarray.length();

            if (limit != 0) {
                gksDatabase.PersonsDelete();
                progressStaffListInfo = 1; // Staff List updated

            }

            for (int i = 0; i < limit; i++) {
                JSONObject object = Jarray.getJSONObject(i);

                //store the data into database
                // SId:StaffID  SNo:StaffNumber     SN:StaffName    CNo:CardNumber
                gksDatabase.PersonsSave(Integer.parseInt(object.getString("sid")), object.getString("sno"), object.getString("sn"),
                        object.getString("cno")
                );
                publishProgress((int) (((i+1) / (float) limit) * 100));
            }

            return jsonData;
        } catch (JSONException e) {
            progressStaffListInfo = 0;
        } catch (Exception e) {
            e.printStackTrace();
            progressStaffListInfo = 0;
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }
}

private void setProgressPercent(int progValue){
    txtrecordValue.setText(progValue);
}

In above AsyncTask function, it gives error when it try to display the count of entries inserted in database. Actually, not only this. if I set any thing (Like progressbar or count) on different thread, even then it stops till the asyncTask finishes its work. As an example AlertDialog handler also starts when AsyncTask function finishes all its work.

Following are the logs:

E/AndroidRuntime: FATAL EXCEPTION: main android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:249)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:3796)
at com.emiturk.gsk.synchronizeStaffList.setProgressPercent(synchronizeStaffList.java:172)
at com.emiturk.gsk.synchronizeStaffList.access$100(synchronizeStaffList.java:25)
at com.emiturk.gsk.synchronizeStaffList$OkHttpHandler.onProgressUpdate(synchronizeStaffList.java:167)
at com.emiturk.gsk.synchronizeStaffList$OkHttpHandler.onProgressUpdate(synchronizeStaffList.java:116)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4810)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method

Kindly help me out.

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
Jawad
  • 31
  • 1
  • 1
  • 5
  • 2
    The answer below is a tight one, but i would prefer String.valueOf(progValue); – Nik Myers Dec 01 '16 at 12:24
  • @NikMyers your way is right but it's will just be a little extra code , try reading this http://stackoverflow.com/questions/9159358/implicit-cast-to-string-tostring-and-int – Pavneet_Singh Dec 01 '16 at 12:33
  • @PavneetSingh IMHO it's more appealing to the eyes – Nik Myers Dec 01 '16 at 13:24
  • @PavneetSingh, i've started my suggestion with the The answer below is a right one, just misspelled word "right" i think that's an issue here, or what? – Nik Myers Dec 01 '16 at 13:49

1 Answers1

1

You cannot set int value on textView so it should be a String object so do it like

private void setProgressPercent(int progValue){
    txtrecordValue.setText(""+progValue);
}

""+ will implicitly convert your progValue to String as if first parameter is a string (which it is empty string "") along with + then other will be promoted to string

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • The error is removed, but it does not show the TextView on the screen where as its visibility is not INVISIBLE or GONE. The major problem with my code is that it stop progressbar or any thing once the asyctask function starts. and resumes every thing after its completion. For more clarity, kindly read the text written above LOGs – Jawad Dec 01 '16 at 12:57
  • @Jawad why freeze because you are using delay along with `handler` first for 500 millisecond and 2nd handler call will be executed after `5000` milliseconds so solution is simply use `post` instead of `postDelayed` for first handler call and for alterdialog , you don't have to executed dialog on some thread , simply put your alert dialog code in some function and call that function from `onPostExecute` , onPostExecute is part of asyncTaks so override it – Pavneet_Singh Dec 01 '16 at 13:09
  • @Jawad and about textview visibility, it's a issue with your xml , just put a log or toast inside `setProgressPercent` method so it's getting called or not ,if yes mean issue is with XML if no mean issue in your asyncTask – Pavneet_Singh Dec 01 '16 at 13:12