#android #sqlite
Вопрос:
Я хочу прочитать все данные (folder_id =1 в качестве примера) из моей таблицы базы данных.
Примечание:- Folder_id-это столбец, в котором хранится идентификатор папки из таблицы папок в folder.db, которая является другой базой данных folder_id, не генерируется базой данных notes.db
Можно ли это сделать, не слишком сильно меняя код, как я могу этого добиться? Я попытался найти ответ в гугле, но не смог найти ни одного подходящего ответа. вот почему я спрашиваю здесь
вот мой вспомогательный класс базы данных:-
public class MyNotesDatabaseHelper extends SQLiteOpenHelper
{
//create a context object that will help us to point to this MyDatabaseHelper class
private Context context;
//Constants
//database name
private static final String DATABASE_NAME = "Notes_collection.db";
private static final int DATABASE_VERSION = 1;
//table name
public static final String TABLE_NAME = "my_notes";
//creating columns names
private static final String COLUMN_ID = "notes_id";
private static final String COLUMN_FOLDER_ID ="folder_id";
private static final String COLUMN_NOTE_TITLE ="note_title";
private static final String COLUMN_NOTE_CONTENT ="note_content";
public MyNotesDatabaseHelper(@Nullable Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
//query is holding the sql statement needed for the operation
//be sure to add spaces and follow the syntax otherwise it may cause issue
String query = "CREATE TABLE " TABLE_NAME
" (" COLUMN_ID " INTEGER PRIMARY KEY AUTOINCREMENT, "
COLUMN_FOLDER_ID " INTEGER, "
COLUMN_NOTE_TITLE " TEXT, "
COLUMN_NOTE_CONTENT " TEXT " ")" ;
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " TABLE_NAME);
//whenever we upgrade our database we need to call our oncreate method as well
onCreate(db);
}
void addNote(Integer folder_id_String,String Note_name,String Note_content)
{
//create a sql Lite database object
//this will refer to our SQLiteOpenHelper class
//getWritableDatabase() will help us to write to our table
SQLiteDatabase db = this.getWritableDatabase();
//ContentValues cv will store all our data from our application and will pass this to our database table
ContentValues cv = new ContentValues();
//cv.put(key:"column name",value:"Data")
cv.put(COLUMN_FOLDER_ID,folder_id_String);
cv.put(COLUMN_NOTE_TITLE,Note_name);
//the folder detail will contain the notes_id which will come from another database
cv.put(COLUMN_NOTE_CONTENT,Note_content);
//now we will insert the data inside our database using our SQLite object db
long result = db.insert(TABLE_NAME,null,cv);
if(result == -1) //our application failed to insert the data
{
Toast.makeText(context,"Err Bad Protocol A113 0007287197x6211963H!",Toast.LENGTH_SHORT).show();
}
else //our application sucessfully inserted the data from our app to our database
{
Toast.makeText(context,"Added Successfully!",Toast.LENGTH_SHORT).show();
}
}
Cursor ReadAllData()
{
//db.rawQuery("SELECT name,address FROM mytable WHERE name = 'Fred'");
//it will select all the names called Fred
//selecting all the data from our database table
String query = "SELECT * FROM " TABLE_NAME;
//creaing an sql database object and get readable database this time
SQLiteDatabase db = this.getReadableDatabase();
//creating a cursor object
Cursor cursor = null;
if(db!=null)
{
cursor = db.rawQuery(query,null);
}
return cursor;
}}
вот мой пользовательский класс адаптера:-
public class NotesCustomAdapter extends RecyclerView.Adapter<NotesCustomAdapter.MyViewHolder>
{
private Context context;
private ArrayList note_id_CustomAdapter, folder_id_CustomAdapter,
note_title_CustomAdapter,note_content_CustomAdapter;
//item position index in our recylerView
int position;
//create an activity object so that we can refresh our recyclerView in our application
Activity activity;
//custom Adapter constructor should have a context and four different arrayList
//because when we initialize this class inside our main activity
//we want to pass all these array list that we have already created in our MainActivity
NotesCustomAdapter(Activity activity,Context context , ArrayList note_id,ArrayList folder_id, ArrayList note_title,ArrayList note_content)
{
//refreshing our Main activity RecyclerView with new data
this.activity = activity;
//setting up the parameter variable of this constructor to our global variable of this class
//so we can access these objects in our full class
this.context = context;
this.note_id_CustomAdapter = note_id;
this.folder_id_CustomAdapter = folder_id;
this.note_title_CustomAdapter = note_title;
this.note_content_CustomAdapter = note_content;
}
@NonNull
@Override
public NotesCustomAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//we will be infating our row layout for our RecyclerView
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.note_list_card_view,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
this.position = position;
//getting data from arrays and setting the data to our textView that is present in row Layout for our RecylerView
//here we are going to set Text into these textView's
holder.note_id__note_card_view_layout.setText(String.valueOf(note_id_CustomAdapter.get(position)));
holder.folder_id_note_row.setText(String.valueOf(folder_id_CustomAdapter.get(position)));
holder.note_title_note_card_view_layout.setText(String.valueOf(note_title_CustomAdapter.get(position)));
holder.note_content_id_row.setText(String.valueOf(note_content_CustomAdapter.get(position)));
//ad onclick listener on recylerView items
//setting up the onclick Listener for our mainlayout
holder.note_card_view_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,ViewNoteContentActivity.class);
//sending data to View activity via intent
intent.putExtra("note_id",String.valueOf(note_id_CustomAdapter.get(position)));
intent.putExtra("folder_id",String.valueOf(folder_id_CustomAdapter.get(position)));
intent.putExtra("note_title",String.valueOf(note_title_CustomAdapter.get(position)));
intent.putExtra("note_content",String.valueOf(note_content_CustomAdapter.get(position)));
//refreshing our Main activity recylerView with updated data
activity.startActivityForResult(intent,1);
//activity transition animation
activity.overridePendingTransition(R.anim.slide_in_left, R.anim.nothing);
}
});
//add onlong click listener on recyclerview items
//setting up the onclick Listener for our mainlayout
holder.note_card_view_layout.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// go to update Folder name Activity when the item is long pressed in the main activity
Intent intent2 = new Intent(context,NoteUpdateActivity.class);
//sending data to View activity via intent
intent2.putExtra("note_id",String.valueOf(note_id_CustomAdapter.get(position)));
intent2.putExtra("folder_id",String.valueOf(folder_id_CustomAdapter.get(position)));
intent2.putExtra("note_title",String.valueOf(note_title_CustomAdapter.get(position)));
intent2.putExtra("note_content",String.valueOf(note_content_CustomAdapter.get(position)));
//refreshing our Main activity recylerView with updated data
activity.startActivityForResult(intent2,1);
//activity transition animation
activity.overridePendingTransition(R.anim.slide_in_left, R.anim.nothing);
return true;
}
});
}
@Override
public int getItemCount() {
return note_id_CustomAdapter.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView note_title_note_card_view_layout; //holds the title of a note
TextView note_id__note_card_view_layout; //holds the id of the note from note.db
TextView folder_id_note_row; //holds the folder_id
TextView note_content_id_row; //will hold the contents of the note
// calling our mainlayout from our recycler_view_row.xml file
ConstraintLayout note_card_view_layout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
//now getting the id's of those textView's
note_title_note_card_view_layout = itemView.findViewById(R.id.note_title_note_card_view_layout);
note_id__note_card_view_layout = itemView.findViewById(R.id.note_id__note_card_view_layout);
folder_id_note_row = itemView.findViewById(R.id.folder_id_note_row);
note_content_id_row = itemView.findViewById(R.id.note_content_id_row);
// binding our mainlayout from our recycler_view_row.xml file to CustomAdapter class
note_card_view_layout = itemView.findViewById(R.id.note_card_view_layout);
}
}
}
here is my java activity class:-
public class ViewFolderContentsActivity extends AppCompatActivity {
//creating an object of MyDatabaseHelper Class
MyNotesDatabaseHelper notesdb;
//NotesCustomAdapter
NotesCustomAdapter NotesCustomAdapter;
//now create an array list to hold the list of note_id,folder_id,note_title,note_content
ArrayList<String> note_id,folder_id,note_title,note_content;
//related to folder.db
String folder_id_String,folder_name_String,folder_content_String;
FloatingActionButton Add_Button_view_folder_content_activity ;
RecyclerView recylerView_view_folder_content_activity;
ImageView empty_imageView_view_folder_content_activity;
TextView textView_view_folder_content_activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_folder_contents);
Add_Button_view_folder_content_activity = findViewById(R.id.Add_Button_view_folder_content_activity);
recylerView_view_folder_content_activity = findViewById(R.id.recylerView_view_folder_content_activity);
empty_imageView_view_folder_content_activity = findViewById(R.id.empty_imageView_view_folder_content_activity);
textView_view_folder_content_activity = findViewById(R.id.textView_view_folder_content_activity);
//making the textView invisible
textView_view_folder_content_activity.setVisibility(View.INVISIBLE);
//making th imageView invisible
empty_imageView_view_folder_content_activity.setVisibility(View.INVISIBLE);
// calling the action bar
ActionBar actionBar = getSupportActionBar();
// showing the back button in action bar
actionBar.setDisplayHomeAsUpEnabled(true);
//First call this
//this function gets data from the main activity holding the list of folders
getIntentDataFromCustomAdapter();
//setting up the title of the activity
actionBar.setTitle(folder_name_String);
//add an onclick listener on the floating add button
Add_Button_view_folder_content_activity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//open AddNote Activity
Intent intent = new Intent(ViewFolderContentsActivity.this, AddNoteActivity.class);
//send the folder_id_String via intent to Add note activity
intent.putExtra("folder_id",folder_id_String);
startActivity(intent);
//activity transition animation
overridePendingTransition(R.anim.slide_in_left, R.anim.nothing);
}
});
notesdb = new MyNotesDatabaseHelper(ViewFolderContentsActivity.this);
note_id = new ArrayList<>();
folder_id = new ArrayList<>();
note_title = new ArrayList<>();
note_content = new ArrayList<>();
//calling StoreDataInArrays() function
StoreDataInArrays();
//debugging
Log.i("folder_id_array", String.valueOf(folder_id));
//initialize our custom Adapter object
/*
customAdapter = new CustomAdapter(activity: MainActivity.this,context: this,book_id,book_title,book_author,book_page);
the above line will refresh the recylerView in our main Activity by updating the incoming data from CustomAdapter class
*/
NotesCustomAdapter = new NotesCustomAdapter(ViewFolderContentsActivity.this,this,note_id,folder_id,note_title,note_content);
recylerView_view_folder_content_activity.setAdapter(NotesCustomAdapter);
recylerView_view_folder_content_activity.setLayoutManager(new LinearLayoutManager(ViewFolderContentsActivity.this));
}
void StoreDataInArrays()
{
//calling ReadAllData() method or function from MyDatabaseHelper class
Cursor cursor = notesdb.ReadAllData();
if(cursor.getCount() == 0) //that means there is no data
{
empty_imageView_view_folder_content_activity.setVisibility(View.VISIBLE);
textView_view_folder_content_activity.setVisibility(View.VISIBLE);
}
else
{
//move the cursor to the next position in the table
//adding data from our database to our arrays
while(cursor.moveToNext())
{
note_id.add(cursor.getString(0));
folder_id.add(cursor.getString(1));
note_title.add(cursor.getString(2));
note_content.add(cursor.getString(3));
}
}
}// DisplayData function closed
//get data from the CustomAdapter Layout via intent
//this function gets data from the main activity holding the list of folders
void getIntentDataFromCustomAdapter()
{
if(getIntent().hasExtra("id") amp;amp; getIntent().hasExtra("folder_name") amp;amp; getIntent().hasExtra("folder_content"))
{
//get data from CustomAdapter class via Intent
folder_id_String = getIntent().getStringExtra("id");
folder_name_String = getIntent().getStringExtra("folder_name");
folder_content_String = getIntent().getStringExtra("folder_content");
//setting data to the editText
Log.i("folder_id",folder_id_String);
Log.i("folder_name",folder_name_String);
}
else
{
Toast.makeText(this,"No data Err A113 000x2273821",Toast.LENGTH_SHORT).show();
}
}
// this event will enable the back activity action bar back button
// function to the button on press activity action bar back button
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
overridePendingTransition(R.anim.nothing, R.anim.slide_out_right);
return true;
}
return super.onOptionsItemSelected(item);
}
//this method handles back button of android os
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(R.anim.nothing, R.anim.slide_out_right);
}
//refreshing the recylerView in our main activity with new data when mainActivity restarts
@Override
protected void onRestart() {
super.onRestart();
recreate();
}
}