用于加载图像的AsyncTask无法正常工作

时间:2015-12-27 07:54:14

标签: android sqlite android-asynctask

我有一个简单的Asynctask代码,它是从数据库加载后设置和映像到imageview的。我在我片段的onCreateView中调用此类,但图像不在imageview中。 注意 - 该表只有一行,所以我认为查询没有错误。

         protected class setpro extends AsyncTask<String, String, Bitmap> {


    @Override
    protected Bitmap doInBackground(String... params) {
        //Set profile
        DataBaseOperations hell = new DataBaseOperations(getActivity());
        SQLiteDatabase db = hell.getReadableDatabase();
        String[] columns = {mDatabase.Tableinfo.Pic};
        Cursor cur = db.query(mDatabase.Tableinfo.Table_Name, columns, null, null, null, null, null);
        byte[] b = null;
        Bitmap bp = null;
        while (cur.moveToNext()) {
            b = cur.getBlob(cur.getColumnIndex(mDatabase.Tableinfo.Pic));
        }
        if (b.length > 0) {
            bp = BitmapFactory.decodeByteArray(b, 0, b.length);
            cur.close();
            db.close();
            hell.close();
        }
            return bp;
    }
     @Override
protected void onPostExecute(Bitmap result) {
    if(result != null){
        ImageView iv = (ImageView) mview.findViewById(R.id.pro);
        iv.setImageBitmap(result);
}
}

这是我的主叫代码。

      @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mview = inflater.inflate(R.layout.fragment_profile, container, false);
    Button Setprofile = (Button) mview.findViewById(R.id.setprofile);
    // set profile pic
    new setpro().execute("whatever");
  }

2 个答案:

答案 0 :(得分:1)

爵士 你从表中获取位图但没有将其绑定到图像视图中,所以请将此代码添加到Asynctask

protected void onPostExecute(Bitmap bm) {

iv.setImageBitmap(bm);
}

答案 1 :(得分:0)

onPostExecute(Bitmap b){ }的{​​{1}}方法在哪里?

AsyncTask利用它来返回结果/与UI线程交互。 https://developer.android.com/reference/android/os/AsyncTask.html