-1

I have a problem with some deprecated methods.(httpDefault)

What that i want is simple: i have url (json data) -> send request -> receive jsonObject.

i have no idea. i've already tried some tutorial, but it didn't work for me. ( 1. http://techlovejump.com/android-json-parser-from-url/ 2. https://www.youtube.com/watch?v=Fmo3gDMtp8s&list=PLsoBxH455yoZZeeza9TiG8I9dGP0zz5o9&index=4)

here is my sample code. just working with String data. (not from server data.)

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

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

       /* // url : http://www.jsoneditoronline.org/?id=a31f7f816285e14991e175fccd09a561
        * {
        *   "id":123,
        *   "name":abc,
        *   "status":"ok"
        * }
        */
        final String customJSON = "{\"id\":123,\"name\":abc,\"status\":\"ok\"}";

        try {
            JSONObject jsonObject = new JSONObject(customJSON);
            int id = jsonObject.getInt("id");
            String name = jsonObject.getString("name");
            String status = jsonObject.getString("status");
            Toast.makeText(MainActivity.this, "id #"+id+", name #"+name+", status #"+status, Toast.LENGTH_SHORT).show();

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

please give me your tips.

how do i get JSONObject (all i have just url). url : http://www.jsoneditoronline.org/?id=a31f7f816285e14991e175fccd09a561

bubu uwu
  • 463
  • 2
  • 12
  • 26

3 Answers3

2

The correct way to do this would be to wrap requests in a worker thread. One of the ways to do this is by using an AsyncTask. See http://developer.android.com/reference/android/os/AsyncTask.html for the android documented usage of this but it basically boils down to the following implementation:

A private subclass which extends AsyncTask which Implements the following methods:

  1. onPreExecute – Invoked on the UI thread before the task is executed and is used for setting stuff up (e.g showing the progress bar)

  2. doInBackground – The actual operation you want to perform which is fired immediately after onPreExecute

  3. onPostExecute – Invoked on the UI thread after doInBackground completes. This takes in the result from doInBackground as a parameter and can then be used on the UI thread.

An AsyncTask is used for operations which aren’t permitted on the UI thread such as:

  • Opening a socket connection
  • HTTP requests (such as HTTPClient and HTTPURLConnection)
  • Attempting to connect to a remote MySQL database
  • Downloading a file \ your JSON

Your current code is sitting in a method which will be created on the UI thread (which will throw a NetworkOnMainThreadException, so you need to move your code over to a thread which is running on the main thread, such as an AsyncTask, a Handler or something similar. I found JSON Parsing tutorial on AndroidHive very helpful when learning, and referring back to the Android Documentation.

Smittey
  • 2,475
  • 10
  • 28
  • 35
1

As smittey mentioned you need to use a background thread or using AsyncTask to do that request. To do the http request you can use library OkHttp and here is an exampele. Remember to use <uses-permission android:name="android.permission.INTERNET" /> in your manifest to access the Internet.

M.Baraka
  • 725
  • 1
  • 10
  • 24
1
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

    Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;


         new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... params) {

                StringBuilder responseString = new StringBuilder();
                try {
                    HttpURLConnection urlConnection = (HttpURLConnection) new URL("http://you_url_here").openConnection();
                    urlConnection.setRequestMethod("GET");
                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode == 200){
                        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            responseString.append(line);
                        }
                    }
                    urlConnection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return responseString.toString();
            }

            @Override
            protected void onPostExecute(String o) {
                Toast toast = Toast.makeText(context, (CharSequence) o, Toast.LENGTH_SHORT);
                toast.show();

                /* if your json structure this type then it will work now 
                * {
                *   "id":123,
                *   "name":abc,
                *   "status":"ok"
                * }
                */
                try {
                    JSONObject jsonObject = new JSONObject(o);
                    int id = jsonObject.getInt("id");
                    String name = jsonObject.getString("name");
                    String status = jsonObject.getString("status");
                    Toast.makeText(MainActivity.this, "id #"+id+", name #"+name+", status #"+status, Toast.LENGTH_SHORT).show();

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


            }
        }.execute("");
    }
}

You may try this. it worked for me, I hope it also work for you.

hmtmcse
  • 130
  • 1
  • 9