Moudiz
Moudiz

Reputation: 7377

Alternative way than AsyncTask to send data to server

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();
    }
}

Upvotes: 0

Views: 579

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191710

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());
      }
    });
  }

Upvotes: 2

Bryan
Bryan

Reputation: 15155

"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.

Upvotes: 2

Related Questions