0

I want to make sure if there are better way of my below code , a way to send data to server the below is working , but can be better?

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {

        String json = "";
        String s_calc=String.valueOf(calc);;


        try {
            RequestBody formBody = new FormEncodingBuilder()
                    //  .add("tag","login")
                    .add("likes", "9")
                    .add("id", id)
                    .build();
            Request request = new Request.Builder()
                    .url("http://justedhak.com/old-files/singleactivity.php")
                    .post(formBody)
                    .build();
            Response responses = null;
            try {
                responses = client.newCall(request).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String jsonData = responses.body().string();
            JSONObject Jobject = new JSONObject(jsonData);

            int success = Jobject.getInt("success");
            if (success == 1) {
                // this means that the credentials are correct, so create a login session.
                JSONArray JAStuff = Jobject.getJSONArray("stuff");
                int intStuff = JAStuff.length();
                if (intStuff != 0) {
                    for (int i = 0; i < JAStuff.length(); i++) {
                        JSONObject JOStuff = JAStuff.getJSONObject(i);
                        //create a login session.
                   //     session.createLoginSession(name, pass);
                    }
                }

            } else {
                // return an empty string, onPostExecute will validate the returned value.
                return "";
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("MYAPP", "unexpected JSON exception", e);
        }

        //this return will be reached if the user logs in successfully. So, onPostExecute will validate this value.
        return "RegisterActivity success";
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // if not empty, this means that the provided credentials were correct. .
        if (!result.equals("")) {
            finish();
            return;
        }
        //otherwise, show a popup.
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this);
        alertDialogBuilder.setMessage("Wrong username or password, Try again please.");
    //    alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
      //      @Override
        //    public void onClick(DialogInterface arg0, int arg1) {
          //      alertDialog.dismiss();
         //   }
       // });
       // alertDialog = alertDialogBuilder.create();
       // alertDialog.show();
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Moudiz
  • 7,211
  • 22
  • 78
  • 156

2 Answers2

2

"Better" is subjective, but as @KenWolf pointed out, I believe the general consensus is that Retrofit is the way to go for accessing your server API. Retrofit is reliant on OkHttp, and can use a variety of converters to parse JSON for you (including Gson, and my preference Moshi). It is also compatible with RxJava (and RxAndroid), which can make a world of difference.

An alternative to Retrofit would be Volley by Google, though it is a much lower level of abstraction. Also, Google has not produced any similar supporting libraries that Retrofit has, and only supports Gson for de/serialization.

Bryan
  • 14,756
  • 10
  • 70
  • 125
  • 1
    @cricket_007 In terms of what? Google does maintain the Protocol Buffer APIs for [select languages](https://developers.google.com/protocol-buffers/docs/tutorials), but does not maintain any library for compatibility with `Retrofit` or `Volley`. Square does maintain a ProtoBuf library for `Retrofit` though. – Bryan Sep 15 '16 at 17:00
  • @Moudiz The [`Retrofit`](http://square.github.io/retrofit/) link I posted guides you through the setup and provides some basic examples. The [GitHub repo](https://github.com/square/retrofit) provides samples as well. As for serialization and deserialization, most (if not all) provide samples on their repositories as well. [u2020](https://github.com/JakeWharton/u2020) is also a great sample application made by Jake Wharton that uses `Retrofit`, `Moshi` and `RxAndroid` together, as well as `Dagger` for dependency injection. – Bryan Sep 15 '16 at 17:12
  • I was just pointing out the comment about Google only supporting Gson, but ProtoBuf is also another option – OneCricketeer Sep 15 '16 at 18:13
2

You already are using OkHttp. So, you don't even need an AsyncTask

OKHttp Recipes - Async GET can be used outside an AsyncTask. If you are explicitly using JSON requests though, then Retrofit or Volley make good alternatives.

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        Headers responseHeaders = response.headers();
        for (int i = 0, size = responseHeaders.size(); i < size; i++) {
          System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }

        System.out.println(response.body().string());
      }
    });
  }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I had problem with volley related to images and caching I don't rember exaclty, so with okhttp no need to use asyntask ever right? – Moudiz Sep 15 '16 at 20:24
  • There may be times when necessary, but I cannot think of any right now – OneCricketeer Sep 15 '16 at 20:28
  • 2
    @Moudiz [You should not use `AsyncTask` with `OkHttp`.](http://stackoverflow.com/a/27341320/5115932) – Bryan Sep 15 '16 at 20:33
  • @cricket_007 i am having error ` cannot resolve Callback` and I dont which one to import for it .. do you want a screenshot for the error ? in the documentation they ddint mention import or anyting – Moudiz Sep 15 '16 at 20:34
  • @Bryan There are really very few legitimate cases where using asynctask is still a good option. – njzk2 Sep 15 '16 at 20:35
  • @Moudiz Not sure what to tell you. The IDE should let you import `okhttp3.Callback` – OneCricketeer Sep 15 '16 at 20:47