Dumping android SQLite text content into textView - java

I built an app that so far manages to ADD text to a database (cannot verify yet but I killed the FC). However, when I try to read from the database it FCs because I'm unsure of how to use the Cursor object. I read the documentation and it confuses me more. I have a database with table "records" and a single column "texts". While my project manages to input text into the database (via an EditText), I'm trying unsuccessfully to return all the database entries from this "texts" column into a textView.
DB Helper inner-class:
private class dbHelper extends SQLiteOpenHelper {
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
System.out.println("create statement"+SQL_CREATE_ENTRIES);
try
{
db.execSQL(SQL_CREATE_ENTRIES);
}catch(SQLiteException sql)
{
sql.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS records");
onCreate(db);
}
public void addRecord(String t) {
ContentValues values = new ContentValues(1);
values.put(RECORDS_COLUMN_TEXTS,t);
getWritableDatabase().insert(TABLE_NAME, RECORDS_COLUMN_TEXTS, values);
}
public Cursor getRecords() {
return getWritableDatabase().rawQuery("select * from " + TABLE_NAME, null);
}
}
Within main class:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "CSCI598";
private static final String TABLE_NAME = "records";
public static final String RECORDS_COLUMN_TEXTS = "texts";
private dbHelper openHelper;
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
public void onClick(View v) {
TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);
openHelper = new dbHelper(this);
switch(v.getId()) {
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
cursor.moveToFirst();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString());
break;
case R.id.append1:
String txt=et.getText().toString();
openHelper.addRecord(txt);
break;
}
logcat: http://pastebin.com/mqUn6g7P
As you can see, I'm probably trying something very stupid with the action for clicking the fetch button, ie. "openHelper.getRecords().toString()" attempting to convert all that Cursor returns to string. How can I go about this alternately in the simplest fashion?

Ok First you have get the strings from the Cursor by doing this
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
Then you can set it to the textView
tv.setText(sb.toString);
This should work actually
.Replace this part of your code
case R.id.fetch1:
tv.setText(openHelper.getRecords().toString());
break;
With this
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString);
break;
Also remove autoincrement for Text when you create the table
Replace this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
With this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT" + ")";
Also Add table name in the constructor instead of database name. Change this:
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
To this:
public dbHelper(Context context) {
super(context, TABLE_NAME, null, DATABASE_VERSION);
}

Related

How to search value in Sqlite database?

I'm developing an app which is used for contacts and for this i used sqlite database to store name and number so i want to filter name and number for searching for which
i tried that query but
it's not working for me
any solution for problem i used like and "=" both?
public boolean onQueryTextChange(String newText) {
try {
final String temp = newText.toLowerCase();
final ArrayList<Map> map1 = new ArrayList();
try {
dbhelper =new FeedReaderDbHelper(getActivity());
SQLiteDatabase db=dbhelper.getReadableDatabase();
String projection[]={FeedReaderContract.FeedEntry.COLUMNS_TITLE,FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE};
Cursor cursor =db.query(FeedReaderContract.FeedEntry.TABLE_NAME,projection ,FeedReaderContract.FeedEntry.COLUMNS_TITLE+"= ?",new String[]{newText},null,null,null);
while(cursor.moveToFirst()){
String name = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMNS_TITLE));
String number = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE));
Map<String, Object> map = new HashMap();
map.put(name, number);
if (name.toLowerCase().contains(temp)) {
map1.add(map);
Phone.this.adapter.Filter(map1);
}
} }
catch(Exception e){
System.out.print(Retriving_list);
}
}catch(Exception e){
Toast.makeText(getActivity(), First_Retrive_Data, Toast.LENGTH_SHORT).show();
}
//DbHelperClass
public class FeedReaderDbHelper extends SQLiteOpenHelper{
public static final int DB_VERSION =1;
public static String getDataBASE_NAME() {
return DataBASE_NAME;
}
public static void setDataBASE_NAME(String dataBASE_NAME) {
DataBASE_NAME = dataBASE_NAME;
}
public static String DataBASE_NAME;
Context context;
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + "(" +
FeedReaderContract.FeedEntry._ID + "INTEGER PRIMARY KEY," +
FeedReaderContract.FeedEntry.COLUMNS_TITLE + " TEXT ," +
FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " TEXT UNIQUE)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
public FeedReaderDbHelper(Context context) {
super(context, FeedReaderDbHelper.getDataBASE_NAME(), null, DB_VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
}
void addContactValues(FeedReaderDbHelper dbhelper ,String name ,String number){
SQLiteDatabase db= dbhelper.getWritableDatabase();
ContentValues values =new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMNS_TITLE ,name);
values.put(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE,number);
long rows= db.insertWithOnConflict(FeedReaderContract.FeedEntry.TABLE_NAME,null,values,SQLiteDatabase.CONFLICT_IGNORE);
if (rows==-1){
// Toast.makeText(context, String.valueOf(rows)+"not interested", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, String.valueOf(rows)+"inserted", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
onCreate(sqLiteDatabase);
}
}
It's not clear what exact do you want, but if you want do get only rows with given values, it should looks like this:
String mSearchString = "what do you want to search";
String selection = setupSelectionString();
cursor = database.query(NoteContract.NoteEntry.NOTES_TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
private String setupSelectionString() {
String selection = null;
if (mSearchString != null) {
selection = FeedReaderContract.FeedEntry.COLUMNS_TITLE + " LIKE '%"
+ mSearchString + "%'"
+ " OR " + FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " LIKE '%"
+ mSearchString + "%'";
}
return selection;
It works in my app

How to update a password in a SQLite database (Login and Registration System)? [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
When I click Submit Button in Change password class or layout the app crashes. What's wrong with my code, please teach me! Thanks in Advance. I am working with Sqlite database for user login system and user can change their password from app bar layout. On clicking >>change password in App Bar new activity pops up i.e changePassword Activity. Upto here everything works fine but after typing password and clicking on submit button the app crashes and sets back to MainActivity.
Here is my change password class
public class changePasswordActivity extends AppCompatActivity {
EditText oldpasswordEditText;
EditText newpasswordEditText;
EditText confirmpasswordEditText;
Button btnsubmit;
String realusername, realpassword;
String checkoldpass, checknewpass, checkconfirmpass;
SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
oldpasswordEditText = findViewById(R.id.oldpasswordEditText);
newpasswordEditText = findViewById(R.id.newPasswordEditText);
confirmpasswordEditText = findViewById(R.id.confirmPasswordEditText);
btnsubmit= findViewById(R.id.btnsubmit);
checkoldpass = oldpasswordEditText.getText().toString();
checknewpass = newpasswordEditText.getText().toString();
checkconfirmpass = confirmpasswordEditText.getText().toString();
realusername = getIntent().getStringExtra("USERNAME");
realpassword= getIntent().getStringExtra("PASSWORD");
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!(checkconfirmpass.equals(checknewpass))) {
Toast.makeText(changePasswordActivity.this,"New Password didn't matched",Toast.LENGTH_SHORT).show();
}else if (!(realpassword.equals(checkoldpass))){
Toast.makeText(changePasswordActivity.this,"Old password didn't matched",Toast.LENGTH_SHORT).show();
}
else if (checkconfirmpass.equals(checkoldpass)){
Toast.makeText(changePasswordActivity.this,"New password cannot be same as old password",Toast.LENGTH_SHORT).show();
}else if(checkconfirmpass.equals(checknewpass.equals(checkoldpass))) {
Toast.makeText(changePasswordActivity.this, "New password cannot be same as old password", Toast.LENGTH_SHORT).show();
}
else{
sqLiteHelper = new SQLiteHelper(changePasswordActivity.this);
sqLiteHelper.changepassword(checknewpass,realusername);
}
}
});
}
}
Here is my SQLiteHelper class
public class SQLiteHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
private static final String DATABASE_NAME = "info.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "profile";
public static final String COLUMN_ID = "userid";
public static final String COLUMN_FULLNAME = "fullname";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASSWORD = "password";
public static final String COLUMN_MOBILE = "mobile";
private static final String CREATE_TABLE_QUERY =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FULLNAME + " TEXT, " +
COLUMN_EMAIL + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_MOBILE + " TEXT " + ")";
//modified constructor
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData() {
String query = "SELECT * FROM" + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public void changepassword(String mpassword, String mname) {
Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
+SQLiteHelper.COLUMN_PASSWORD
+" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
}
db will be null, there is also no need for a Cursor, so change
public void changepassword(String mpassword, String mname) {
Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
+SQLiteHelper.COLUMN_PASSWORD
+" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
To :-
public void changepassword(String mpassword, String mname) {
SQLiteDatabase db = this.getWriteableDatabae();
db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
+SQLiteHelper.COLUMN_PASSWORD
+" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
You will also have the same issue with the getData method so you should add SQLiteDatabase db = this.getWriteableDatabae(); to the getData method as well.
Alternately you could change :-
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
to :-
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = this.getWriteableDatabase();
}
In which case db will be a valid SQLiteDatabase.

Database Operations On Thread

I am working on android application which stores some data in database when the user starts the application it fetches data from the database to an ArrayList and keeps that ArrayList throughout the application life cycle. whenever I require an update to data I updates both database and ArrayList which holds the data, this approach reduces the CPU effort. here I have to update the database via a non ui thread, so that I need some suggestions,
1- is this a good approach ?
2- I have a database helper class which directly interacts with the database, and I am maintaining separate class for each tables, that communicates with the UI and Database helper class, so where should I implement thread , either in the Helper class or in the table corresponding class ?
code
DbHandler
#Override
public void onCreate(SQLiteDatabase db) {
FirstTable.createDatabaseTable(db);
SecondTable.createDatabaseTable(db);
}
public void insertData(String tableName, ContentValues contentValues) {
SQLiteDatabase db = getWritableDatabase();
db.insert(tableName, null, contentValues);
dbClose();
}
public Cursor readData(String tableName, String[] columns, String selection, String[]
selectionArgs, String groupBy, String having, String orderBy, String limit) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
return cursor;
}
public void deleteData(String tableName, String id, NewsItem newsItem) {
SQLiteDatabase db = getWritableDatabase();
db.delete(tableName, id + " =?", new String[]{String.valueOf(newsItem.getmGuid())});
dbClose();
}
public void updateData(String tableName, ContentValues contentValues, String where, String[] whereArgs) {
SQLiteDatabase db = getWritableDatabase();
db.update(tableName, contentValues, where, whereArgs);
dbClose();
}
public void dbClose() {
if (mDbHandler != null) {
mDbHandler.close();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
FirstTable.deleteTable(db);
SecondTable.deleteTable(db);
onCreate(db);
}
Table Specific class
public static void createDatabaseTable(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
public static void deleteTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void createData(Data data) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_TITLE, data.getTitle());
contentValues.put(COLUMN_LINK, data.getLink());
DbHandler dbHandler = DbHandler.getInstance(mContext);
dbHandler.insertData(TABLE_NAME, contentValues);
}
public ArrayList<NewsItem> readData() {
ArrayList<Data> allData = new ArrayList<>();
DbHandler dbHandler = DbHandler.getInstance(mContext);
Cursor cursor = dbHandler.readData(TABLE_NAME, null, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Data data = new Data();
data.setTitle(cursor.getString(2));
data.setLink(cursor.getString(3));
allNewsList.add(newsItem);
} while (cursor.moveToNext());
}
return allData;
}
public void deleteData(Data data) {
DbHandler dbHandler = DbHandler.getInstance(mContext);
dbHandler.deleteData(TABLE_NAME, ID, data);
}
suggest me good method
Yes its good idea to store data and maintain in background process. I like to suggest you that to make a common class to handle Database & Tables.
For example
public class DatabaseHandler extends SQLiteOpenHelper{
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "demo_database";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
private static final String TABLE_PROINFO = "proinfo";
private static final String TABLE_RETAPROINFO = "retaproinfo";
private static final String TABLE_ATTENDANCE = "attendance";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_STUDID = "studid";
private static final String KEY_AVAILABILITY = "availability";
private final ArrayList<Bean_attendance> att_list = new ArrayList<Bean_attendance>();
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
SQLiteDatabase db;
Cursor cursor;
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORY_NAME_TABLE = "CREATE TABLE " + TABLE_ATTENDANCE
+ "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_STUDID + " TEXT,"
+ KEY_AVAILABILITY + " TEXT" + ")";
db.execSQL(CREATE_CATEGORY_NAME_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
int upgradeTo = oldVersion + 1;
while (upgradeTo <= newVersion) {
switch (upgradeTo) {
case 1:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 2:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 3:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 4:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 5:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 6:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 7:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 8:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 9:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 10:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 11:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 12:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
}
upgradeTo++;
}
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
public void Add_Attandance(Bean_attendance contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STUDID, contact.getStud_id());
values.put(KEY_AVAILABILITY, contact.getAvailability());
// Inserting Row
db.insert(TABLE_ATTENDANCE, null, values);
db.close(); // Closing database connection
}
public ArrayList<Bean_attendance> Get_Attandance() {
try {
att_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ATTENDANCE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bean_attendance contact = new Bean_attendance();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setStud_id(cursor.getString(1));
contact.setAvailability(cursor.getString(2));
// Adding contact to list
att_list.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return att_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_attandance", "" + e);
}
return att_list;
}
public int Update_MainAttandnce(String availble,int id) {
String countQuery = "UPDATE " + TABLE_ATTENDANCE + " SET " + KEY_AVAILABILITY
+ " = " + "\"" + availble + "\"" + " where " + KEY_ID + "=" + "\"" + id
+ "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
public void Delete_Attandance_main(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ATTENDANCE, KEY_ID + "=" + id, null);
db.close();
}
public void Attandanceremove() {
SQLiteDatabase db = this.getWritableDatabase();
// context.deleteDatabase(DATABASE_NAME);
db.execSQL("delete from " + TABLE_ATTENDANCE);
// db.delete(DATABASE_TABLE, null, null);
}
}

My program can not find tables in sqlite database on Android

I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
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;
public class DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.

cursor.getstring() is getting the wrong field in the database

So this is my code:
public void onItemClick(AdapterView<?> listView, View view, int position, long id)
{
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
int _id = cursor.getInt(0);
String _recipe = cursor.getString(1);
Intent intent = new Intent(Luzon1Activity.this,RecipeInstruction.class);
intent.putExtra("id", _id);
intent.putExtra("recipe", _recipe);
startActivity(intent);
}
This is my code for the next activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipeinstruction);
dbHelper = new Dbadapter(this);
dbHelper.open();
bg = (RelativeLayout) findViewById(R.id.relativeLayout1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id = extras.getInt("id");
recipe = extras.getString("recipe");
}
Toast.makeText(this, id+"\n"+recipe, Toast.LENGTH_SHORT).show();
bg.setBackgroundResource(getImageId(this, recipe));
}
My problem is on this part: String _recipe = cursor.getString(1).
It always gives me the wrong data. I tried to change the number but still it gives me the wrong data.
This is my database:
package com.pinoycookbook;
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;
public class Dbadapter
{
public static final String ROWID = "_id";
public static final String NAME = "foodname";
public static final String ORIGIN = "origin";
public static final String RECIPE = "recipe";
public static final String CATEGORY = "category";
private static final String TAG = "Dbadapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "PinoyCookbook.sqlite";
public static final String SQLITE_TABLE = "Food";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
ROWID + " integer PRIMARY KEY autoincrement," +
NAME + " TEXT," +
RECIPE + " TEXT," +
ORIGIN + " TEXT," +
CATEGORY+ " TEXT,"+
" UNIQUE (" + ROWID +"));";
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
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 " + SQLITE_TABLE);
onCreate(db);
}
}
public Dbadapter(Context ctx) {
this.mCtx = ctx;
}
public Dbadapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createData(String foodname, String recipe, String origin, int i) {
ContentValues initialValues = new ContentValues();
initialValues.put(NAME, foodname);
initialValues.put(RECIPE, recipe);
initialValues.put(ORIGIN, origin);
initialValues.put(CATEGORY, i);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public boolean deleteAllData() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertData() {
createData("Adobong Manok","adobongmanok","Manila",1);
createData("Lechon","lechon","Cebu",2);
createData("Crispy Pata","crispypata","Cebu",2);
createData("Bulalo","bulalo","Batangas",1);
createData("Taba ng Talangka Rice","talangkarice","Roxas",2);
createData("Arroz Caldo","arrozcaldo","Roxas",2);
createData("Sinigang","sinigang","Manila",1);
}
}
So i recommend you to use getColumnIndex() method rather than hardcode it.
String _recipe = cursor.getString(cursor.getColumnIndex(Dbadapter.RECIPE));
It will ensure that you will get always right field. And if it still get wrong data problem is in query not in Cursor
Note: An usage of static fields that hold column names is always the best practise.
Update:
I've tried it before and it gives me this error:
java.lang.IllegalArgumentException: column 'recipe' does not exist
You need to find out your actual table structure. Try to perform this statement:
PRAGMA table_info(Dbadapter.SQLITE_TABLE);
What says docs(source):
This pragma returns one row for each column in the named table.
Columns in the result set include the column name, data type, whether
or not the column can be NULL, and the default value for the column.
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.
Example:
Here i created for you method for getting tableinfo via PRAGMA:
public String getTableInfo() {
StringBuilder b = new StringBuilder("");
Cursor c = null;
try {
db = helper.getReadableDatabase();
String query = "pragma table_info(" + Dbadapter.SQLITE_TABLE + ")";
c = db.rawQuery(query, null);
if (c.moveToFirst()) {
do {
b.append("Col:" + c.getString(c.getColumnIndex("name")) + " ");
b.append(c.getString(c.getColumnIndex("type")));
b.append("\n");
} while (c.moveToNext());
}
return b.toString();
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
Output will be something like this:
Column: type text
Column: date text
Only for imagination i will give you screen:
you can try it this way:
cursor.getString(cursor.getColumnIndex("recipe"));
it returns you the correct index and as result the correct value.

Categories

Resources