Hacer que el código de Android/Java sea más eficiente: eliminar duplicados

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?

preguntado el 31 de julio de 12 a las 15:07

How you start AsyncTask can you post it. -

I edited at the very top, thanks! -

1 Respuestas

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.

Respondido 31 Jul 12, 15:07

Thanks, I think I have decided to go in a different direction that makes this process unnecessary. But you had a very well though creative answer that I believe would probably get someone on the right path. - elmaestrodelaslechugas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.