如何从sqlite数据库附加RecyclerView适配器

时间:2017-03-25 03:01:38

标签: java android android-studio android-recyclerview android-cursoradapter

我试图找到一个如何用sqlite制作recycleview的教程,但我对他的步骤了解不多。有谁可以帮我解决以下问题。创建sqlite的数据适配器recycleview。

RecyclerViewHolder.java

package com.my.app;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class RecyclerViewHolder extends RecyclerView.ViewHolder {
    TextView tv1;
    ImageView imageView;

    public RecyclerViewHolder(View itemView) {
        super(itemView);
        tv1 =(TextView)itemView.findViewById(R.id.data_kategori);
        imageView=(ImageView)itemView.findViewById(R.id.list_kategori);
    }
}

RecycleAdapter.java

package com.my.app;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;


public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.myViewHolder> {
    public ArrayList<String> myValues;


    public RecycleAdapter (ArrayList<String> myValues){
        this.myValues = myValues;
    }

    @Override
    public RecycleAdapter.myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View listitem =LayoutInflater.from(parent.getContext()).inflate(R.layout.list_kategori, parent, false);
        return new myViewHolder(listitem);
    }

    @Override
    public void onBindViewHolder(RecycleAdapter.myViewHolder holder, int position) {
        holder.data_nm.setText(myValues.get(position));
    }

    @Override
    public int getItemCount() {
        return myValues.size();
    }

    public  static class  myViewHolder extends RecyclerView.ViewHolder {
        private TextView data_nm;
        public myViewHolder (View itemView) {
            super(itemView);
            data_nm =(TextView)itemView.findViewById(R.id.data_kategori);
        }
    }
}

DbHelper.java

package com.my.app;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {

        // Database Information
        static final String DB_NAME = "SavePassword";

        // database version
        static final int DB_VERSION = 1;

        // Table Name
        public static final String kategori_tb = "tb_kategori";

        // Table columns
        public static final String kategori_id = "_id";
        public static final String kategori_nm = "nm";

        // Creating table query
        private static final String data_kategori = "create table " + kategori_tb + "(" + kategori_id
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + kategori_nm + " TEXT NOT NULL);";

        public DbHelper(Context context) {
                super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
                db.execSQL(data_kategori);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("DROP TABLE IF EXISTS " + data_kategori);
                onCreate(db);
        }

}


**DbManager.java**

    package com.my.app;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;

    public class DbManager {

        private DbHelper dbHelper;

        private Context context;

        private SQLiteDatabase database;

        public DbManager(Context c) {
            context = c;
        }

        public DbManager open() throws SQLException {
            dbHelper = new DbHelper(context);
            database = dbHelper.getWritableDatabase();
            return this;
        }

        public void close() {
            dbHelper.close();
        }

        public Cursor fetch_data() {
            String[] columns = new String[] { DbHelper.kategori_id, DbHelper.kategori_nm };
            Cursor cursor = database.query(DbHelper.kategori_tb, columns, null, null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
            }
            return cursor;
        }

        public void insert_data(String nm_kategori) {
            ContentValues value = new ContentValues();
            value.put(DbHelper.kategori_nm, nm_kategori);
            database.insert(DbHelper.kategori_tb, null, value);
        }
    }

MainActivity.java

package com.savepassword.app;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

import static com.savepassword.app.R.id.nama_kategori;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
    RecyclerView recyclerView;

    private DbManager dbManager;
    private Button crk;
    private Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ArrayList<String> myValues = new ArrayList<>();

        //adapter = new SimpleCursorAdapter(this, R.layout.view_akun, cursor, from, to, 0);

        myValues.add("kitkat");
        myValues.add("lolipop");
        myValues.add("nougat");

        RecycleAdapter adapter = new RecycleAdapter(myValues);
        RecyclerView myView = (RecyclerView)findViewById(R.id.rc_kategori);
        myView.setHasFixedSize(true);
        myView.setAdapter(adapter);
        myView.setLayoutManager(new GridLayoutManager(this, 2));
        myView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
        myView.setItemAnimator(new DefaultItemAnimator());

    }

}    

3 个答案:

答案 0 :(得分:1)

你几乎已经完成了它,在主要活动中只是从数据库中获取数据并将其存储在内部列表中。您已经创建了适配器,只需将该数组列表与您的RecyclerView绑定,它就可以正常工作。

E.g。

ArrayList<String> myDataList = fetchDataFromDB() // will return Data from DB
RecycleAdapter adapter = new RecycleAdapter(myDataList);

答案 1 :(得分:1)

CursorAdapter或[{1}}直接使用Cursor没有可用的内容。

相反,您可以使用Recyclerview.Adapter<>从sqlite获取数据,将数据填充到Cursor并将其传递给ArrayList

以下是使用Loaders

的另一种方法

答案 2 :(得分:0)

首先,您需要使用ArrayList

填充数据库

更改此

的insert_data(String nm_kategori)
public void insert_data(ArrayList<String> kategoriArray) {
    ContentValues value = new ContentValues();

    for(String nm_kategori : kategoriArray){
    value.put(DbHelper.kategori_nm, nm_kategori);
    database.insert(DbHelper.kategori_tb, null, value);

    }
}

填充ArrayList myValues后,在MainActivity上执行此操作。

DbManager dbManager = new DbManager(this);// this for activity and getActivity()
dbManager.open();
dbManager.insert_data(myValues)
dbManager.close();

并且最后填充您的回收者视图执行此操作。

dbManager.open();
ArrayList<String> populateRecycler= fetchDataFromDB() // will return Data from DB
dbManager.close();
RecycleAdapter adapter = new RecycleAdapter(populateRecycler);//and then populate your recycler adapter