0

Please have a look at the following code

package com.example.jsontest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText editText;

/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    StrictMode.ThreadPolicy policy = new StrictMode.
    ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy); 

    setContentView(R.layout.activity_main);

    editText = (EditText)findViewById(R.id.edit_text);

    //Call The JSon
    try {
        JSONObject jObject = new JSONObject(getJson());


        int code = jObject.getInt("code");

        editText.append("Code: "+code+"\n");

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

  }

  private String getJson()
  {
      DefaultHttpClient   httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("https://bigml.io/andromeda/source/5277b1bd035d074e940056e0?username=xxx;api_key=xxxxxxxxxxxxxxx");
      // Depends on your web service
      httppost.setHeader("Content-type", "application/json");

      InputStream inputStream = null;
      String result = null;
      try {
          HttpResponse response = httpclient.execute(httppost);           
          HttpEntity entity = response.getEntity();

          inputStream = entity.getContent();
          // json is UTF-8 by default
          BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
          StringBuilder sb = new StringBuilder();

          String line = null;
          while ((line = reader.readLine()) != null)
          {
              sb.append(line + "\n");
          }
          result = sb.toString();
      } catch (Exception e) { 
          // Oops
      }
      finally {
          try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
      }

      return result;
  }
} 

In here, what I need to do is, print the "entire" result I retrieved. I wish to print the entire thing, I don't need to get separate values. How can I do this? Here is the link to the BigML retrieve documentation.

halfer
  • 19,824
  • 17
  • 99
  • 186
PeakGen
  • 21,894
  • 86
  • 261
  • 463

3 Answers3

6

Just use JSONObject.toString() ?

holtaf
  • 787
  • 6
  • 19
-1

So I ran your code, and it crashed. I also see that you are bypassing security and doing network operations in onCreate, in the main thread. This isn't a good idea in Android. Network operations should go in a background thread.

I refactored it very quickly to use a thread and it worked. Here is the code:

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    editText = (EditText)findViewById(R.id.edit_text);
  }

  @Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    new Thread(new Runnable() {

        @Override
        public void run() {
            JSONObject jObject;
            try {
                jObject = new JSONObject(getJson());
                // I am logging the raw value that was returned here
                Log.i("JSON Body", jObject.toString());
                int code = jObject.getInt("code");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }).start();
}

If you want to update the main thread (MainActivity) within the thread, create a Handler and pass a reference to that into the thread, and use that for updates.

David S.
  • 6,567
  • 1
  • 25
  • 45
  • This is generally good advice, but it doesn't answer the question that was asked. Also, NetworkOnMainThreadException are well-covered on Stackoverflow -- and using Threads directly is usually disparaged in favor of AsyncTasks. – 323go Dec 16 '13 at 16:32
  • @323go I did answer the question actually -- look at the line 'Log.i("MainActivity", jObject.toString());` -- this shows printing the string value of the JSON to the log. As to Thread vs. AsyncTask, I don't know that one is always better than the other. See http://stackoverflow.com/questions/18480206/asynctask-vs-thread-in-android for a thorough discussion of the merits of each. – David S. Dec 16 '13 at 18:25
  • It's still a poor answer as best, as the single line answer is buried deep inside code that's irrelevant to the quest asked. Even just replacing `"MainActivity"` with a useful tag would have improved this post. – 323go Dec 16 '13 at 19:09
-1

You should never connect to network on main thread. Best and the most simple option is to use AsyncTask<...>.

something like this:

private class DownloadProductsTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        try {
            return new PublicDataDBManager().retriveJsonData(mCode, mUserMail);
        } catch (Exception e) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result){
        buildData(result);// here you update mathod in your main thread
    }
}

Here is simple example: http://androide-examples.blogspot.com/2013/11/android-retrieve-json-data-from-url.html

5er
  • 2,506
  • 7
  • 32
  • 49