如何在android中从数据库显示图像到自定义列表视图?

时间:2015-06-29 09:57:10

标签: java android sqlite

我已将一些Data + Image添加到SQLite数据库,但现在我想将它们显示到自定义列表视图中。就像下面的图像(图像链接)。

Image Link

我无法从数据库中检索图像并将其显示到自定义列表视图中。我已经以BLOB类型将图像存储到数据库。

MainActivity.java

package com.example.crudexamplerepeat;

import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

    Button btn_add_new;
    Button btn_old_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_add_new = (Button) findViewById(R.id.btn_add_new);
        btn_add_new.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(getApplicationContext(),
                        Add_new_activity.class);
                startActivity(i);

            }
        });

        btn_old_data = (Button) findViewById(R.id.btn_old_data);
        btn_old_data.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent i_new = new Intent(getApplicationContext(),
                        Old_data_activity.class);
                startActivity(i_new);
            }
        });

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Old_data_activity.java

package com.example.crudexamplerepeat;

import java.util.ArrayList;
import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Old_data_activity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_old_data_activity);

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

DatabaseHandler.java

package com.example.crudexamplerepeat;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import android.R.array;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DB_VERSION = 4;
    private static final String DB_NAME = "usersInfo";
    private static final String TABLE_NAME = "users";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PASS = "pass";
    private static final String KEY_IMG = "pic";

    public DatabaseHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID
                + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, " + KEY_PASS
                + " TEXT, " + KEY_IMG + " BLOB NOT NULL)";
        db.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public void addNewUser(UserGetSet userGetSet) {
        // TODO Auto-generated method stub
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, userGetSet.getName());
        values.put(KEY_PASS, userGetSet.getPass());
        values.put(KEY_IMG, userGetSet.getImage());

        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public List<UserGetSet> getAllUsers() {
        List<UserGetSet> userList = new ArrayList<UserGetSet>();

        String selectQuery = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) 
        {
            do 
            {
                UserGetSet userGetSetobj = new UserGetSet();
                userGetSetobj.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
                userGetSetobj.setPass(cursor.getString(cursor.getColumnIndex(KEY_PASS)));
                userGetSetobj.setImage(cursor.getBlob(cursor.getColumnIndex(KEY_IMG)));
                userList.add(userGetSetobj);
            } while (cursor.moveToNext());
        }
        return userList;
    }
}

UserListCustomAdapter.java

package com.example.crudexamplerepeat;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class UserListCustomAdapter extends BaseAdapter {
    Context context;

    protected List<UserGetSet> listUsers;
    LayoutInflater inflater;

    public UserListCustomAdapter(Context context, List<UserGetSet> listUsers) {
        // TODO Auto-generated constructor stub

        super();
        this.listUsers = listUsers;
        this.inflater = LayoutInflater.from(context);
        this.context = context;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return listUsers.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return listUsers.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return listUsers.get(position).getUserId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        // TODO Auto-generated method stub
        ViewHolder viewHolder = new ViewHolder();

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.user_list_view, null);

            TextView name = (TextView) v.findViewById(R.id.txt_data_name);
            TextView pass = (TextView) v.findViewById(R.id.txt_data_pass);
            ImageView photo = (ImageView) v.findViewById(R.id.img_photo);

            viewHolder.txt_name = name;
            viewHolder.txt_pass = pass;
            viewHolder.img_pic = photo;

            v.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) v.getTag();
        }

        UserGetSet uGetSet = listUsers.get(position);
        viewHolder.txt_name.setText(uGetSet.getName());
        viewHolder.txt_pass.setText(uGetSet.getPass());
        viewHolder.img_pic.setImageResource(uGetSet.getUserId());

        return convertView;
    }

    private class ViewHolder {
        TextView txt_name;
        TextView txt_pass;
        ImageView img_pic;
    }
}

2 个答案:

答案 0 :(得分:0)

您必须先将博客数据转换为图像视图

byte[] byteArray = DBcursor.getBlob(columnIndex);  

Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);

现在您可以将位图设置为图像视图。

答案 1 :(得分:0)

We don't need to store bytes of image in db, just store Uri of that image into DB and fetch that Uri and set on imageView.

Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
imageView.setImageBitmap(bitmap);

I hope it'll help you