0

What is the error in this code?

I would like to add a facebook page name and get its json data, but there is something error I cannot discover. These are all files I use and added logcat messages:

PagesActivity.java

package com.engahmedphp.facebookcollector;

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

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class PagesActivity extends Activity {

    DatabaseHandler db = new DatabaseHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pages);

        final Button button = (Button) findViewById(R.id.addPage);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AlertDialog.Builder alert = new AlertDialog.Builder(
                        PagesActivity.this);

                alert.setTitle("Add New Page");
                alert.setMessage("Enter Page Name OR Valid Facebook Link");

                // Set an EditText view to get user input
                final EditText input = new EditText(PagesActivity.this);
                alert.setView(input);

                alert.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                String value = input.getText().toString();
                                // Do something with value!
                                String url = "http://graph.facebook.com/"
                                        + value + "/?fields=picture,name";
                                // Creating JSON Parser instance
                                JSONParser jParser = new JSONParser();

                                // getting JSON string from URL
                                JSONObject json = jParser.getJSONFromUrl(url);

                                try {
                                    // Storing each json item in variable

                                    String name = json.getString("name");
                                    String fid = json.getString("id");
                                    String picture = json
                                            .getJSONObject("picture")
                                            .getJSONObject("data")
                                            .getString("url");

                                    db.addPage(name, fid, picture);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                // addPageData(value);
                            }
                        });

                alert.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                // Canceled.
                            }
                        });

                alert.show();
            }
        });

    }

    void addPageData(String pageName) {
        String url = "http://graph.facebook.com/" + pageName
                + "/?fields=picture,name";
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Storing each json item in variable

            String name = json.getString("name");
            String fid = json.getString("id");
            String picture = json.getJSONObject("picture")
                    .getJSONObject("data").getString("url");

            db.addPage(name, fid, picture);

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.splash, menu);
        return true;
    }

}

JSONParser.java

package com.engahmedphp.facebookcollector;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
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() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            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;

    }
}

LogCat

08-31 03:35:23.031: D/dalvikvm(15972): GC_FOR_ALLOC freed 39K, 6% free 2633K/2792K, paused 65ms, total 68ms
08-31 03:35:23.041: I/dalvikvm-heap(15972): Grow heap (frag case) to 3.767MB for 1136500-byte allocation
08-31 03:35:23.163: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 5% free 3740K/3904K, paused 116ms, total 116ms
08-31 03:35:23.511: D/gralloc_goldfish(15972): Emulator without GPU emulation detected.
08-31 03:35:26.611: I/Choreographer(15972): Skipped 30 frames!  The application may be doing too much work on its main thread.
08-31 03:39:40.903: D/dalvikvm(15972): GC_FOR_ALLOC freed 47K, 4% free 4013K/4180K, paused 48ms, total 81ms
08-31 03:39:40.903: I/dalvikvm-heap(15972): Grow heap (frag case) to 4.638MB for 635812-byte allocation
08-31 03:39:41.023: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 4% free 4631K/4804K, paused 111ms, total 111ms
08-31 03:39:41.483: I/Choreographer(15972): Skipped 83 frames!  The application may be doing too much work on its main thread.
08-31 03:39:48.701: D/AndroidRuntime(15972): Shutting down VM
08-31 03:39:48.701: W/dalvikvm(15972): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
08-31 03:39:48.741: E/AndroidRuntime(15972): FATAL EXCEPTION: main
08-31 03:39:48.741: E/AndroidRuntime(15972): android.os.NetworkOnMainThreadException
08-31 03:39:48.741: E/AndroidRuntime(15972):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at com.engahmedphp.facebookcollector.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at  com.engahmedphp.facebookcollector.PagesActivity$1$1.onClick(PagesActivity.java:49)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at android.os.Looper.loop(Looper.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at android.app.ActivityThread.main(ActivityThread.java:5103)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at java.lang.reflect.Method.invokeNative(Native Method)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at java.lang.reflect.Method.invoke(Method.java:525)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 03:39:48.741: E/AndroidRuntime(15972):    at dalvik.system.NativeStart.main(Native Method)
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
eng.ahmed
  • 905
  • 4
  • 16
  • 38

4 Answers4

2

You are getting NetworkOnMainThreadException. See How to fix android.os.NetworkOnMainThreadException? . This exception is thrown when an application attempts to perform a networking operation on its main (UI) thread. Do the networking tasks using AsyncTask or inside a new thread. See the Android Documentation on NetworkOnMainThreadException for reasons of this Exception.

Here:

// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

you are doing network related stuff on main UI thread. Try to do this in a new thread.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • are there any problem to parse json data in onclicklistener ?? i thought this is the error – eng.ahmed Aug 31 '13 at 07:45
  • The problem is that you cannot do this operation on main UI thread. You can currently doing it on UI thread. You need to start a new thread and then call the 'HTTP' related methods. So just follow your LogCat. Do the above operation in a new thread. – Shobhit Puri Aug 31 '13 at 07:49
  • sorry but i am not professional .. can you give me link contains a tutorial for that or old question on stack – eng.ahmed Aug 31 '13 at 07:59
  • There are 2 links in question. However find more http://www.techblogistech.com/2011/11/how-to-fix-the-android-networkonmainthreadexception/. ALso there is a poor work around which is not encouraged http://stackoverflow.com/questions/12650921/quick-fix-for-networkonmainthreadexception – Shobhit Puri Aug 31 '13 at 08:05
  • can you see taht please http://stackoverflow.com/questions/18548210/error-in-facebook-graph-org-json-jsonexception-no-value-for-name – eng.ahmed Aug 31 '13 at 12:47
  • i used AsyncTask but it is still not working – eng.ahmed Aug 31 '13 at 12:48
  • @eng.ahmed Read the answer there. You AsyncTask is fine. You are indeed getting a JSON object in return. You can try to print the JSON that you get. That yway you can be sure tat you are getting a JSON in return. – Shobhit Puri Aug 31 '13 at 22:40
  • sorry, but it worked by answer in the other question that you told me to read it – eng.ahmed Sep 02 '13 at 03:22
0

The JSONParser make a HTTP connect in UI thread(The oneClick is invoked in UI thread)and it was fobidden now. So you need move the network codes to other thread.

bixiaopeng
  • 383
  • 2
  • 11
0

In case you have not noticed; StrictMode for network access results in a fatal error as for Android 3.0 (Honeycomb) or later, unless your app is targeting an API version before Honeycomb.

The right way of solving this is to use Android AsyncTask for network access.

The lazy way of handling this is to turn the check of:

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

Bhargav Jhaveri
  • 2,123
  • 1
  • 18
  • 23
0

As others mentioned, you shouldn't be doing networking on UI thread to make your app UI responsive.

Try this

public class JsonParser extends AsyncTask<String, Void, JSONObject> {

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

@Override
protected JSONObject doInBackground(String... params) {

    // Making HTTP request
    try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(params[0]);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    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;
}

@Override
protected void onPostExecute(JSONObject json) {

    try {
            // Storing each json item in variable

            String name = json.getString("name");
            String fid = json.getString("id");
            String picture = json
                    .getJSONObject("picture")
                    .getJSONObject("data")
                    .getString("url");

            db.addPage(name, fid, picture);

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

}

Put the above class in your activity class, then use new JsonParser().execute(url); to fetch data and update the database.

Hari Prasad
  • 603
  • 8
  • 18