我想制作一个recyclerview,以将数据显示到SQLITE数据库中的新活动中

时间:2019-07-04 22:07:11

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

我正在做一个项目,我有一个带id,标题,内容的sqlite数据库 我想制作一个recyclerview并从数据库中获取标题,并将其设置为每个位置的recyclerview项,当用户单击某个项目时,他们将能够从数据库中读取内容。希望我的问题清楚!谢谢。

这是我的DatabaseHelper类

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DBNAME = "alQais.db";

private Context context;
private SQLiteDatabase sqLiteDatabase;

public DatabaseHelper(Context mContext){
    super(mContext, DBNAME, null, 1);
    this.context = mContext;
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void openDatabase(){
    String dbPath = context.getDatabasePath(DBNAME).getPath();
    if(sqLiteDatabase != null && sqLiteDatabase.isOpen()){
        return;
    }
    sqLiteDatabase = SQLiteDatabase.openDatabase(dbPath, null,SQLiteDatabase.OPEN_READWRITE);
}

public void closeDatabase(){
    if(sqLiteDatabase != null){
        sqLiteDatabase.close();
    }
}

public ArrayList getAllTitles(){
    ArrayList arrayList = new ArrayList();
    openDatabase();
    Cursor cursor = sqLiteDatabase.rawQuery("select * from muallaqat", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()){
        arrayList.add(cursor.getString(cursor.getColumnIndex("title")));
        cursor.moveToNext();
    }
    cursor.close();
    closeDatabase();
    return arrayList;
}

public String getMuallaqa(String title){
    String muallaqat;
    openDatabase();
    Cursor cursor = sqLiteDatabase.rawQuery("select * from muallaqat where title like '" + title + "'", null);
    cursor.moveToFirst();
    muallaqat = cursor.getString(cursor.getColumnIndex("muallaqa"));
    cursor.close();
    closeDatabase();
    return muallaqat;
}}

MainActivity.java

public class MainActivity extends AppCompatActivity {

DatabaseHelper db = new DatabaseHelper(this);
ListView listView;
TextView textView;

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

    getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

    listView = findViewById(R.id.listView);

    File database = getBaseContext().getDatabasePath(db.DBNAME);
    if(false == database.exists()){
        db.getReadableDatabase();
        if(copyDatabase(this)){
            Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    ArrayList lstTitles = db.getAllTitles();
    ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.item_layout, lstTitles);


    listView.setAdapter(arrayAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String title = String.valueOf(parent.getItemAtPosition(position));
            Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            intent.putExtra("title", title);
            startActivity(intent);
        }
    });

}

private boolean copyDatabase(Context mContext){
    try{
        InputStream inputStream = mContext.getAssets().open(db.DBNAME);
        String outFileName = db.DBLOCATION + db.DBNAME;
        OutputStream outputStream = new FileOutputStream(outFileName);
        byte[] buff = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(buff)) > 0){
            outputStream.write(buff, 0, length);
        }
        outputStream.flush();
        outputStream.close();
        return true;
    }catch (Exception e){
        return false;
    }
}}

这是显示来自sqlite的内容的活动

Main2Activity.java

public class Main2Activity extends AppCompatActivity {

DatabaseHelper db = new DatabaseHelper(this);

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

    Typeface face = Typeface.createFromAsset(getAssets(), "font/Amiri-Regular.ttf");

    getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

    final TextView muallaqa = findViewById(R.id.muallaqa);

    muallaqa.setMovementMethod(new ScrollingMovementMethod());
    muallaqa.setTypeface(face);

    Intent intent = getIntent();
    String title = intent.getStringExtra("title");
    String fullMuallaqa = db.getMuallaqa(title);
    muallaqa.setText(fullMuallaqa);
    this.setTitle(title);
}}

3 个答案:

答案 0 :(得分:1)

  

作为参考,请遵循步骤

1)创建ID,标题,内容的setter和getter方法 例如

public class settter 
 {

int id;
String name;
String content;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
   }
 }

2)在xml mainactivity中添加recyclerview

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
     />

3)在MainActivity中,删除所有与listview相关的代码,并添加下面给出的代码

 RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view2);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //make array list object with setter class
        ArrayList<setter> name =db.getAllTitles();

       //new adapter(ArrayList<setter>, context) ,so initiate adapter
        recyclerView.setAdapter(new adapter(name,getApplicationContext()));

        //draw line 
        recyclerView.addItemDecoration(new 
     DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));

4)创建一个布局文件,其中包含您的数据并在recyclerview中进行充气

名称:recycler_content_holder.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="vertical">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/recycler_content_holder"
    >
    <TextView
        android:layout_width="50dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:id="@+id/tv_id"/>
    <TextView
        android:layout_width="100dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:id="@+id/tv_title"
        android:gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:gravity="center|right"
        android:id="@+id/tv_content"/>
</LinearLayout>

5)创建适配器类

public class adapter extends RecyclerView.Adapter<adapter.AdapterViewHolder>
{

ArrayList<settter> data;
Context context;
public adapter(ArrayList<settter> data,Context context)
{
    this.data=data;
    this.context=context;
}

@NonNull
@Override
public AdapterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
    LayoutInflater layoutInflater=LayoutInflater.from(viewGroup.getContext());
    View view=layoutInflater.inflate(R.recycler_content_holder,viewGroup,false);
    return new ProgramingViewHolder(view);


}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i)
{

    viewHolder.id.setText(""+data.get(i).getId());
    viewHolder.title.setText(data.get(i).getTitle());
    viewHolder.content.setText(data.get(i).getContent());

    viewHolder.linearLayout.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            String title = String.valueOf(data.get(i).getTitle());
            Intent intent = new Intent(context, Main2Activity.class);
            intent.putExtra("title", title);
            startActivity(intent);

        }
    });



}

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

//class programingViewHolder
public class AdapterViewHolder extends RecyclerView.ViewHolder
{
    TextView id,title,content;
    LinearLayout linearLayout;

    public AdapterViewHolder(@NonNull View itemView) {
        super(itemView);
        id=(TextView)itemView.findViewById(R.id.tv_id);
        title=(TextView)itemView.findViewById(R.id.tv_mtrNo);
        content=(TextView)itemView.findViewById(R.id.tv_nm);
        linearLayout=(LinearLayout)itemView.findViewById(R.id.recycler_content_holder);

    }


  }
 }

6)DatabaseHelper中的更改方法

public ArrayList<setter> getAllTitles(){
    ArrayList<setter> arrayList = new ArrayList();
    openDatabase();
    setter set=new setter();
    Cursor cursor = sqLiteDatabase.rawQuery("select * from muallaqat", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()){
        set.setTitle(cursor.getString(cursor.getColumnIndex("title")));
        //add object to arralist
        arrayList.add(set);
        cursor.moveToNext();
    }
    cursor.close();
    closeDatabase();
    return arrayList;
}

只需复制,粘贴和理解,希望对您有所帮助。

答案 1 :(得分:0)

如果我理解正确,那么您想对SQLite数据库中的数据使用recyclerview吗?并且您想在单击某个项目并用该项目中的数据填充它时打开一个新活动?查看这篇文章

Implementation of RecyclerView with Cursor Adapter

答案 2 :(得分:0)

只做一件事 从数据库中获取ID和标题,并在recyclerview中显示标题。并且当onItemClick在recyclerview上时,将垂直位置的ID传递到下一个活动。

然后在下一个活动中获取从上一个活动传递的ID。

然后从具有ID的数据中获取数据。您将获得所有数据。

并显示获取的数据以进行活动。