Thursday 21 November 2013

Android : Retrieve Json data from url

How to retrieve data as Json object from url in Android.
In this example when you click on the button and the system will retrieve data from url. For main Activity you can use the code from my other examples.
If there is something that is unclear, feel free to ask.







package com.example.testingdownload;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author Peter Gostincar
 */

public class MainFragment extends Fragment {
 
 private Button mCallButton;
 private TextView mTextView;
 private String mFetchedString;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
  View v = inflater.inflate(R.layout.fragment_main, parent, false);
  
  mTextView = (TextView) v.findViewById(R.id.view_text);
  
  mCallButton = (Button) v.findViewById(R.id.call_button);
  mCallButton.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    new FetchContent().execute();
   }
  });
  return v;
 }
 
 
 public void doUpdate() {
  if(getActivity() == null || mTextView == null)
   return;
  if(mFetchedString != null){
   mTextView.setText(mFetchedString);
  }
 }
 
 
 private class FetchContent extends AsyncTask {
  @Override
  protected String doInBackground(Void... params) {
   try {
    /** download data */
    return new Fetcer().retriveJsonData();
   } catch (Exception e) {
    // TODO: handle exception
   }
   return null;
  }

  @Override
  protected void onPostExecute(String result){
   mFetchedString = result;
   doUpdate();
  }
 }
}

package com.example.testingdownload;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * @author Peter Gostincar
 */

public class Fetcer {

 String url = "http://.../script_json.php (appended at the bottom)";
 private static final String JSON_ID = "id";
 private static final String JSON_NAME = "name";

 public byte[] getUrlBytes(String urlSpec) throws IOException{
  URL url = new URL(urlSpec);
  HttpURLConnection connection = (HttpURLConnection)url.openConnection();

  try {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   InputStream in = connection.getInputStream();

   if(connection.getResponseCode() != HttpURLConnection.HTTP_OK)
    return null;

   int bytesRead = 0;
   byte[] buffer = new byte[1024];
   while((bytesRead = in.read(buffer)) > 0){
    out.write(buffer, 0, bytesRead);
   }
   out.close();
   return out.toByteArray();

  } finally {
   connection.disconnect();
  }
 }

 
 public String retriveJsonData() {
  StringBuilder ret = new StringBuilder();
  try {
   String jsonString = (new String(getUrlBytes(url)));
   //Parse to json array
   JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
   for(int i = 0; i < array.length(); i++){
    JSONObject json = array.getJSONObject(i);
    ret.append(json.getString(JSON_NAME));
    ret.append(json.getInt(JSON_ID));
    ret.append(System.getProperty("line.separator"));
   }

   System.out.println();
  } catch (Exception e){
  }
  return ret.toString();
 }
}

activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />


fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <Button
        android:id="@+id/call_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="retrieve data" />



    <TextView
        android:id="@+id/view_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="do not forget to set Manifest -Network-" />


</LinearLayout>

<?php
$arr = array(
    array(
        "id" => "1",
        "name" => "Peter"
    ),
    array(
        "id" => "2",
        "name" => "Rok"
    ),
    array(
        "id" => "3",
        "name" => "Franci"
    )
);

echo json_encode($arr);
?>

2 comments:

  1. Hello Peter, this is very useful post, is this work in sliding menu fragments? 'cause i cant show JSON data in fragments. Can you help me please? Thanks

    ReplyDelete
    Replies
    1. Hi Mihriban, this holder should work in any fragment. But this code is old I would suggest you to go look at Gson lib, it makes mapping much easier: https://sites.google.com/site/gson/gson-user-guide.

      Regards

      Delete