نمایش اطلاعات database بصورت انتخابی در listview
سلام
بنده دیتابیسی دارم که اطلاعات از طریق بخش های مختلف برنامه واردش می شود ، می خواهم اطلاعات وارد شده هر بخش را بطور جداگانه در بخش مربوطه لیست کنم در صورت امکان راهنمایی کنید :
NotesDbAdapter.java
package com.example.notepad;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Simple notes database access helper class. Defines the basic CRUD operations
* for the notepad example, and gives the ability to list all notes as well as
* retrieve or modify a specific note.
*
* This has been improved from the first version of this tutorial through the
* addition of better error handling and also using returning a Cursor instead
* of using a collection of inner classes (which is less scalable and not
* recommended).
*/
/* It is not original code that notepad exercise provided.
*
* I did some edit on this code by adding date parameter on it.
*/
public class NotesDbAdapter {
public static final String KEY_TITLE = "title";
public static final String KEY_DATE = "date";
public static final String KEY_BODY = "body";
public static final String KEY_FAMIL="famil";
public static final String KEY_ROWID = "_id";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null, date text not null);";
private static final String DATABASE_NAME = "data1";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* @param ctx the Context within which to work
*/
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* Open the notes database. If it cannot be opened, try to create a new
* instance of the database. If it cannot be created, throw an exception to
* signal the failure
*
* @return this (self reference, allowing this to be chained in an
* initialization call)
* @throws SQLException if the database could be neither opened or created
*/
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
/**
* Create a new note using the title and body provided. If the note is
* successfully created return the new rowId for that note, otherwise return
* a -1 to indicate failure.
*
* @param title the title of the note
* @param body the body of the note
* @return rowId or -1 if failed
*/
public long createNote(String title, String body, String date,String famil) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_FAMIL, famil);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Delete the note with the given rowId
*
* @param rowId id of note to delete
* @return true if deleted, false otherwise
*/
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
/**
* Return a Cursor over the list of all notes in the database
*
* @return Cursor over all notes
*/
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_BODY,KEY_DATE,KEY_FAMIL}, null, null, null, null, null, null);
}
/**
* Return a Cursor positioned at the note that matches the given rowId
*
* @param rowId id of note to retrieve
* @return Cursor positioned to matching note, if found
* @throws SQLException if note could not be found/retrieved
*/
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY,KEY_DATE,KEY_FAMIL}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Update the note using the details provided. The note to be updated is
* specified using the rowId, and it is altered to use the title and body
* values passed in
*
* @param rowId id of note to update
* @param title value to set note title to
* @param body value to set note body to
* @return true if the note was successfully updated, false otherwise
*/
public boolean updateNote(long rowId, String title,String famil, String body,String date) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
args.put(KEY_FAMIL, famil);
//This lines is added for personal reason
args.put(KEY_DATE, date);
//One more parameter is added for data
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
notelist.java
package com.example.notepad;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class NoteList extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int DELETE_ID = Menu.FIRST;
private int mNoteNumber = 1;
private NotesDbAdapter mDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notelist);
mDbHelper = new NotesDbAdapter (this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
Button addnote = (Button)findViewById(R.id.addnotebutton);
addnote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createNote();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.notelist_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
AlertDialog.Builder dialog = new AlertDialog.Builder(NoteList.this);
dialog.setTitle("About");
dialog.setMessage("Hello! I'm Heng, the creator of this application. This application is created based on learning." +
" Used it on trading or any others activity that is related to business is strictly forbidden."
+"If there is any bug is found please freely e-mail me. "+
"\n\tedisonthk@gmail.com"
);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void createNote() {
Intent i = new Intent(this, NoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE ,NotesDbAdapter.KEY_DATE};
int[] to = new int[] { R.id.text1 ,R.id.date_row};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
setListAdapter(notes);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
}
این سوال را قبلا در سایت stackoverflow مطرح کردم ولی جواب نگرفتم ، ان شاا... اینجا به جواب برسم و جزو اعضای ویژه سایت شوم .
ممنون احسان ، در نوشتن این کوئری که گفتید مشکل دارم فکر می کنم کوئری فعلی این باشد که در سورس بالا (NotesDbAdapter.java) قرار دارد . یک مثال لازم دارم مثلا یک کوئری که فقط ایمیل ها را لیست کند .
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY,KEY_DATE,KEY_FAMIL}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
شاید من متوجه مظورت نشدم و اگه اینطور هست عذر میخوام.
شما اطلاعات رو در جدول های جداگانه ذخیره کنید مثلا
users Table
-----------------
id | name
1 | ALI
2 | Hassan
books Table
----------------
id | book
1 | BookName1
2 | BookName2
حالا اگر قرار هست که هر کتاب فقط به یک کاربر مرتبط باشه کافیه که یک ستون دیگه به نام bookID بسازید و id ای که اون کتاب در جدول book داره رو ذخیره کنید.
اگر هر کتاب میتونه واسه چند کاربر باشه پس باید یک جدول رابط بسازید
id | BookID | UserID
-----------------------
1 | 3 | 2
2 | 2 | 5
برای کوئری گرفتن هم که یه SELECT با یک شرط هست
SELECT * FROM books WHERE ...
سلام ، خیلی ممنون از توضیحات کاملی که دادید . همانطور که در سورس بالا می بینید اطلاعات را در یک جدول ذخیره کردم .
کاربر وقتی وارد نرم افزار می شود مثلا وارد این دو لی اوت می شود و مشخصات را وارد می کند و در دیتابیس ذخیره می شوند
ui کتاب
لیست کتاب خوانده شده
نام نویسنده
شاهنامه فردوسی
+افزودن_______________________{نام کتاب ...... نویسنده .....
**************
ui دوستان:
لیست دوستان
نام صمیمیت
عباس نه زیاد
+افزودن_______________________{نام دوست...... صمیمت.....
مشکل هم در بخش لیست کردن اطلاعات است الان به شکل زیر لیست می شود (لیست دوستان را هم در لیست کتاب ها می آورد)
لیست کتاب خوانده شده
نام نویسنده
شاهنامه فردوسی
عباس نه زیاد
+افزودن_______________________{نام کتاب ...... نویسنده .....
**************
از اینکه وقت گذاشتید و پاسخ دادید ممنونم - +++ رفتم اصولی تر یاد بگیرم ، چند ویدیو اول سایت را دیدم برایم تازگی داشت یک دور این ویدیوها را می بینم بعد ببینم می توانم یا نه.پس دوستان عزیز دیگر نمی خواهم با این سوال دست و پا شکسته وقت شما را بگیرم .
سپاس
پاسخگویی و مشاهده پاسخ های این سوال تنها برای اعضای ویژه سایت امکان پذیر است .
چنانچه تمایل دارید به همه بخش ها دسترسی داشته باشید میتوانید از این بخش لایسنس این آموزش را خریداری نمایید .