2

I am a new in android and I am trying to display data that I am getting from server through json.I use lazylist with JSONparser.my app its work on android 2.3 but on 4.0 ..so i trying to add AsyncTask in my code. And my code is:

package dlmbg.pckg.tampil.gambar;

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 AmbilJson(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;

    }
}

when i run in 4.0,its error

11-01 12:16:19.063: E/AndroidRuntime(623): FATAL EXCEPTION: main
11-01 12:16:19.063: E/AndroidRuntime(623): java.lang.RuntimeException: Unable to start activity ComponentInfo{dlmbg.pckg.tampil.gambar/dlmbg.pckg.tampil.gambar.TampilkanGambarActivity}: android.os.NetworkOnMainThreadException
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.os.Looper.loop(Looper.java:137)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.main(ActivityThread.java:4424)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.lang.reflect.Method.invokeNative(Native Method)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.lang.reflect.Method.invoke(Method.java:511)
11-01 12:16:19.063: E/AndroidRuntime(623):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-01 12:16:19.063: E/AndroidRuntime(623):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-01 12:16:19.063: E/AndroidRuntime(623):  at dalvik.system.NativeStart.main(Native Method)
11-01 12:16:19.063: E/AndroidRuntime(623): Caused by: android.os.NetworkOnMainThreadException
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
11-01 12:16:19.063: E/AndroidRuntime(623):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-01 12:16:19.063: E/AndroidRuntime(623):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-01 12:16:19.063: E/AndroidRuntime(623):  at dlmbg.pckg.tampil.gambar.JSONParser.AmbilJson(JSONParser.java:38)
11-01 12:16:19.063: E/AndroidRuntime(623):  at dlmbg.pckg.tampil.gambar.TampilkanGambarActivity.onCreate(TampilkanGambarActivity.java:38)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.Activity.performCreate(Activity.java:4465)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-01 12:16:19.063: E/AndroidRuntime(623):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-01 12:16:19.063: E/AndroidRuntime(623):  ... 11 more

I dont know where i must put AsyncTask Can anyone helps me?

febriyanmf
  • 23
  • 1
  • 6

3 Answers3

0

1.First you define class and create object of class

 MyFirstMethod myfirst;
  1. Now you execute this class adding

myfirst=new MyFirstMethod();

myfirst.execute(your url);

public class MyFirstMethod extends AsyncTask<String, Void, String> {
            ProgressDialog dialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = new ProgressDialog(context);
                dialog.setMessage("Loading....");
                dialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                String url = params[0];
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    ResponseHandler<String> resHandler = new  BasicResponseHandler();
                    String page = httpClient.execute(httpGet, resHandler);
                    Log.d("result", page);

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

                return null;
            }

            @Override
            protected void onPostExecute(String result) {

                super.onPostExecute(result);
                dialog.dismiss();
                dialog.cancel();


            }

        }
QuokMoon
  • 4,387
  • 4
  • 26
  • 50
  • where i must execute the new class?? in jsonparse?? im sory im newbie – febriyanmf Nov 01 '12 at 07:07
  • @user1790440 you are use myfirst=new MyFirstMethod(); myfirst.execute(your url); k..in ocreate or any event where you want just pass the url into "your url" field. – QuokMoon Nov 01 '12 at 07:10
0

Read these tutorials for asynkTask:-

these linkl! &this is a stackoverflowlink Try these tutorials for asynktask

Community
  • 1
  • 1
Deepanker Chaudhary
  • 1,694
  • 3
  • 15
  • 35
0

You should try AsyncTask something like below in your code...

private class BackgroundTask extends AsyncTask<String, Void, String> {
@Override
  protected String doInBackground(String... urls) {
    // 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();
        String result = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

   return result;
 }

 @Override
 protected void onPostExecute(String result) {
  // try parse the string to a JSON object
    try {
        jObj = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

}

and call it by below line where you need...

 new BackgroundTask().execute(url);
Priyank Patel
  • 12,244
  • 8
  • 65
  • 85
  • i replace AmbilJson(link_url) to new BackgroundTask().execute(url) but its error: my original: JSONParser jParser = new JSONParser(); JSONObject json = jParser.AmbilJson(link_url); – febriyanmf Nov 01 '12 at 07:20
  • you should call `new BackgroundTask().execute(url);` from your `AmbilJson(link_url)` function...no need to replace it with AsyncTaxk... – Priyank Patel Nov 01 '12 at 07:26
  • its error nullpointerException...in my mainActivity JSONParser jParser = new JSONParser(); JSONObject json = jParser.AmbilJson(link_url); – febriyanmf Nov 01 '12 at 07:45
  • try `Thread.sleep(2000);` after calling `new BackgroundTask().execute(url);` and then return json object `return jObj;`...because your jObj is null until AsyncTask will not finish in background.... – Priyank Patel Nov 01 '12 at 08:02
  • i created String result = null; for return result; (because if i didnt created local variabel is error) is affect? – febriyanmf Nov 01 '12 at 09:26
  • i put new BackgroundTask().execute(url); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jObj; but its still "nullPointerException" – febriyanmf Nov 02 '12 at 04:09