0

I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference at

com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)

Error shows this line textView.setText(jsonObject.getString("distance"));

My Code

 HttpResponse httpResponse;
    Button button;
    TextView textView;
    static JSONObject jsonObject = null ;
    String StringHolder = "" ;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        textView = (TextView)findViewById(R.id.textView);
        progressBar = (ProgressBar)findViewById(R.id.progressBar);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressBar.setVisibility(View.VISIBLE);
                new GetDataFromServerIntoTextView(MainActivity.this).execute();

            }
        });
    }

    public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
    {
        public Context context;
        public GetDataFromServerIntoTextView(Context context)
        {
            this.context = context;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {

            HttpClient httpClient = new DefaultHttpClient();
            String HttpURL = "https://api.myjson.com/bins/1cuzhn";
            // Adding HttpURL to my HttpPost oject.
            HttpPost httpPost = new HttpPost(HttpURL);

            try {
                httpResponse = httpClient.execute(httpPost);

                StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try{
                JSONArray jsonArray = new JSONArray(StringHolder);
                jsonObject = jsonArray.getJSONObject(0);



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

            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(Void result)
        {
            try {

               textView.setText(jsonObject.getString("distance"));

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            progressBar.setVisibility(View.GONE);

        }
    }
10
  • post your json.. Commented Aug 20, 2019 at 5:20
  • api.myjson.com/bins/1cuzhn Commented Aug 20, 2019 at 5:21
  • your jsonObjectis null Commented Aug 20, 2019 at 5:23
  • Can you correct my code Commented Aug 20, 2019 at 5:26
  • can you please post your json response Commented Aug 20, 2019 at 5:30

2 Answers 2

1

I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.

Add below dependencies // OKHTTP

implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'

and

public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String> 
          {
        public Context context;

        public GetDataFromServerIntoTextView(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... voids) {

            String strUrl = "https://api.myjson.com/bins/1cuzhn";
            String data = "";
            InputStream iStream = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(strUrl);

                // Creating an http connection to communicate with url
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();

                // Reading data from url
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                StringBuffer sb = new StringBuffer();

                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                data = sb.toString();

                br.close();

            } catch (Exception e) {
                Log.d(TAG, "Exception while downloading url " + e.toString());
            } finally {
                try {
                    iStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                urlConnection.disconnect();
            }
            return data;
        }


        @Override
        protected void onPostExecute(String data) {
            super.onPostExecute(data);
            try {
                if (data != null) {
                    JSONArray jsonArray = new JSONArray(data);

                    for (int i = 0; i < jsonArray.length(); i++) {

                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                        // Here is your all data of distance and time
                        Log.e(TAG, "distance " + jsonObject.get("distance"));
                        Log.e(TAG, "time " + jsonObject.get("time"));

                    }

                } else {
                    Log.e(TAG, "onPostExecute: null json object");
                }

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

        }
    } 
Sign up to request clarification or add additional context in comments.

3 Comments

You modified this code? Added anything in doinbackground?
Happy Coding :D
Go for Retrofit for Json parsing. Its easy and clean. you can avoid parsing using Retrofit
0

You are using POST request where as your api is expecting GET request Here is more details about GET and POST

HttpPost httpPost = new HttpPost(HttpURL);

replace this with following

 HttpGet request = new HttpGet(HttpURL);

To avoid crash replace your code with

 textView.setText(jsonObject.getString("distance"));

this

 textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.