1

my app always force close on android above gingerbread, most of the answers said that I need to convert my code to asynctask. I have tried it, but always failed. anyone can help me? below is my JSONParser class

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONListfromURL(String url,List<NameValuePair> params){

        //initialize
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

        //convert response to string
        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();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

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

        return jArray;
    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // 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();

        } 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();
            Log.e("JSON", json);
        } 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;

    }

    public void SendJSONToURL(String url,List<NameValuePair> params){

        //http post
        try{
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(params));
            httpclient.execute(httppost);

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
    }
}

and below is my activity class, for getting data from server then put it to the listview

public class TransaksiList extends Activity {

    EditText filter;
    Button tambah;
    ListView list;
    /** Called when the activity is first created. */
    List<String> items, items2,items3,items4,items5;
    private JSONParser jsonParser;
    String ServerURL = "http://10.0.2.2/fmapp/"; // alamat lokasi file untuk
                                                    // menangkap/mengirim JSON
    String list_tag = "getDataTransaksi",pesan_tag="deleteTransaksi";
    List<String> data=new ArrayList<String>();
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.transaksi_list);
        tambah = (Button) findViewById(R.id.btnTambah);
        filter = (EditText) findViewById(R.id.filter);
        list=(ListView) findViewById(R.id.listTransaksi);
        registerForContextMenu(list);

        tambah.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentTransaksi = new Intent(TransaksiList.this,
                        TransaksiTambah.class);
                startActivity(intentTransaksi);
            }// onClick
        });

        filter.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                TransaksiList.this.adapter.getFilter().filter(s);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    protected void onStart() {
        items = new ArrayList<String>();
        items2 = new ArrayList<String>();
        items3 = new ArrayList<String>();
        items4 = new ArrayList<String>();
        items5 = new ArrayList<String>();
        items.clear();
        items2.clear();
        items3.clear();
        items4.clear();
        items5.clear();
        this.data.clear();
        // Memanggil class JSONParser
        jsonParser = new JSONParser();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", list_tag));
        // Mengirim parameter yang akan di tangkap server
        JSONObject json = jsonParser.getJSONFromUrl(ServerURL, params);
        try {
            JSONArray data = json.getJSONArray("transaksi"); // key ini didapat
                                                                // dari nama
                                                                // array yang
                                                                // kita buat di
                                                                // dalam JSON
            for (int i = 0; i < data.length(); i++) {
                JSONObject e = data.getJSONObject(i);
                items.add(e.getString("id_transaksi"));
                items2.add(e.getString("pancing"));
                items3.add(e.getString("umpan"));
                items4.add(e.getString("bakar"));
                items5.add(e.getString("harga_total"));
                this.data.add("id: "+items.get(i)+" "+"total: "+items5.get(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, this.data);
        list.setAdapter(adapter);
        super.onStart();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {
        case R.id.transaksi_ikan:
            // search action
            Intent intentTransaksi = new Intent(TransaksiList.this,TransaksiIkan.class);
            startActivity(intentTransaksi);
            return true;
        case R.id.ikan:
            // search action
            Intent intentIkan = new Intent(TransaksiList.this,IkanList.class);
            startActivity(intentIkan);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        AdapterContextMenuInfo menuInfo=(AdapterContextMenuInfo) item.getMenuInfo();
        String id=items.get((menuInfo.position));
        switch (item.getItemId()) {
        case R.id.edit:
            Intent intentEdit = new Intent(TransaksiList.this,TransaksiEdit.class);
            intentEdit.putExtra("id", id);
            intentEdit.putExtra("pancing", items2.get((menuInfo.position)));
            intentEdit.putExtra("umpan", items3.get((menuInfo.position)));
            intentEdit.putExtra("bakar", items4.get((menuInfo.position)));
            intentEdit.putExtra("harga", items5.get((menuInfo.position)));
            startActivity(intentEdit);
            return true;
        case R.id.delete:
            jsonParser = new JSONParser();       
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("tag", pesan_tag));
            params.add(new BasicNameValuePair("id", id));
            //Mengirim parameter yang akan di tangkap server
            try{
                jsonParser.SendJSONToURL(ServerURL, params);
                Toast.makeText(getApplicationContext(), "Berhasil menghapus transaksi", Toast.LENGTH_LONG).show();
                onStart();
            }
            catch(Exception e){
                Toast.makeText(getApplicationContext(), "Gagal menghapus transaksi", Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_transaksi, menu);
        return true;
    }
    @Override
    public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_dml, menu);
    }
}

thanks for your help

  • could you add error log?? – Anil Jadhav Jul 18 '14 at 01:40
  • This error will most likely occur on any version of Android, since we should not perform time-consuming processes in the UI thread. see more here [Android Background Processing](http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html) – Anderson K Jul 18 '14 at 01:50
  • @André.C.S yes, it should be done differently on any version of Android but it was made explicitly impossible as of api 11, I believe. So it will work on older versions, in some cases. – codeMagic Jul 18 '14 at 01:54
  • @codeMagic, thanks, really was StrictMode is configured to crash with a NetworkOnMainThreadException from Android 3.0 (Honeycomb) – Anderson K Jul 18 '14 at 02:00

1 Answers1

1

AsyncTasks are so easy to use. You have have to figure out the right way to use them and rememeber AsyncTask must be subclassed to be used. The subclass will override at least one method doInBackground(Params...), and most often will override a second one. You can right click and add unimplement methods to see all. Here are the docs's and dont forget you have to call your web request inside of the asynctask.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}
dsum27
  • 505
  • 3
  • 12