Search code examples
javaandroidjsoncode-duplication

Making Android/Java code more efficient - removing duplicate


I have a standard AsyncTask like this:

// starting AsyncTask in onCreate   
new TaskName().execute();


class TaskName extends AsyncTask<String, String, Void> {
    private ProgressDialog progressDialog = new ProgressDialog(Items.this);
    private InputStream is = null;
    private String result = "";

    protected void onPreExecute() {
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        progressDialog.setOnCancelListener(new OnCancelListener() {

            public void onCancel(DialogInterface dialog) {
                TaskName.this.cancel(true);

            }
        });
    }

    @Override
    protected Void doInBackground(String... params) {
        String url_select = "my_link.php";

        param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("Category", Category));

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url_select);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(param));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // read content
            is = httpEntity.getContent();

        } catch (Exception e) {

            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

        } catch (Exception e) {
            // TODO: handle exception
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        return null;

    }

    protected void onPostExecute(Void v) {

        try {

            JSONArray jArray = new JSONArray(result);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                item = json_data.getString("item");

                items.add(item);

            }
        } catch (JSONException e1) {
            Toast.makeText(getBaseContext(), "No items!",
                    Toast.LENGTH_SHORT).show();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

        progressDialog.dismiss();

    }
}

However, I find myself having three near identical AsyncTasks doing this same thing. Accessing a PHP file, parsing JSON & printing JSON.

I search for a while to see if there is a standard class out there I can use but I could not find any. Is there a way to make this more efficient so I am not repeating so many times?


Solution

  • Maybe this will help, I am not sure if this is what you are asking.

    I am not sure there is anything like that, but you can certainly develop a pattern based mechanism. For example, you could create an interface called DoInAsyncTask that has a method doIt on it. Then have your AsyncTask class take one of these in its constructor.

    Then in the onExecute method, it just calls doIt on the instance that was passed in to it.

    Then, put all the specialized code for the parsing of each JSON string into a set of different classes that implement the DoInAsyncTask interface.

    Then you only have one AsyncTask class and all the specialized code goes into the separate parsing classes and you just pass in the correct one when you instantiate the one AsyncTask Class you have.

    Hard to write, hope this makes some sense and is what you were asking.