Shaardool
Shaardool

Reputation: 137

JSON to Android error

I have a successfully converted data from database into json format, my json data is as follows

{"room":[{"id":"1044","location":"kathmandu","title":"room room rome",
 "quantity":"2","price":"1000","contact":"9811111111","area":"1500",
"description":"kjkfs ksdjfsd kj","address":"kat"}],"success":1}

I want to view these data on android, my json parser code is

package com.iwantnew.www;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }          

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

my view room java file is intended to extract the json data

package com.iwantnew.www;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class viewroom extends ListActivity {

    // url to make request
    private static String url = "http://10.0.2.2/iWant/src/android_view_all_room.php";

    // JSON Node names
    private static final String TAG_ROOM = "room";
   // private static final String TAG_SUCCESS = "success";
    private static final String TAG_ID = "id";
    private static final String TAG_LOCATION = "location";
    private static final String TAG_TITLE = "title";
    private static final String TAG_QUANTITY = "quantity";
    private static final String TAG_PRICE = "price";
    private static final String TAG_CONTACT = "contact";
    private static final String TAG_AREA = "area";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_ADDRESS = "address";

    // contacts JSONArray
    JSONArray room = null;

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

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> roomList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);

        try {
            // Getting Array of Contacts
            room = json.getJSONArray(TAG_ROOM);

            // looping through All Contacts
            for(int i = 0; i < room.length(); i++){
                JSONObject c = room.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String location = c.getString(TAG_LOCATION);
                String quantity = c.getString(TAG_QUANTITY);
                String address = c.getString(TAG_ADDRESS);
                String price = c.getString(TAG_PRICE);
                String contact = c.getString(TAG_CONTACT);
                String area = c.getString(TAG_AREA);
                String description = c.getString(TAG_DESCRIPTION);
                String title = c.getString(TAG_TITLE);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_LOCATION, location);
                map.put(TAG_QUANTITY, quantity);
                map.put(TAG_ADDRESS, address);
                map.put(TAG_PRICE, price);
                map.put(TAG_CONTACT, contact);
                map.put(TAG_AREA, area);
                map.put(TAG_DESCRIPTION, description);
                map.put(TAG_TITLE, title);

                // adding HashList to ArrayList
                roomList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, roomList,
                R.layout.list_room,
                new String[] { TAG_TITLE, TAG_LOCATION, TAG_PRICE }, new int[] {
                        R.id.title, R.id.location, R.id.price });
        setListAdapter(adapter);
        // selecting single ListView item
        ListView lv = getListView();
        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
                String location = ((TextView) view.findViewById(R.id.location)).getText().toString();
                String price = ((TextView) view.findViewById(R.id.price)).getText().toString();            
                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleRoomActivity.class);
                in.putExtra(TAG_TITLE, title);
                in.putExtra(TAG_LOCATION, location);
                in.putExtra(TAG_PRICE, price);
                startActivity(in);
            }
        });
    }
}

the singleroom activity class is intended to show data about clicked room only, it is as follows

package com.iwantnew.www;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SingleRoomActivity extends Activity {


private static final String TAG_TITLE = "title";
private static final String TAG_LOCATION = "location";
private static final String TAG_PRICE = "price";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_room);

    // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String title = in.getStringExtra(TAG_TITLE);
    String location = in.getStringExtra(TAG_LOCATION);
    String price = in.getStringExtra(TAG_PRICE);

    // Displaying all values on the screen
    TextView lblTitle = (TextView) findViewById(R.id.title_label);
    TextView lblLocation = (TextView) findViewById(R.id.location_label);
    TextView lblPrice = (TextView) findViewById(R.id.price_label);

    lblTitle.setText(title);
    lblLocation.setText(location);
    lblPrice.setText(price);
}

}

and here is the log cat error i get. :(

http://pastebin.com/q4yQxKvF

Upvotes: 2

Views: 549

Answers (3)

BlackHatSamurai
BlackHatSamurai

Reputation: 23513

With ICS & beyond, you can't make network calls on the main thread (as you've noticed, it throws an error), which is why you need to use something like AsyncTask; or, you can create a new thread (using the Runnable class) to make your network call. Either way, you are not making the http call on the main thread. Even if you aren't using an ICS or JB device, you should never make network calls on the main thread.

From the Android docs:

Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.

Here is that link: http://developer.android.com/training/basics/network-ops/connecting.html

Upvotes: 0

Tarsem Singh
Tarsem Singh

Reputation: 14199

According to your code one Exception Which you will be getting is NetworkOnMainThreadException

Because you are performing Network operations on Main UI Thread

to Avoid it use AsyncTask inside view room java file

Check Example here AsyncTask Android example

Upvotes: 1

Kavin
Kavin

Reputation: 544

Try using the below code inside your viewroom activity below setContentView() to avoid networkOnmainThread exception..

if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

But, doing heavy operation inside background thread using AsyncTask without blocking main thread would be great!

Upvotes: 0

Related Questions