android sqlite read all rows at once - java

Is there a way to read all the rows in an sqlite table and display them at once in a textview?
This is how I read them and it reads line by line ....
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_ISBN,
KEY_TITLE,
KEY_PUBLISHER},
null,
null,
null,
null,
null);
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;
public class DatabaseActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
//---get all titles---
db.open();
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db.close();
}
}
public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"ISBN: " + c.getString(1) + "\n" +
"TITLE: " + c.getString(2) + "\n" +
"PUBLISHER: " + c.getString(3),
Toast.LENGTH_LONG).show();
}

First of all, you might want to look into listviews to easily display a list of data like this.
If your goal really is to display all information in one textview (or toast as you're making now), you could try making one large string, with which you create the toast:
//---get all titles---
db.open();
Cursor c = db.getAllTitles();
String text = "";
if (c.moveToFirst())
{
do {
DisplayTitle(c, text);
} while (c.moveToNext());
}
db.close();
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
public void DisplayTitle(Cursor c, String text)
{
text +=
"id: " + c.getString(0) + "\n" +
"ISBN: " + c.getString(1) + "\n" +
"TITLE: " + c.getString(2) + "\n" +
"PUBLISHER: " + c.getString(3);
}

db.getReadableDatabase();
StringBuffer sb=new StringBuffer();
Cursor c=db.rawQuery(SELECT * FROM TABLE_NAME);
while(c.moveToNext){
sb.append(c.getString(0);//c.getString(Column Index)
sb.append(c.getString(1);
//getString( till n number of Columns you have )
}
textView.setText(sb);

Related

SQLiteException: no such table Android Studio [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
Where I made mistake?
When I try to insert data into database, I get Toast message that I inserter,but in LOG file i see error:
no such table: reservation (code 1): , while compiling: INSERT INTO reservation(phone,address,surname,name,start,destination) VALUES (?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
DBHelper.java
package com.example.demir.carsharing;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.TextView;
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "carsharing.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
public static final String RES_TABLE="reservation";
public static final String COLUMN_NAME="name";
public static final String COLUMN_SURNAME="surname";
public static final String COLUMN_ADDRESS="address";
public static final String COLUMN_PHONE="phone";
public static final String COLUMN_START="start";
public static final String COLUMN_DESTINATION="destination";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public static final String CREATE_TABLE_RESERVATION = "CREATE TABLE " + RES_TABLE + "("
+ COLUMN_NAME + " TEXT,"
+ COLUMN_SURNAME + " TEXT,"
+ COLUMN_ADDRESS + " TEXT,"
+ COLUMN_PHONE + " TEXT,"
+ COLUMN_START + " TEXT,"
+ COLUMN_DESTINATION + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_RESERVATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST" + USER_TABLE);
onCreate(db);
db.execSQL("DROP TABLE IF EXIST" + RES_TABLE);
onCreate(db);
}
public void addUser(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String email, String pass) {
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_EMAIL + " = " + "'" + email + "'" + " and " + COLUMN_PASS + " = " + "'" + pass + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
// method for inserting data from method reservation
public void addReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_SURNAME, surname);
values.put(COLUMN_ADDRESS, address);
values.put(COLUMN_PHONE, phone);
values.put(COLUMN_START, start);
values.put(COLUMN_DESTINATION, destination);
long a = db.insert(RES_TABLE, null, values);
db.close();
Log.e(TAG, "Data insetred" + a);
}
//Get data from Reservation
public boolean getData(String name, String surname, String address, String phone, String start, String destination) {
String query = "select * from " + RES_TABLE + " where " +
COLUMN_NAME + " = " + "'" + name + "'" + " , " + COLUMN_SURNAME + " = " + "'" + surname + "'" +
COLUMN_ADDRESS + " = " + "'" + address + "'" + " , " + COLUMN_PHONE + " = " + "'" + phone + "'" +
COLUMN_START + " = " + "'" + start + "'" + " , " + COLUMN_DESTINATION + " = " + "'" + destination + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
//insert data iinto Reservation
public boolean insertReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",name);
contentValues.put("surname",surname);
contentValues.put("address",address);
contentValues.put("phone",phone);
contentValues.put("start",start);
contentValues.put("destination",destination);
db.insert("reservation",null,contentValues);
return true;
}
}
Reservation.java
package com.example.demir.carsharing;
import android.content.Intent;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static com.example.demir.carsharing.R.id.etName;
public class ReservationActivity extends AppCompatActivity {
private Button save;
private EditText name, surname, address, phone, start, destination;
private DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
db = new DbHelper(this);
name = (EditText) findViewById(etName);
surname = (EditText) findViewById(R.id.etSurname);
address = (EditText) findViewById(R.id.etAddress);
phone = (EditText) findViewById(R.id.etPhone);
start = (EditText) findViewById(R.id.etStart);
destination = (EditText) findViewById(R.id.etDestination);
save = (Button) findViewById(R.id.btnSave);
AddData();
}
public void AddData(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = db.insertReservation(name.getText().toString(),
surname.getText().toString(),
address.getText().toString(),
phone.getText().toString(),
start.getText().toString(),
destination.getText().toString());
if(isInserted==true)
Toast.makeText(ReservationActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(ReservationActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
});
}
}
You might have made changes to your helper class after creating the tables for the first time, in which case you must clear your app's data before you rerun, in your device/emulator go to App Info and the Clear Data "for >= Marshmallow go to App Info -> Storage -> Clear Data"
You don't have to delete and reinstall the whole app. that would be a waste of time.

i get a null reference exception after trying to print data from my database in android studio

Thank for reading my inquiry. I know this question has been asked before but I didn't find the answer I was looking for in the other responses. I hope I will ask the right question.
this code is for my DataBase Handler.
It houses all the methods that pertain to it, such as creating the table, adding and deleting entries and printing the database in my app.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class EmailDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "loginEntries.db";
public static final String TABLE_LOGINENTRIES = "loginEntries";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NICKNAME = "nickname";
public static final String COLUMN_EMAILADDRESS = "emailAddress";
public static final String COLUMN_PASSWORD = "password";
public static final String COLUMN_LASTNAME = "lastName";
public static final String COLUMN_FIRSTNAME = "firstName";
public EmailDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_LOGINENTRIES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NICKNAME + " TEXT, " +
COLUMN_EMAILADDRESS + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_LASTNAME + " TEXT, " +
COLUMN_FIRSTNAME + " TEXT " +
/*COLUMN_PHONENUMBER + " INTEGER " +*/
");";
db.execSQL(query);
String queryTwo = "INSERT INTO " + TABLE_LOGINENTRIES +
" (" + COLUMN_EMAILADDRESS + ", " +
COLUMN_NICKNAME + ", " +
COLUMN_PASSWORD + ", " +
COLUMN_FIRSTNAME + ", " +
COLUMN_LASTNAME + " " +
/* COLUMN_PHONENUMBER +*/ ")" + " VALUES " + " (\'email address\', \'nickname\', \'password\', \' First Name\', \'Last Name \');";
db.execSQL(queryTwo);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGINENTRIES);
onCreate(db);
}
public String logInCheck(String loginEmailEntry){
//used to find email and password in the database to compare to entered entries to confirm user
String passwordHolder;
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT " + COLUMN_PASSWORD + " FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS + "=\"" + loginEmailEntry + "\"";
Cursor c = db.rawQuery(query, null);
passwordHolder = c.getString(c.getColumnIndex(COLUMN_PASSWORD));
db.close();
c.close();
return passwordHolder;
}
public boolean signUpEmailCheck(String emailEntry){
//checks if a new email entry already exists in the database
Integer holder;
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS + "=\"" + emailEntry + "\"";
Cursor c = db.rawQuery(query,null);
holder = c.getColumnCount();
if (holder > 0) {
db.close();
c.close();
return true;
} else {
db.close();
c.close();
return false;
}
}
//add new row to Database
public void addEntry(LoginEntries entry){
ContentValues values = new ContentValues();
values.put(COLUMN_EMAILADDRESS,entry.get_emailAddress());
values.put(COLUMN_PASSWORD,entry.get_password());
values.put(COLUMN_FIRSTNAME,entry.get_firstName());
values.put(COLUMN_LASTNAME,entry.get_lastName());
values.put(COLUMN_NICKNAME,entry.get_nickname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_LOGINENTRIES, null, values);
db.close();
}
//delete items from database
public void deleteEmailEntry(String emailEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS + "=\"" +
emailEntry + "\";");
}
public void deleteNickname(String nicknameEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_NICKNAME + "=\"" +
nicknameEntry + "\";");
}
public void deletePasswordEntry(String passwordEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_PASSWORD + "=\"" +
passwordEntry + "\";");
}
public void deleteLastNameEntry(String lastNameEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_LASTNAME + "=\"" +
lastNameEntry + "\";");
}
public void deleteFirstNameEntry(String FirstNameEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_FIRSTNAME + "=\"" +
FirstNameEntry + "\";");
}
//Print database as a string
public String emailDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_EMAILADDRESS)) !=null){
dbString += c.getString(c.getColumnIndex(COLUMN_EMAILADDRESS));
dbString += "\n";
}c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String passwordDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_PASSWORD)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_PASSWORD));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String firstNameDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_FIRSTNAME)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_FIRSTNAME));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String lastNameDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_LASTNAME)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_LASTNAME));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String nicknameDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_NICKNAME)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_NICKNAME));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
}
This class is my sign up class, where I input new data into my database. Most of the if statements dictate the user if they are entering data incorrectly.
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SignUpMainClass extends AppCompatActivity{
EditText newEmailAddressInput;
EditText newPasswordInput;
EditText confirmNewPasswordInput;
TextView newFirstNameInput;
TextView newLastNameInput;
TextView newNickname;
TextView displayNickname;
TextView displayEmail;
TextView displayPassword;
TextView displayFirstName;
TextView displayLastName;
// EditText newPhoneNumberInput;
EmailDBHandler dbHandler;
//SignUpWelcomeScreen inputEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_main);
newEmailAddressInput = (EditText) findViewById(R.id.newEmailAddressInput);
newPasswordInput = (EditText) findViewById(R.id.newPasswordInput);
confirmNewPasswordInput = (EditText) findViewById(R.id.confirmNewPasswordInput);
newFirstNameInput = (TextView) findViewById(R.id.newFirstNameInput);
newLastNameInput = (TextView) findViewById(R.id.newLastNameInput);
newNickname = (TextView) findViewById(R.id.newNickname);
dbHandler = new EmailDBHandler(this, null, null, 1);
Bundle nameData = getIntent().getExtras();
if(nameData == null){
return;
}
String newFirstNameMessage =nameData.getString("newFirstNameMessage");
String newLastNameMessage =nameData.getString("newLastNameMessage");
String newNicknameMessage =nameData.getString("newNicknameMessage");
newFirstNameInput.setText(newFirstNameMessage);
newLastNameInput.setText(newLastNameMessage);
newNickname.setText(newNicknameMessage);
}
public void registerAccount(View view) {
LoginEntries emailEntry = new LoginEntries(newEmailAddressInput.getText().toString(), "", "", "", "");
String isTempEmail = newEmailAddressInput.getText().toString();
LoginEntries passwordEntry = new LoginEntries("", newPasswordInput.getText().toString(), "", "","");
String isTempPass = newPasswordInput.getText().toString();
String confirmPasswordHolder = confirmNewPasswordInput.getText().toString();
LoginEntries newFirstNameEntry = new LoginEntries("", "", newFirstNameInput.getText().toString(), "", "");
LoginEntries newLastNameEntry = new LoginEntries("", "", "", newLastNameInput.getText().toString(),"");
LoginEntries newNicknameEntry = new LoginEntries("", "", "", "", newNickname.getText().toString());
if (TextUtils.isEmpty(isTempEmail) && TextUtils.isEmpty(isTempPass)) {
Toast.makeText(this, "Enter Email and Password", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (TextUtils.isEmpty(isTempEmail) && !TextUtils.isEmpty(isTempPass)) {
Toast.makeText(this, "Enter Email", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (!TextUtils.isEmpty(isTempEmail) && TextUtils.isEmpty(isTempPass)) {
Toast.makeText(this, "Enter Password", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} /*Temporary while app is offline, when app will be operational, different prompt will search web to verify email address*/
else if (!isTempEmail.endsWith("#gmail.com") && !isTempEmail.endsWith("#yahoo.com") && !isTempEmail.endsWith("#aol.com") && !isTempEmail.endsWith("#hotmail.com")) {
Toast.makeText(this, "Not a valid email address, trying again", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (!dbHandler.signUpEmailCheck(isTempEmail)) {
Toast.makeText(this, "Email used, please try again", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (!confirmPasswordHolder.equals(isTempPass)) {
Toast.makeText(this, "Passwords don't match!", Toast.LENGTH_LONG).show();
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else{
Intent i = new Intent(this, SecondarySignUpClass.class);
String firstName = newFirstNameInput.getText().toString();
String lastName = newLastNameInput.getText().toString();
String nickname = newNickname.getText().toString();
i.putExtra("newFirstNameMessage",firstName);
i.putExtra("newLastNameMessage",lastName);
i.putExtra("newNicknameMessage", nickname);
startActivity(i);
Toast.makeText(this, "Saved!", Toast.LENGTH_LONG).show();
dbHandler.addEntry(emailEntry);// adds email to database
dbHandler.addEntry(passwordEntry);//adds password to database
dbHandler.addEntry(newFirstNameEntry);//adds First Name to database
dbHandler.addEntry(newLastNameEntry);//adds Last name to database
dbHandler.addEntry(newNicknameEntry);//adds Nickname to Database
printDatabase();
}
}
public void printDatabase(){
String dbEmailString = dbHandler.emailDatabaseToString();
String dbPasswordString = dbHandler.passwordDatabaseToString();
String dbFirstNameString = dbHandler.firstNameDatabaseToString();
String dbLastNameString = dbHandler.lastNameDatabaseToString();
String dbNicknameString= dbHandler.nicknameDatabaseToString();
displayEmail.setText(dbEmailString);
displayPassword.setText(dbPasswordString);
displayFirstName.setText(dbFirstNameString);
displayLastName.setText(dbLastNameString);
displayNickname.setText(dbNicknameString);
}
}
My input process is simple. It is meant to be a login in for a generic app, most likely a social app. User presses a sign up button, it takes him to the xml that the above class is attached to. The user puts in the data(first name, last name, email, password, nickname) and presses the Register button which is the associated with the Register account method. The information is then supposed to be entered into the database, from which I can later extract it. But it doesn't.
This is the error message I receive in my logcat when I try to extract data from the database. I assume that I missed something Small that plays a big part but I'm not sure what it is.
Process: com.example.vitaliy_2.emailpassworddatabasetrial, PID: 15139
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(App CompatViewInflater.java:275)
at android.view.View.performClick(View.java:5191)
at android.view.View$PerformClick.run(View.java:20916)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5191) 
at android.view.View$PerformClick.run(View.java:20916) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5972) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.vitaliy_2.emailpassworddatabasetrial.SignUpMainClass.printDatabase(SignUpMainClass.java:165)
at com.example.vitaliy_2.emailpassworddatabasetrial.SignUpMainClass.registerAccount(SignUpMainClass.java:135)
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270) 
at android.view.View.performClick(View.java:5191) 
at android.view.View$PerformClick.run(View.java:20916) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5972) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)at com.android.internal.os.Zygote
Init.main(ZygoteInit.java:1194) 
Thank you for getting this far.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.TextView.setText(java.lang.CharSequence)'
on a null object reference
TextView object is null .
At first you need to set all TextView id after setContentView(R.layout.signup_main);
displayNickname = (TextView) findViewById(R.id.Your_Id);
displayEmail = (TextView) findViewById(R.id.You_id);
.......// Call Rest of Textview //.............
Your display TextView objects don"t seem to have been initialized anywhere :
TextView displayNickname;
TextView displayEmail;
TextView displayPassword;
TextView displayFirstName;
TextView displayLastName;

Android SQLite issue - table __ has no column named ___

I am a new developer and I am having an SQLite issue. Some reason I am not able to add two columns (table_row_three, and table_row_four) to my SQLite data table. When I read the database file currently, it has a table with "id", "table_row_one", and "table_row_two", but is missing "table_row_three" and "table_row_four".
The error message in my logcat reads: "(1) table database_table has no column named table_row_three".
I am really confused to why the columns "table_row_three" and "table_row_four" are not showing up on my table, and why only "id", "table_row_one", and "table_row_two" appear in my data table.
Here is my Database class:
DatabaseHandler.java
import java.util.ArrayList;
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 DatabaseHandler
{
Context context;
private SQLiteDatabase db;
private final String DB_NAME = "database_name";
private final int DB_VERSION = 2;
private final String TABLE_NAME = "database_table";
private final String TABLE_ROW_ID = "id";
private final String TABLE_ROW_ONE = "table_row_one";
private final String TABLE_ROW_TWO = "table_row_two";
private final String TABLE_ROW_THREE = "table_row_three";
private final String TABLE_ROW_FOUR = "table_row_four";
public DatabaseHandler(Context context)
{
this.context = context;
// create or open the database
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
//TABLE_ROW_ONE = Title
//TABLE_ROW_TWO = Location
//TABLE_ROW_THREE = Notes
//TABLE_ROW_FOUR = Picture
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
// ask the database object to insert the new data
try{db.insert(TABLE_NAME, null, values);}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID)
{
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public ArrayList<Object> getRowAsArray(long rowID)
{
ArrayList<Object> rowArray = new ArrayList<Object>();
Cursor cursor;
try
{
cursor = db.query
(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
rowArray.add(cursor.getLong(0));
rowArray.add(cursor.getString(1));
rowArray.add(cursor.getString(2));
rowArray.add(cursor.getString(3));
rowArray.add(cursor.getString(4));
}
while (cursor.moveToNext());
}
cursor.close();
}
catch (SQLException e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
// return the ArrayList containing the given row from the database.
return rowArray;
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
{
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor;
try
{
cursor = db.query(
TABLE_NAME,
new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR},
null, null, null, null, null
);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataList.add(cursor.getString(4));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
}
catch (SQLException e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return dataArrays;
}
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
public CustomSQLiteOpenHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text" +
TABLE_ROW_THREE + " text" +
TABLE_ROW_FOUR + " text" +
");";
db.execSQL(newTableQueryString);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
Here is my Test class:
public class DatabaseExampleActivity extends Activity {
EditText textFieldOne, textFieldTwo, textFieldThree, textFieldFour,
idField,
updateIDField, updateTextFieldOne, updateTextFieldTwo,updateTextFieldThree, updateTextFieldFour;
Button addButton, deleteButton, retrieveButton, updateButton;
TableLayout dataTable;
DatabaseHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
// this try catch block returns better error reporting to the log
try {
// Android specific calls
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_databaseexample);
// create the database manager object
db = new DatabaseHandler(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
// load the data table
updateTable();
} catch (Exception e) {
Log.e("ERROR", e.toString());
e.printStackTrace();
}
}
private void setupViews() {
// THE DATA TABLE
dataTable = (TableLayout) findViewById(R.id.data_table);
// THE DATA FORM FIELDS
textFieldOne = (EditText) findViewById(R.id.text_field_one);
textFieldTwo = (EditText) findViewById(R.id.text_field_two);
textFieldThree = (EditText) findViewById(R.id.text_field_three);
textFieldFour = (EditText) findViewById(R.id.text_field_four);
idField = (EditText) findViewById(R.id.id_field);
updateIDField = (EditText) findViewById(R.id.update_id_field);
updateTextFieldOne = (EditText) findViewById(R.id.update_text_field_one);
updateTextFieldTwo = (EditText) findViewById(R.id.update_text_field_two);
updateTextFieldThree = (EditText) findViewById(R.id.update_text_field_three);
updateTextFieldFour = (EditText) findViewById(R.id.update_text_field_four);
addButton = (Button) findViewById(R.id.add_button);
deleteButton = (Button) findViewById(R.id.delete_button);
retrieveButton = (Button) findViewById(R.id.retrieve_button);
updateButton = (Button) findViewById(R.id.update_button);
}
private void addButtonListeners() {
addButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
addRow();
}
}
);
deleteButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteRow();
}
}
);
updateButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
updateRow();
}
}
);
retrieveButton.setOnClickListener
(
new View.OnClickListener() {
#Override
public void onClick(View v) {
retrieveRow();
}
}
);
}
private void addRow() {
try {
// ask the database manager to add a row given the two strings
db.addRow
(
textFieldOne.getText().toString(),
textFieldTwo.getText().toString(),
textFieldThree.getText().toString(),
textFieldFour.getText().toString()
);
// request the table be updated
updateTable();
// remove all user input from the Activity
emptyFormFields();
} catch (Exception e) {
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
private void deleteRow() {
try {
// ask the database manager to delete the row with the give rowID.
db.deleteRow(Long.parseLong(idField.getText().toString()));
// request the table be updated
updateTable();
// remove all user input from the Activity
emptyFormFields();
} catch (Exception e) {
Log.e("Delete Error", e.toString());
e.printStackTrace();
}
}
private void retrieveRow() {
try {
// The ArrayList that holds the row data
ArrayList<Object> row;
// ask the database manager to retrieve the row with the given rowID
row = db.getRowAsArray(Long.parseLong(updateIDField.getText().toString()));
// update the form fields to hold the retrieved data
updateTextFieldOne.setText((String) row.get(1));
updateTextFieldTwo.setText((String) row.get(2));
updateTextFieldThree.setText((String) row.get(3));
updateTextFieldFour.setText((String) row.get(4));
} catch (Exception e) {
Log.e("Retrieve Error", e.toString());
e.printStackTrace();
}
}
private void updateRow() {
try {
// ask the database manager to update the row based on the information
// found in the corresponding user entry fields
db.updateRow
(
Long.parseLong(updateIDField.getText().toString()),
updateTextFieldOne.getText().toString(),
updateTextFieldTwo.getText().toString(),
updateTextFieldThree.getText().toString(),
updateTextFieldFour.getText().toString()
);
updateTable();
emptyFormFields();
} catch (Exception e) {
Log.e("Update Error", e.toString());
e.printStackTrace();
}
}
private void emptyFormFields() {
textFieldOne.setText("");
textFieldTwo.setText("");
textFieldThree.setText("");
textFieldFour.setText("");
idField.setText("");
updateIDField.setText("");
updateTextFieldOne.setText("");
updateTextFieldTwo.setText("");
updateTextFieldThree.setText("");
updateTextFieldFour.setText("");
}
private void updateTable() {
// delete all but the first row. remember that the count
// starts at one and the index starts at zero
while (dataTable.getChildCount() > 1) {
// while there are at least two rows in the table widget, delete
// the second row.
dataTable.removeViewAt(1);
}
// collect the current row information from the database and
// store it in a two dimensional ArrayList
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
// iterate the ArrayList, create new rows each time and add them
// to the table widget.
for (int position = 0; position < data.size(); position++) {
TableRow tableRow = new TableRow(this);
ArrayList<Object> row = data.get(position);
TextView idText = new TextView(this);
idText.setText(row.get(0).toString());
tableRow.addView(idText);
TextView textOne = new TextView(this);
textOne.setText(row.get(1).toString());
tableRow.addView(textOne);
TextView textTwo = new TextView(this);
textTwo.setText(row.get(2).toString());
tableRow.addView(textTwo);
TextView textThree = new TextView(this);
textThree.setText(row.get(3).toString());
tableRow.addView(textThree);
TextView textFour = new TextView(this);
textFour.setText(row.get(4).toString());
tableRow.addView(textFour);
dataTable.addView(tableRow);
}
}
Missing ',' in create statement :
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +
");";
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text" +
TABLE_ROW_THREE + " text" +
TABLE_ROW_FOUR + " text" +
");";
In this statement you missed two commas after type defind. Thats why the field is not created so you found that exception. And one another thing after the close parenthesis ");" the semicolon is not required.
Replace your code to :-
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +
")";
I hope this will help you. :)
TABLE_ROW_TWO + " text" +
TABLE_ROW_THREE + " text" +
TABLE_ROW_FOUR + " text" +
put , after text
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +
Change CustomSQLiteOpenHelper code like this,
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
public CustomSQLiteOpenHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " text," +
TABLE_ROW_THREE + " text," +
TABLE_ROW_FOUR + " text" +
");";
db.execSQL(newTableQueryString);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}

How i insert intent method to this code for when click button it will show second activity

Here is the java activity that provide to add data for record in SQLite. My question is how i insert some code for when clicking button and it will show second activity. i don't know where i should insert. And don't know what the code should be. please help me.
import java.sql.PreparedStatement;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddStudent extends Activity {
DatabaseStudent mHelper;
SQLiteDatabase mDb;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
mHelper = new DatabaseStudent(this);
mDb = mHelper.getWritableDatabase();
final EditText editName = (EditText)findViewById(R.id.editName);
final EditText editLastName = (EditText)findViewById(R.id.editLastName);
ImageView buttonAdd = (ImageView)findViewById(R.id.imageAdd);
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = editName.getText().toString();
String lastname = editLastName.getText().toString();
String condition = getIntent().getStringExtra("Condition");
double school = getIntent().getDoubleExtra("Intent", 0);
//Date&Time
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
if(name.length() != 0 && lastname.length() != 0
) {//&& school.length() != 0
Cursor mCursor = mDb.rawQuery("SELECT * FROM "
+ DatabaseStudent.TABLE_NAME + " WHERE "
+ DatabaseStudent.COL_NAME + "='" + name + "'"
+ " AND " + DatabaseStudent.COL_LASTNAME + "='"
+ lastname + "'" + " AND "
+ DatabaseStudent.COL_SCHOOL + "='" + school //add COL_SCHOOL = currentTime
+ "'"+ " AND " + DatabaseStudent.COL_TIME + "='" + currentTime
+ "'"+ " AND " + DatabaseStudent.COL_CON + "='" + condition
+ "'", null);
if(mCursor.getCount() == 0) {
mDb.execSQL("INSERT INTO " + DatabaseStudent.TABLE_NAME
+ " (" + DatabaseStudent.COL_NAME
+ ", " + DatabaseStudent.COL_LASTNAME
+ ", " + DatabaseStudent.COL_SCHOOL
+ ", " + DatabaseStudent.COL_TIME
+ ", " + DatabaseStudent.COL_CON
+ ") VALUES ('" + name + "', '" + lastname
+ "', '" + school + "', '" + currentTime + "', '" + condition + "');");
editName.setText("");
editLastName.setText("");
Toast.makeText(getApplicationContext()
, "Already added"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext()
, "This data is exist"
, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext()
, "Please fill in the blank"
, Toast.LENGTH_SHORT).show();
}
}
});
}
public void onStop() {
super.onStop();
mHelper.close();
mDb.close();
}
}
You'd want to insert any code you want executed when you hit a button in the onClick method, which you have as seen here:
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do stuff when buttonAdd is clicked
}
});
Now you can use intents inside the onClick method to begin a second activity, like so:
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(current_activity.this, second_activity.class);
startActivity(intent);
}
});
You can consult the following for more details: http://developer.android.com/training/basics/firstapp/starting-activity.html

Retrieving all data from database

I have encountered a problem while I was developing my Android application. I am trying to retrieve all the data from my Android application, but I don't exactly know how. Here is my DBAdapter.java class:
package com.example.foodsaver2;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.AvoidXfermode;
import android.util.Log;
import com.example.*;
public class DBAdapter {
public static final String KEY_ROWID = "rowid";
public static final String KEY_CUSTOMER = "customer";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_ADDRESS1 = "address1";
public static final String KEY_ADDRESS2 = "address2";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_ZIP = "zipCode";
public static final String KEY_SEARCH = "searchData";
public static final String TOTAL_CARB = "carb";
public static final String FIBER = "fiber";
public static final String SUGAR = "sugar";
public static final String PROTEIN = "protein";
public static final String SODIUM = "salt";
public static final String TOTALCALORIES = "calories";
public static Context contextOfApplication;
private static final String TAG = "DBAdapter";
private DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;
private static final String DATABASE_NAME = "Data";
private static final String FTS_VIRTUAL_TABLE = "Info";
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_CREATE1 =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
KEY_CUSTOMER + /*"INTEGER," + */ "," +
KEY_NAME + "," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
KEY_SEARCH + "," +
TOTAL_CARB + "," +
FIBER + "," +
SUGAR + "," +
PROTEIN + "," +
SODIUM + "," +
TOTALCALORIES + "," +
" UNIQUE (" + KEY_CUSTOMER + "));";
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) {
Log.w(TAG, DATABASE_CREATE1);
db.execSQL(DATABASE_CREATE1);
}
public static Context getContextOfApplication(){
return contextOfApplication;
}
#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 " + FTS_VIRTUAL_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 createCustomer(String customer, String name, String address1, String address2, String city, String state, String zipCode, String carb, String fiber, String sugar, String protein, String sodium, String calories) {
ContentValues initialValues = new ContentValues();
String searchValue = customer + " " +
name + " " +
address1 + " " +
city + " " +
state + " " +
zipCode;
initialValues.put(KEY_CUSTOMER, customer);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS1, address1);
initialValues.put(KEY_ADDRESS2, address2);
initialValues.put(KEY_CITY, city);
initialValues.put(KEY_STATE, state);
initialValues.put(KEY_ZIP, zipCode);
initialValues.put(KEY_SEARCH, searchValue);
initialValues.put(TOTAL_CARB, carb);
initialValues.put(FIBER, fiber);
initialValues.put(SUGAR, sugar);
initialValues.put(PROTEIN, protein);
initialValues.put(SODIUM, sodium);
initialValues.put(TOTALCALORIES, calories);
return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
public Cursor searchCustomer(String inputText) throws SQLException {
Log.w(TAG, inputText);
String query = "SELECT docid as _id," +
KEY_CUSTOMER + "," +
KEY_NAME + "," +
"(" + KEY_ADDRESS1 + "||" +
"(case when " + KEY_ADDRESS2 + "> '' then '\n' || " + KEY_ADDRESS2 + " else '' end)) as " + KEY_ADDRESS +"," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
TOTAL_CARB + "," +
FIBER + "," +
SUGAR + "," +
PROTEIN + "," +
SODIUM + "," +
TOTALCALORIES +
" from " + FTS_VIRTUAL_TABLE +
" where " + KEY_SEARCH + " MATCH '" + inputText + "';";
Log.w(TAG, query);
Cursor mCursor = mDb.rawQuery(query,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean deleteAllCustomers() {
int doneDelete = 0;
doneDelete = mDb.delete(FTS_VIRTUAL_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
}
Here is my SendFeedback.java class, where I try to retrieve the data.
package com.example.foodsaver2;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by mother on 2/7/14.
*/
public class SendFeedback extends Activity {
private DBAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_feedback);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
}
public void send (View v) {
Cursor c = mDbHelper.getData();
GmailSender sender = new GmailSender("omitted for privacy", "omitted for privacy");
try {
sender.sendMail("This is Subject",
"This is Body",
"omitted for privacy",
"omitted for privacy");
Toast.makeText(getApplicationContext(), "Sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot send message!", Toast.LENGTH_SHORT).show();
}
}
}
I don't know how to do this. I have searched the internet and SO for a while, but I can't find a solution. I don't have any experience with SQLiteDatabases either. Any help regarding this problem is appreciated.
This is a good tutorial on sqlite databases on android:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
take a look a this extract:
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return comments;
}
And
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
so for your app you could have:
public List getAllComments() {
List customers = new ArrayList();
Cursor cursor = database.query(FTS_VIRTUAL_TABLE, new String[]{"KEY_CUSTOMER", "KEY_NAME " , etc..}, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Customer customer = cursorToCustomer(cursor);
customers.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return customers;
}
And
private Customer cursorToCustomer(Cursor cursor) {
Customer customer = new Customer();
customer.setCustomer(cursor.getString(0));
customer.setName(cursor.getString(1));
customer.setAddress1(cursor.getString(2));
customer.setAddress2(cursor.getString(3));
customer.setCity(cursor.getString(4));
customer.setState(cursor.getString(5));
customer.setZipCode(cursor.getString(6));
customer.setSearchValue(cursor.getString(7));
customer.setCarb(cursor.getString(8));
customer.setFiber(cursor.getString(9));
customer.setSugar(cursor.getString(10));
customer.setProtein(cursor.getString(11));
customer.setSodium(cursor.getString(12));
customer.setCalories(cursor.getString(13));
return comment;
}
PS: You need to create your own class "Customer" to hold the data shown here

Categories