如何在android中加载数据时避免黑屏

时间:2014-04-22 05:09:59

标签: android android-asynctask

我从android中的远程服务器获取数据。数据加载时显示黑屏,持续7-8秒。这有时会导致android显示ANR对话框。我使用asynctask进行数据的后台加载,但黑屏仍然存在。此外,我无法在活动栏中看到不确定的进展。我究竟做错了什么?我正在粘贴下面的代码 -

public class ItemActivity extends Activity {

    private String str = null;
    private ListView listview;
    private LazyItemLoadAdapter adapter;
    private Item[] item_data = null;

    private Item[] filteredItems = null;

    private int id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_item);

        ActionBarUtils.setActionBar(this);

        id = getIntent().getExtras().getInt("id");

        listview = (ListView) findViewById(R.id.listViewAllItems);

        AsyncData data=new AsyncData();
        data.execute(String.valueOf(id), "http://kurdshopping.net/apj/adlist.php");
        try {
            item_data=data.get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (item_data == null || item_data.length == 0) {
            listview.setVisibility(View.GONE);
            return;
        }
        adapter = new LazyItemLoadAdapter(this, R.layout.listview_item_row, item_data);

        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                int itemid = item_data[position].id;
                Toast.makeText(ItemActivity.this, String.valueOf(itemid),
                        Toast.LENGTH_SHORT).show();
                if (id == 96) {
                    Intent carIntent = new Intent(ItemActivity.this,
                            CarActivity.class);
                    carIntent.putExtra("id", itemid);
                    startActivity(carIntent);
                } else {
                    Intent adIntent = new Intent(ItemActivity.this,
                            AdActivity.class);
                    adIntent.putExtra("id", itemid);
                    startActivity(adIntent);
                }
            }
        });

    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (item_data == null || item_data.length == 0) {
            menu.getItem(0).setEnabled(false);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.item, menu);
        return true;
    }


    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_search:
            Intent optionsIntent = new Intent(ItemActivity.this,
                    OptionsActivity.class);
            optionsIntent.putExtra("id", id);
            startActivityForResult(optionsIntent, 1);
            break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    private class AsyncData extends AsyncTask<String, Void, Item[]>{

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected Item[] doInBackground(String... arg0) {
            Item[] item_data=null;
            try {
                ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters
                        .add(new BasicNameValuePair("id", arg0[0]));
                str = CustomHttpClient.executeHttpPost(
                        arg0[1], postParameters);
                JSONArray array = new JSONArray(str);
                item_data = new Item[array.length()];

                for (int i = 0; i < item_data.length; i++) {
                    JSONObject jdata = array.getJSONObject(i);
                    String path = "http://kurdshopping.net/thumbs/"
                            + jdata.getString("name");
                    int itemid = jdata.getInt("id");
                    item_data[i] = new Item();
                    item_data[i].id = itemid;
                    item_data[i].imageUrl = path;
                    item_data[i].city = jdata.getString("city_name");
                    item_data[i].make = jdata.getString("cc_name");
                    item_data[i].model = jdata.getString("cm_name");
                    item_data[i].price = jdata.getString("price");
                    item_data[i].text = jdata.getString("title") + "\nPrice: "
                            + jdata.getString("price");
                    Log.i("break", "break");
                }
            } catch (NotFoundException n) {
                Log.e("ItemActivity", n.getMessage());
            } catch (JSONException j) {
                Log.e("ItemActivity", j.getMessage());
            } catch (Exception e) {
                Log.e("ItemActivity", e.getMessage());
            }
            return item_data;
        }

        @Override
        protected void onPostExecute(Item[] result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            setProgressBarIndeterminateVisibility(false);
        }

    }
}

感谢任何帮助。提前谢谢。

3 个答案:

答案 0 :(得分:3)

data.get()调用完全阻止UI线程,直到AsyncTask完成其处理。

您应该将这两个语句移到onPostExecute()的末尾:

   adapter = new LazyItemLoadAdapter(this, R.layout.listview_item_row, item_data);

   listview.setAdapter(adapter);

你必须摆脱data.get()电话周围的整个try / catch块。

最后,作为进一步的改进,您应该考虑是否应该将这两行移动到onResume(),以便每次重新显示活动时刷新数据:

    AsyncData data=new AsyncData();
    data.execute(String.valueOf(id), "http://kurdshopping.net/apj/adlist.php");

答案 1 :(得分:1)

试试这个编辑过的代码。我加了// @ Hashir -start&amp; // @ Hashir - 结束我的纠正。

public class ItemActivity extends Activity {

private String str = null;
private ListView listview;
private LazyItemLoadAdapter adapter;
//@Hashir - start
//    private Item[] item_data = null;
private Item[] item_data = new Item[0];
//@Hashir - end

private Item[] filteredItems = null;

private int id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_item);

    ActionBarUtils.setActionBar(this);

    id = getIntent().getExtras().getInt("id");

    listview = (ListView) findViewById(R.id.listViewAllItems);

    AsyncData data=new AsyncData();
    data.execute(String.valueOf(id), "http://kurdshopping.net/apj/adlist.php");
  //@Hashir - start
    /*try {
        item_data=data.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (item_data == null || item_data.length == 0) {
        listview.setVisibility(View.GONE);
        return;
    }*/
  //@Hashir - end
    adapter = new LazyItemLoadAdapter(this, R.layout.listview_item_row, item_data);

    listview.setAdapter(adapter);
    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            int itemid = item_data[position].id;
            Toast.makeText(ItemActivity.this, String.valueOf(itemid),
                    Toast.LENGTH_SHORT).show();
            if (id == 96) {
                Intent carIntent = new Intent(ItemActivity.this,
                        CarActivity.class);
                carIntent.putExtra("id", itemid);
                startActivity(carIntent);
            } else {
                Intent adIntent = new Intent(ItemActivity.this,
                        AdActivity.class);
                adIntent.putExtra("id", itemid);
                startActivity(adIntent);
            }
        }
    });

}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if (item_data == null || item_data.length == 0) {
        menu.getItem(0).setEnabled(false);
    }
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.item, menu);
    return true;
}


@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_search:
        Intent optionsIntent = new Intent(ItemActivity.this,
                OptionsActivity.class);
        optionsIntent.putExtra("id", id);
        startActivityForResult(optionsIntent, 1);
        break;
    }
    return super.onMenuItemSelected(featureId, item);
}

private class AsyncData extends AsyncTask<String, Void, Item[]>{

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        setProgressBarIndeterminateVisibility(true);
    }

    @Override
    protected Item[] doInBackground(String... arg0) {
        Item[] item_data=null;
        try {
            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters
                    .add(new BasicNameValuePair("id", arg0[0]));
            str = CustomHttpClient.executeHttpPost(
                    arg0[1], postParameters);
            JSONArray array = new JSONArray(str);
            item_data = new Item[array.length()];

            for (int i = 0; i < item_data.length; i++) {
                JSONObject jdata = array.getJSONObject(i);
                String path = "http://kurdshopping.net/thumbs/"
                        + jdata.getString("name");
                int itemid = jdata.getInt("id");
                item_data[i] = new Item();
                item_data[i].id = itemid;
                item_data[i].imageUrl = path;
                item_data[i].city = jdata.getString("city_name");
                item_data[i].make = jdata.getString("cc_name");
                item_data[i].model = jdata.getString("cm_name");
                item_data[i].price = jdata.getString("price");
                item_data[i].text = jdata.getString("title") + "\nPrice: "
                        + jdata.getString("price");
                Log.i("break", "break");
            }
        } catch (NotFoundException n) {
            Log.e("ItemActivity", n.getMessage());
        } catch (JSONException j) {
            Log.e("ItemActivity", j.getMessage());
        } catch (Exception e) {
            Log.e("ItemActivity", e.getMessage());
        }
        return item_data;
    }

    @Override
    protected void onPostExecute(Item[] result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //@Hashir - start
        item_data = result;
        adapter.notifyDataSetChanged();
        listview.invalidate();
        //@Hashir - end
        setProgressBarIndeterminateVisibility(false);
    }

}
}

答案 2 :(得分:0)