0

I've run a similar code successfully before, but this time it's not working! I really can't understand why.

Any ideas?

public class SingleMenuItemActivity extends Activity {

private static String url = "http://www.tatangalar.com/android/takim_detay.php?takimID=5";

private static final String TAG_MACBILGISI = "son10mac";
private static final String TAG_10 = "10";
private static final String TAG_9 = "9";

JSONArray sonuclar = null;
String filan;

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

    JSONParser jParser = new JSONParser();

    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        sonuclar = json.getJSONArray(TAG_MACBILGISI);

        for(int i = 0; i < sonuclar.length(); i++){

            JSONObject c = sonuclar.getJSONObject(i);

            String s_on = c.getString(TAG_10);
            String s_dokuz = c.getString(TAG_9);

            filan = s_on;

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


    TextView txtsecilen = (TextView) findViewById(R.id.son9); 

    txtsecilen.setText(filan);

}
}
İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
dgkn
  • 1
  • 2

1 Answers1

1

You are receiving a NetworkOnMainThreadException because of this line of code:

jParser.getJSONFromUrl(url);

This used to be a warning, but on newer versions of the Android OS it is not permitted. You must not access the internet from the main UI Thread, such as in your onCreate() method. Send your internet command from a separate runOnUIThread(), Thread/Runnable or AsyncTask and your NetworkOnMainThreadException problem will be solved.

Android disallows this to make sure you don't hang the UI during long tasks by forcing you to do time consuming activity in alternate Threads.

Example:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        ...
        jParser.getJSONFromUrl(url);
        ...
    }
});

You will probably want to display a ProgressDialog and close it when the Thread finishes. An AsyncTask involves a few more steps, but is extremely well suited to this task because it provides hooks for displaying, updating, and dismissing your ProgressDialog.

David Manpearl
  • 12,362
  • 8
  • 55
  • 72
  • Which codes be written in runOnUIThread() my friend? i've tried somethings after your post but i didn't get values again : ( – dgkn Apr 27 '13 at 17:30
  • there is a certain thing which is that android couldn't get values from JSON. i don't know why.. – dgkn Apr 27 '13 at 18:00
  • I got the solution; I've just changed getString to optString and it worked! thanks :) – dgkn Apr 27 '13 at 19:21