如何将其更改为asynctask并使其与上面的姜饼兼容?

时间:2014-07-18 01:20:02

标签: android json database android-asynctask

我的应用程序总是强制关闭android上面的姜饼,大多数答案说我需要将我的代码转换为asynctask。我试过了,但总是失败了。有人可以帮帮我吗?下面是我的JSONParser类

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());
        }
    }
}

以下是我的活动类,用于从服务器获取数据,然后将其放入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);
    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

AsyncTasks非常易于使用。您必须找出使用它们的正确方法,并记住AsyncTask必须使用子类。子类将覆盖至少一个方法doInBackground(Params ...),并且通常会覆盖第二个方法。您可以右键单击并添加未实现方法以查看所有内容。这是docs的 并且不要忘记你必须在asynctask中调用你的web请求。

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");
 }
}