0

I have PostData class to transmit data lat, long,mac,.. to the server which is being sent to it from the service class. In PostData class, the data is being processed with the aid of AsyncTask and HttpURLConnection.

Now I have a new activity where the user can send query to the server. To reach that I have to get ArrayList<Integer> from the server and create a something like checkbox list, where the user can select the desirable items then the data will be sent to the server to retrieve a result.

Can I implement a new Asyntask and HttpURLConnection to achieve that or I have to use my AsynTask and HttpURLCOnnection in the POstData class?

I appreciate any help.

My PostData class:

public class PostData {
    String jSONString;
    private AsyncTaskCallback callback;

    public PostData(AsyncTaskCallback callback) {
        this.callback = callback;
    }

    public String getjSONString() {
        return jSONString;

    }

    public void setjSONString(String jSONString) {
        this.jSONString = jSONString;
    }

    public void post_data(String jSONString, Context context) {
        this.jSONString = jSONString;

        new MyAsyncTask(context).execute(jSONString);

    }

    class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
        final Context mContext;
        ArrayList<Integer> routes = new ArrayList<Integer>();
        double distance;

        public MyAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected ArrayList<Integer> doInBackground(String... params) {
            BufferedReader reader = null;

            try {

                URL myUrl = new URL(
                        "https://bustracker.rhcloud.com/webapi/test");

                HttpURLConnection conn = (HttpURLConnection) myUrl
                        .openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.connect();

                DataOutputStream wr = new DataOutputStream(
                        conn.getOutputStream());
                wr.writeBytes(params[0]);

                wr.close();

                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }

                Gson gson = new Gson();
                StopsJSON data = gson.fromJson(sb.toString(), StopsJSON.class);

                routes = data.getRoutes();
                distance = data.getDistance();
                System.out.println("The output of the StringBulder: "
                        + sb.toString());

            } catch (IOException e) {

                e.printStackTrace();
                return null;
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                        return null;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            return null;

        }

        protected void onPostExecute(ArrayList<Integer> result) {

             if (routes != null && !routes.isEmpty()) {
            callback.onAsyncTaskFinished(routes, distance);
             }else{
                 Log.e("123", "Avoiding null pointer, the routes are null!!!");
             }
        }

    }

}

1 Answer 1

3

This may set you on a path of some code refactoring, but for general good practice regarding REST requests you should look into Volley, or Retrofit, (also another SO question regarding retrofit that might help).

these libraries are very efficient performance-wise, and in the long run will save you a lot of grief, they take care of the background threading, and you won't necessarily need to explicitly use HttpUrlConnection.

Hope this helps.

Edit :

To further answer your question - if you do wish to specifically use AsyncTask - you should use the PostData class as a general purpose class, in your case for the network operations (might also possibly want to make it a Singleton, and give it a more general name).

and yes your implementation looks like you should be able to use it, and any corrections\changes\additions should be made in the AsyncTask itself under PostData, no need for another general class, if need be - you can just add more inner AsyncTask subclasses.

my (very very general) direction would be:

public class NetworkData {
String jSONString;
private AsyncTaskCallback callback;

public NetworkData(AsyncTaskCallback callback) {
    this.callback = callback;
}

public String getjSONString() {
    return jSONString;

}

public void setjSONString(String jSONString) {
    this.jSONString = jSONString;
}

//let's say this is for post requests...
public void postData(String jSONString, Context context) {
    this.jSONString = jSONString;

    new MyPostTask(context).execute(jSONString);

}

//let's say this is for get requests...
public void getData(String jSONString, Context context) {
    this.jSONString = jSONString;

    new MyGetTask(context).execute(jSONString);

}

class MyPostTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
    final Context mContext;
    ArrayList<Integer> routes = new ArrayList<Integer>();
    double distance;

    public MyPostTask(Context context) {
        mContext = context;
    }

    @Override
    protected ArrayList<Integer> doInBackground(String... params) 
    {
        try
        {
         //do you stuff for post requests...
        } catch (IOException e) 
        {
         //...
        } 
        finally 
            {
             //...
            }
        }
     }

class MyGetTask extends AsyncTask<String, Void, ArrayList<Object>> {
    final Context mContext;
    ArrayList<Object> routes = new ArrayList<Object>();

    public MyPostTask(Context context) {
        mContext = context;
    }

    @Override
    protected ArrayList<Object> doInBackground(String... params) 
    {
        try
        {
         //do you stuff for get requests...
        } 
        catch (IOException e) 
        {
         //...
        } 
        finally 
        {
         //...
        }
      }
    }
}

If you do choose to use Volley or Retrofit, then keep using the general class structure and just modify it's utilities and replace the requset format (i.e. instead of the AsyncTask parts).

3
  • 1
    I completely agree with you in terms of using a library specifically meant to simplify things. But that implementation still probably replaces whatever inside is post_data. And the question itself was whether he can use his general purpose PostData utility class from the activity. I think he should be able to use it. In the end it is just a utility class that fits his use case(s).
    – Raghu
    May 29, 2015 at 21:57
  • 1
    agreed, the AsyncTask itself might require some modification or addition, but the general purpose class is the way to go. I'll edit.
    – TommySM
    May 30, 2015 at 13:20
  • Huge plus (wish there was one) for going extra mile to write a neat helper class. It is such a good job that I can only nitpick the names post_data / get_data ;-)
    – Raghu
    Jun 1, 2015 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.