Varrian
Varrian

Reputation: 301

org.json.JSONException: End of input at character 0 of

I use the JSONObject forecast = new JSONObject(response.body().string()) to get the weather information, but android monitor always show "org.json.JSONException: End of input at character 0 of ".

 import android.app.AlertDialog;
 import android.app.Dialog;
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.Bundle;
 import android.os.Debug;
 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.Snackbar;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;
 import android.util.Log;
 import android.view.View;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.widget.Toast;


 import org.json.JSONException;
 import org.json.JSONObject;

 import java.io.IOException;

 import okhttp3.Call;
 import okhttp3.Callback;
 import okhttp3.OkHttpClient;
 import okhttp3.Request;
 import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if(isconnected()){
        String url = "https://api.forecast.io/forecast/2d0f15adaeff2c8e1343201418843890/37.8267,-122.423";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();


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

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()) {
                    Log.d(TAG, response.body().string());
                    String a=response.body().string();

                    try {
                        JSONObject forecast = new JSONObject(a);

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                } else {
                    alertUserAboutError();

                }


            }
        });
    }

    else{
        Toast.makeText(MainActivity.this,"LOST CONNECTION",Toast.LENGTH_SHORT).show();
    }



    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().hide();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

private boolean isconnected() {
    ConnectivityManager cm =
            (ConnectivityManager)MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
    return isConnected;

}

private void alertUserAboutError() {
    AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
    alertDialogFragment.show(getSupportFragmentManager(), "error");

}

}

I use the Log.d(TAG, response.body().string()) to test it is a string, but when in JSONObject forecast = new JSONObject(response.body().string()), it will not work.

Upvotes: 9

Views: 13592

Answers (5)

Christian C
Christian C

Reputation: 548

I had the same problem, my code looked like this

val myResponse = JSONObject(myBody)

I fixed it by checking that use myBody isn't empty/blank

Upvotes: 0

rimirdev
rimirdev

Reputation: 21

Sometimes the probleme is th URL, if your website forces HTTPS, you have to make sure that you are using an HTTPS URL in your APP, and vice-versa if your website doesn't support HTTPS, you have to use an HTTP URL.

Upvotes: 1

soshial
soshial

Reputation: 6808

For some weird reason if you use .string() >1 time, response turns out to be empty. Try to use it only once when parsing Retrofit response.

Someone, who knows why it happens like this, please improve my answer.

Upvotes: 20

Girish Bhalerao
Girish Bhalerao

Reputation: 636

Answer : Response object should of Generic type - ResponseBody.
See below Correct code for reference.
Now response.body() method will return object ResponseBody i.e.

ResponseBody rb = response.body(); 
rb.string();

Here ResponseBody have method string() which returns String object but internally string() method calls Util.closeQuietly(source); which makes response empty once method string() gets called.

Just remove Log.d(TAG, response.body().string()); and follow below code.


Reference - okhttp3.ResponseBody.java

error : org.json.JSONException: End of input at character 0

Correct code :

@Override
public void onResponse(Call call, Response<ResponseBody> response) throws IOException {
   if (response.isSuccessful()) {

      String remoteResponse=response.body().string();
      Log.d(TAG, remoteResponse);
      try {
          JSONObject forecast = new JSONObject(remoteResponse);
      } catch (JSONException e) { 
          e.printStackTrace();
      }
   }
}

Upvotes: 18

Varrian
Varrian

Reputation: 301

I have solved this problem after moving the "String a=response.body().string()" before "if (response.isSuccessful())".

Upvotes: 0

Related Questions