【问题标题】:how to change it to asynctask and make it compatible for above gingerbread? [duplicate]如何将其更改为 asynctask 并使其与上述姜饼兼容? [复制]
【发布时间】:2014-07-18 01:20:02
【问题描述】:

我的应用程序总是在姜饼上面的 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());
        }
    }
}

下面是我的活动类,用于从服务器获取数据然后将其放入列表视图

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

感谢您的帮助

【问题讨论】:

  • 可以添加错误日志吗??
  • 这个错误很可能发生在任何版本的Android上,因为我们不应该在UI线程中执行耗时的过程。在这里查看更多Android Background Processing
  • @André.C.S 是的,在任何版本的 Android 上都应该以不同的方式完成,但我相信,从 api 11 开始,这显然是不可能的。因此,在某些情况下,它适用于旧版本。
  • @codeMagic,谢谢,StrictMode 确实被配置为在 Android 3.0 (Honeycomb) 中出现 NetworkOnMainThreadException 崩溃

标签: android json database android-asynctask


【解决方案1】:

AsyncTask 非常易于使用。你必须弄清楚使用它们的正确方法,并且记住 AsyncTask 必须子类化才能使用。子类将覆盖至少一个方法 doInBackground(Params...),并且大多数情况下会覆盖第二个。您可以右键单击并添加未实现的方法以查看全部。这是docs的 并且不要忘记您必须在 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");
 }
}

【讨论】:

  • 我明白了,谢谢你的帮助^_^
猜你喜欢
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 2010-11-29
  • 2013-09-01
  • 2017-05-05
相关资源
最近更新 更多