我需要使用RecyclerView创建一个SQLite数据库,我已经尝试过搜索所有样本,但是到目前为止还没有一个能够满足我的需求。因为我无法理解他们的结构,例如他们的文件夹,java classe等等,所以他们中的大多数都无法理解。我一直试图弄清楚自己已经很多天了但是不能理解找到有价值的解决方案我直截了当地说,我需要了解如何将我的sqlite数据库读取到recyclerview,基本上只有字段术语应该出现。目前,数据的插入是硬编码的,因为我想知道我的数据库是否正常工作,但突然之间没有。
这是我的DatabaseHelper.java:
package com.zaid.recyclerviewsqlite.mynote_databases;
import java.util.ArrayList;
import java.util.List;
import com.zaid.recyclerviewsqlite.notes.DataModel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBASE = "my_notes";
public static final String TBLMYNOTES = "tblnotes";
public static final int DBVERSION = 1;
public static final String NOTE_TERM = "note_term";
public static final String NOTE_ID = "note_id";
public static final String NOTE_DEF = "note_def";
public static final String NOTE_SYNTAX = "note_syntax";
public static final String NOTE_CODE = "note_code";
public int currentID;
public DatabaseHelper(Context context) {
super(context, DBASE, null, DBVERSION);
// TODO Auto-generated constructor stub
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+TBLMYNOTES+" ("+ NOTE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NOTE_TERM+" TEXT, "+NOTE_DEF+" TEXT, "+NOTE_SYNTAX+" TEXT, "+NOTE_CODE+" TEXT )");
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+TBLMYNOTES);
onCreate(db);
}
public long InsertNewRecord( String tblname, ArrayList<String> fields, ArrayList<String> values ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues db_values = new ContentValues();
int countArr = values.size();
for( int i = 0; i < countArr; i++ ) {
db_values.put( fields.get(i), values.get(i) );
}
long status = db.insert(TBLMYNOTES, null, db_values);
return status;
}
public Cursor getAllData(String tblname) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM "+tblname, null);
return result;
}
/**
* @return
*/
public List<DataModel> getAllDataModel(){
List<DataModel> dataList = new ArrayList<DataModel>();
String query = "SELECT * FROM" + TBLMYNOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(query, null);
while(c.moveToNext()){
/** DataModel model= new DataModel();
model.setId(Integer.parseInt(c.getString(0)));
model.setTerm(c.getString(1));
model.setDefinition(c.getString(2));
model.setSyntax(c.getString(3));
model.setCode(c.getString(4));
*/
int index0 = c.getColumnIndex(NOTE_ID);
int index1 = c.getColumnIndex(NOTE_TERM);
int index2 = c.getColumnIndex(NOTE_DEF);
int index3 = c.getColumnIndex(NOTE_SYNTAX);
int index4 = c.getColumnIndex(NOTE_CODE);
int id = c.getInt(index0);
String term = c.getString(index1);
String def = c.getString(index2);
String syn = c.getString(index3);
String code = c.getString(index4);
DataModel model = new DataModel(id, term, def, syn, code);
dataList.add(model);
}
return dataList;
}
public int DeleteRecord(String tblname, String strField, String strValue) {
SQLiteDatabase db = this.getWritableDatabase();
int status = db.delete(TBLMYNOTES , " "+strField+" = ? ", new String[] { strValue });
return status;
}
public int UpdateRecord(String tblname, ArrayList<String> Fields, ArrayList<String> Values) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues db_values = new ContentValues();
int countMaxArr = Fields.size();
String strFieldID = Fields.get(0);
String strFieldValue = Values.get(0);
for( int i = 0; i < countMaxArr; i++ ) {
db_values.put(Fields.get(i), Values.get(i));
}
int status = db.update(TBLMYNOTES, db_values, strFieldID+" = ? ", new String[] { strFieldValue });
return status;
}
public void setcurrID(int ID) {
currentID = ID;
}
public int getcurrID() {
return currentID;
}
public Cursor getRecordByID(String tblname, String Fieldname, String Fieldvalue) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM "+TBLMYNOTES+" WHERE "+Fieldname+" = "+Fieldvalue, null);
return result;
}
}
这是My_Notes,显示了recyclerview中的术语列表: 现在我在这里手动编码数据库的插入来测试我的数据库是否正常工作,但无济于事它对我有用。
package com.zaid.recyclerviewsqlite.notes;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import com.zaid.recyclerviewsqlite.R;
import com.zaid.recyclerviewsqlite.addNotes.My_Notes_Add_Main;
import com.zaid.recyclerviewsqlite.mynote_databases.DatabaseHelper;
public class My_Notes extends AppCompatActivity implements View.OnClickListener {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<DataModel> data;
static View.OnClickListener myOnClickListener;
private static ArrayList<Integer> removedItems;
private ImageButton addNote;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_notes);
//database
DatabaseHelper db = new DatabaseHelper(this);
ArrayList<String> ArrValues = new ArrayList<String>() ;
ArrayList<String> FieldsArr = new ArrayList<String>();
ArrValues.add("Hierarchy");
ArrValues.add("Definition Here!");
ArrValues.add("Syntax Here!");
ArrValues.add("Code Here!");
FieldsArr.add( "NOTE_TERM" );
FieldsArr.add( "NOTE_DEF" );
FieldsArr.add( "NOTE_SYNTAX" );
FieldsArr.add( "NOTE_CODE" );
db.InsertNewRecord("TBLMYNOTES", FieldsArr, ArrValues);
// myOnClickListener = new MyOnClickListener(this);
addNote = (ImageButton)findViewById(R.id.addNotes);
recyclerView = (RecyclerView) findViewById(R.id.my_notes_recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(new CustomAdapter(db.getAllDataModel()));
btnAdd();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void btnAdd(){
addNote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),My_Notes_Add_Main.class);
startActivity(i);
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
这是我的DataModel.java
package com.zaid.recyclerviewsqlite.notes;
public class DataModel {
String term_;
String definition_;
int id_;
String syntax_;
String code_;
public DataModel(){
}
public DataModel(int id, String term, String def, String syntax, String code) {
this.term_ = term;
this.id_ = id;
this.definition_=def;
this.syntax_=syntax;
this.code_=code;
}
public String getTerm() {
return term_;
}
public String getDefinition(){
return definition_;
}
public String getSyntax() {
return syntax_;
}
public String getCode() {
return code_;
}
public int getId() {
return id_;
}
public void setTerm(String term){
this.term_= term;
}
public void setId(int id){
this.id_= id;
}
public void setDefinition(String definition){
this.definition_= definition;
}
public void setSyntax(String syntax){
this.syntax_= syntax;
}
public void setCode(String code){
this.code_= code;
}
}
这是我的CustomAdapter.java
package com.zaid.recyclerviewsqlite.notes;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.zaid.recyclerviewsqlite.R;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private ArrayList<DataModel> dataSet;
private List<DataModel> items;
public CustomAdapter(List<DataModel> items){
this.items = items;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewTerm;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewTerm = (TextView) itemView.findViewById(R.id.textViewTerm);
}
}
public CustomAdapter(ArrayList<DataModel> data) {
this.dataSet = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_notes_card_view, parent, false);
//view.setOnClickListener(My_Notes.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
holder.textViewTerm.setText(dataSet.get(listPosition).getTerm());
}
@Override
public int getItemCount() {
return dataSet.size();
}
}
对于我的图书馆,我在这里有: 我使用eclipse所以我不知道它们是什么版本
android-support-v7-appcompat cardview design recyclerview
我的Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zaid.recyclerviewsqlite"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/MyMaterialTheme" >
<activity
android:name="com.zaid.recyclerviewsqlite.index.Index_Activity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.zaid.recyclerviewsqlite.notes.My_Notes"
>
</activity>
<activity
android:name="com.zaid.recyclerviewsqlite.addNotes.My_Notes_Add_Main"
>
</activity>
</application>
</manifest>
在这里编辑:
My_Note_Add_Main.java
package com.zaid.recyclerviewsqlite.addNotes;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.zaid.recyclerviewsqlite.R;
public class My_Notes_Add_Main extends AppCompatActivity implements View.OnClickListener {
private final int numOfPages = 4; //viewpager has 4 pages
private final String[] pageTitle = {"Terms", "Definition", "Syntax", "Code"};
private ImageButton addNew;
private EditText terms, def, syn, code;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_notes_add_main);
addNew = (ImageButton)findViewById(R.id.addNew);
addNewTerms();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
for (int i = 0; i < numOfPages; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new My_Notes_Add_MyPagerAdapter(getSupportFragmentManager(), numOfPages);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
/** @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_notes_add_main_menu, menu);
return true;
} */
public void addNewTerms(){
addNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Add Click", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
My_Notes_Add_MyPagerAdapter.java
package com.zaid.recyclerviewsqlite.addNotes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class My_Notes_Add_MyPagerAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public My_Notes_Add_MyPagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
@Override
public Fragment getItem(int position) {
return My_Notes_Add_TabFragment.getInstance(position);
}
@Override
public int getCount() {
return numOfTabs;
}
}
My_Notes_Add_Tab_Fragment.java
package com.zaid.recyclerviewsqlite.addNotes;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.zaid.recyclerviewsqlite.R;
public class My_Notes_Add_TabFragment extends Fragment {
private int position;
private TextView content;
private ImageView image;
public static Fragment getInstance(int position) {
My_Notes_Add_TabFragment f = new My_Notes_Add_TabFragment();
Bundle args = new Bundle();
args.putInt("position", position);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get data from Argument
position = getArguments().getInt("position");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_notes_add_tab_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
content = (EditText) view.findViewById(R.id.textView);
}
}
添加了Logcat:
03-14 00:33:11.446: E/SQLiteLog(16725): (1) near "FROMtblnotes": syntax error
03-14 00:33:11.446: D/AndroidRuntime(16725): Shutting down VM
03-14 00:33:11.446: W/dalvikvm(16725): threadid=1: thread exiting with uncaught exception (group=0x55d91b20)
03-14 00:33:11.446: D/AndroidRuntime(16725): procName from cmdline: com.zaid.recyclerviewsqlite
03-14 00:33:11.446: E/AndroidRuntime(16725): in writeCrashedAppName, pkgName :com.zaid.recyclerviewsqlite
03-14 00:33:11.446: D/AndroidRuntime(16725): file written successfully with content: com.zaid.recyclerviewsqlite StringBuffer : ;com.zaid.recyclerviewsqlite
03-14 00:33:11.456: I/Process(16725): Sending signal. PID: 16725 SIG: 9
03-14 00:33:11.456: E/AndroidRuntime(16725): FATAL EXCEPTION: main
03-14 00:33:11.456: E/AndroidRuntime(16725): Process: com.zaid.recyclerviewsqlite, PID: 16725
03-14 00:33:11.456: E/AndroidRuntime(16725): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zaid.recyclerviewsqlite/com.zaid.recyclerviewsqlite.notes.My_Notes}: android.database.sqlite.SQLiteException: near "FROMtblnotes": syntax error (code 1): , while compiling: SELECT * FROMtblnotes
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.os.Looper.loop(Looper.java:136)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.ActivityThread.main(ActivityThread.java:5021)
03-14 00:33:11.456: E/AndroidRuntime(16725): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 00:33:11.456: E/AndroidRuntime(16725): at java.lang.reflect.Method.invoke(Method.java:515)
03-14 00:33:11.456: E/AndroidRuntime(16725): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
03-14 00:33:11.456: E/AndroidRuntime(16725): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
03-14 00:33:11.456: E/AndroidRuntime(16725): at dalvik.system.NativeStart.main(Native Method)
03-14 00:33:11.456: E/AndroidRuntime(16725): Caused by: android.database.sqlite.SQLiteException: near "FROMtblnotes": syntax error (code 1): , while compiling: SELECT * FROMtblnotes
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
03-14 00:33:11.456: E/AndroidRuntime(16725): at com.zaid.recyclerviewsqlite.mynote_databases.DatabaseHelper.getAllDataModel(DatabaseHelper.java:84)
03-14 00:33:11.456: E/AndroidRuntime(16725): at com.zaid.recyclerviewsqlite.notes.My_Notes.onCreate(My_Notes.java:64)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.Activity.performCreate(Activity.java:5231)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
03-14 00:33:11.456: E/AndroidRuntime(16725): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-14 00:33:11.456: E/AndroidRuntime(16725): ... 11 more
03-14 00:33:11.606: W/dalvikvm(16740): VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
03-14 00:33:11.606: I/dalvikvm(16740): Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
03-14 00:33:11.606: W/dalvikvm(16740): VFY: unable to resolve interface method 18104: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
03-14 00:33:11.606: D/dalvikvm(16740): VFY: replacing opcode 0x72 at 0x0002
03-14 00:33:11.606: I/dalvikvm(16740): Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
03-14 00:33:11.606: W/dalvikvm(16740): VFY: unable to resolve interface method 18108: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
03-14 00:33:11.606: D/dalvikvm(16740): VFY: replacing opcode 0x72 at 0x0002
03-14 00:33:11.636: I/dalvikvm(16740): Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
03-14 00:33:11.636: W/dalvikvm(16740): VFY: unable to resolve virtual method 424: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
03-14 00:33:11.636: D/dalvikvm(16740): VFY: replacing opcode 0x6e at 0x0002
03-14 00:33:11.636: I/dalvikvm(16740): Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
03-14 00:33:11.636: W/dalvikvm(16740): VFY: unable to resolve virtual method 446: Landroid/content/res/TypedArray;.getType (I)I
03-14 00:33:11.636: D/dalvikvm(16740): VFY: replacing opcode 0x6e at 0x0002