0

I am uploading an image from phone to server using okhttp3. I am uploading image using multiparty. I am trying to fetch response using this but the problem is this when I tried to get response in logcat it shows in "NetworkThreadException" and also I am not able fetch fields from response. I tried a lot of things but all in vain. I do not understand what to do.

Code:

     private void execMultipartPost() throws Exception {


    RequestBody requestBody;

    pBar.setVisibility(View.VISIBLE);

    SessionManager session = new SessionManager(getContext().getApplicationContext());
    HashMap<String, String> user = session.getLoggedUserDetails();
    String api_token = user.get("api_token");

    if (filePath != null) {
        File file = new File(filePath);
        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        filename = "file_" + System.currentTimeMillis() / 1000L;

        Log.e("TAG", "filename: " + filename);

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", filename + ".jpg", fileBody)
                .addFormDataPart("api_token", api_token)
                .addFormDataPart("name", etName.getText().toString())
                .addFormDataPart("introduction", etGoal.getText().toString())
                .addFormDataPart("advisor_id", user.get("id"))
                .addFormDataPart("category", etCompany_name.getText().toString())
                .addFormDataPart("expertise", user.get("specialist"))
                .addFormDataPart("experience", etAge.getText().toString())
                .addFormDataPart("fb_link", et_fb_link.getText().toString())
                .addFormDataPart("feed_link", et_rss_link.getText().toString())
                .addFormDataPart("youtube_link", et_youTube_link.getText().toString())
                .addFormDataPart("linkedin_link", et_linkdenLink.getText().toString())
                .addFormDataPart("email", etMail.getText().toString())


                .build();

    } else {


        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "null")
                .addFormDataPart("api_token", api_token)
                .addFormDataPart("name", etName.getText().toString())
                .addFormDataPart("introduction", etGoal.getText().toString())
                .addFormDataPart("advisor_id", user.get("id"))
                .addFormDataPart("category", etCompany_name.getText().toString())
                .addFormDataPart("expertise", user.get("specialist"))
                .addFormDataPart("experience", etAge.getText().toString())
                .addFormDataPart("fb_link", et_fb_link.getText().toString())
                .addFormDataPart("feed_link", et_rss_link.getText().toString())
                .addFormDataPart("youtube_link", et_youTube_link.getText().toString())
                .addFormDataPart("linkedin_link", et_linkdenLink.getText().toString())
                .addFormDataPart("email", etMail.getText().toString())

                .build();


    }


    okhttp3.Request request = new okhttp3.Request.Builder()
            .url("http://url")
            .post(requestBody)
            .build();


    OkHttpClient okHttpClient = new OkHttpClient();


    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pBar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), getResources().getString(R.string.some_error_occured), Toast.LENGTH_SHORT).show();


                    e.printStackTrace();
                }
            });
        }


        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {

                        String responseStr = response.body().string();
                        Log.e("TAG", "okhttp3run: " + responseStr);

                        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.article_uploaded_successfully), Toast.LENGTH_SHORT).show();
                        //   changeFragment(new FragmentMicroLearningAdviserArticle());
                        pBar.setVisibility(View.GONE);

                    } catch (Exception e) {

                        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.some_error_occured), Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                        pBar.setVisibility(View.GONE);
                    }
                }
            });
        }
    });
}

Response :

      {
"data": {
    "id": 14,
    "category": "ddf",
    "name": "D",
    "email": "",
    "mobile": "99",
    "introduction": "",
    "age": null,
    "gender": "F",
    "belongs_to": "A",
    "services": "12",
    "specialist": "PC",
    "fb_link": "",
    "linkedin_link": "",

   }

This is my response when I add log.e

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
D Developer
  • 73
  • 1
  • 9

1 Answers1

0

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask , or create a handler to execute the network call instead of running in the UiThread. Example for handler in your code :

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask , or create a handler to execute the network call instead of running in the UiThread.

Example for handler in your code :

private void execMultipartPost() throws Exception {

//your code till the else block here

okhttp3.Request request = new okhttp3.Request.Builder()
        .url("http://url")
        .post(requestBody)
        .build();


OkHttpClient okHttpClient = new OkHttpClient();
Handler mHandler = new Handler(Looper.getMainLooper());

okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, final IOException e) 
               mHandler.post(new Runnable() {
               @Override
                public void run() {
                    mTextView.setText(mMessage); // must be inside run()
                }
            });
        }

    @Override
    public void onResponse(Call call, final okhttp3.Response response) throws IOException {
                mHandler.post(new Runnable() {
                @Override
                public void run() {
                   try {

                    String responseStr = response.body().string();
                    Log.e("TAG", "okhttp3run: " + responseStr);

                    Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.article_uploaded_successfully), Toast.LENGTH_SHORT).show();
                    //   changeFragment(new FragmentMicroLearningAdviserArticle());
                    pBar.setVisibility(View.GONE);

                } catch (Exception e) {

                    Toast.makeText(getActivity(), 
                    getActivity().getResources().getString(R.string.some_error_occured), 
                    Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                    pBar.setVisibility(View.GONE);
                }

              }
        });
});

Do not run network calls on the main UI thread as it blocks the users from performing other tasks.

aditya
  • 165
  • 2
  • 12