Display all data to listview using a tableview format - java

Below is my database that I have already created and it works fine, it can save the data to the database,I am really new to this android project and need guidance on how to display all data that was saved inside the listview.
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 BmiDatabase {
private data helper;
private SQLiteDatabase help;
private Context context;
public BmiDatabase(Context context){
helper = new data(context);
help = helper.getWritableDatabase();
this.context=context;
}
public long insertData(String bmi, String status, String weight){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(data.NAME, bmi);
contentValues.put(data._STATUS, status);
contentValues.put(data.WEIGHT, weight);
long id = db.insert(data.DATABASE_TABLE, null, contentValues);
db.close();
return id;
}
public String getAllData(){
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = {data.UID, data.NAME, data._STATUS, data.WEIGHT};
Cursor cursor = db.query(data.DATABASE_TABLE, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext())
{
// int index1 = cursor.getColumnIndex(data.UID);
// int cid = cursor.getInt(index1);
int cid = cursor.getInt(0);
String bmi = cursor.getString(1);
String status = cursor.getString(2);
String weight = cursor.getString(3);
buffer.append(cid +" "+bmi+" kg "+status+" "+weight+ "\n");
}
return buffer.toString();
}
public static class data extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME = "bmidatabase";
private static final String DATABASE_TABLE = "bmitable";
private static final int DB_VERSION = 7;
public static final String UID = "_id";
public static final String NAME = "Bmi";
public static final String _STATUS = "Status";
public static final String WEIGHT = "Weight";
private static final String DROP_TABLE= "DROP TABLE IF EXISTS "+DATABASE_TABLE;
private static final String CREATE_TABLE = "CREATE TABLE "+DATABASE_TABLE+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +
" "+NAME+" VARCHAR(255)," +
" "+_STATUS+" VARCHAR(255)," +
""+WEIGHT+" VARCHAR(255));";
public data(Context context){
super(context, DATABASE_NAME, null, DB_VERSION);
this.context=context;
}
public void getAllData(){
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
Message.message(context,"Database Created");
}
catch (SQLException e){
Message.message(context, "Failed" +e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
Message.message(context, "DATABASE DELETED");
db.execSQL(DROP_TABLE);
onCreate(db);
}
catch(SQLException e){
Message.message(context, "SQL FAILED");
}
}
}
}
Below is the code for my mainactivity, it shows that I can display it using a toast, but I have no idea how to call the method to populate the list view with those data.
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//private static DataHelper DataHelper;
//DataHelper helper = new DataHelper(this);
private static BmiDatabase data;
private EditText weightinputid;
private EditText heightinputid;
private Button buttonBMI, save, detail;
private TextView BMIStatus;
private TextView BMIfinal;
private double weight =0.0;
private double height =0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setupDB();
// setDB();
initializeApp();
}
private void initializeApp(){
weightinputid = (EditText) findViewById(R.id.weightid);
heightinputid = (EditText) findViewById(R.id.heightid);
buttonBMI = (Button) findViewById(R.id.buttonBMI);
BMIfinal= (TextView) findViewById(R.id.BMIfinal);
BMIStatus = (TextView) findViewById(R.id.BMIstatus);
save = (Button) findViewById(R.id.button);
detail = (Button)findViewById(R.id.button1);
data = new BmiDatabase(this);
}
public void calculateBMI (View v){
String status;
weight= Double.parseDouble(weightinputid.getText().toString());
height= Double.parseDouble(heightinputid.getText().toString());
double bmi = weight/(height/100*height/100);
String result = String.format("%.2f", bmi);
Log.d("MainActivity", result);
BMIfinal.setText(result, TextView.BufferType.NORMAL);
if(bmi < 16){
status = "Seriously Underweight";
}
else if(bmi >=16.0 && bmi < 18.0){
status = "Underweight";
}
else if(bmi >=18.0 && bmi <24.0){
status = "Normal";
}
else{
status = "Obese";
}
BMIStatus.setText(status);
}
public void save(View v){
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
String weight = weightinputid.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0)
{
Message.message(this, "");
}
else
{
Message.message(this, "");
}
}
public void detail(View v){
String d = data.getAllData();
Message.message(this, d);
}
}

Related

SQLite Foreign Key Constraints cannot be enabled or disabled while there are transactions in progress

I want to have a Sqlite database that somewhat resembles my MySql database I use to store information. In Sqlite foreign keys are disabled by default.
When I try to use the "setForeignKeyConstraintsEnabled()" command I get the following error.
java.lang.IllegalStateException: Foreign Key Constraints cannot be enabled or disabled while there are transactions in progress. Finish all transactions and release all active database connections first.
How do I fix this?
RegisterActivity
package e.adin_pc.spark;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
EditText Username,Password,Email,Birthday;
Button Register;
String insertURL = "http://10.0.2.2/skripte/insert_user.php";
RequestQueue requestQueue;
private DatabaseHandler db;
private static final String TAG = "RegisterActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Username=findViewById(R.id.UserNameReg_EditText);
Password=findViewById(R.id.PasswordReg_EditText);
Email=findViewById(R.id.EmailReg_EditText);
Birthday=findViewById(R.id.BirthdayReg_EditText);
Register=findViewById(R.id.register_Button);
db=new DatabaseHandler(this);
requestQueue = Volley.newRequestQueue(getApplicationContext());
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
insertURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Register.this,response,Toast.LENGTH_LONG).show();
//Make object
Users user=new Users();
user.setId(Integer.parseInt(
user.setUserName(Username.toString());
user.setPassword(Password.toString());
user.setEmail(Email.toString());
user.setBirthday(Birthday.toString());
user.setIs_Admin(false);
//INSERT IS CALLED HERE
boolean insert = db.InsertUser(user);
Log.i(TAG,"Uspjelo je valjda ",null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this,error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("USERNAME", Username.getText().toString());
parameters.put("PASSWORD", Password.getText().toString());
parameters.put("EMAIL", Email.getText().toString());
parameters.put("BIRTHDAY", Birthday.getText().toString());
return parameters;
}
};
requestQueue.add(stringRequest);
}
});
}
}
DB Handler code
package e.adin_pc.spark;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Adin-PC on 3/30/2018.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Spark.db";
private static final int VERSION = 1;
//Tabela1
private static final String table1_name="Users";
private static final String Users_id = "Users_id";
private static final String user_name = "user_name";
private static final String password = "password";
private static final String email = "email";
private static final String birthday = "birthday";
private static final String is_admin = "is_admin";
//Table 2
private static final String table2_name="Flights";
private static final String Flights_id = "Flights_id";
private static final String start_destination = "start_destination";
private static final String end_destination = "end_destination";
private static final String flight_start_time = "flight_start_time";
private static final String Flight_end_time = "Flight_end_time";
private static final String Price = "Price";
//Table 3
private static final String table3_name="User_flights";
private static final String User_flights_id = "User_flights_id";
private static final String User_fk = "User_fk";
private static final String Flight_fk = "Flight_fk";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String Tb1Sql="CREATE TABLE "+table1_name+" ("+
Users_id+" integer primary key , "+
user_name+" text not null,"+
password+" text not null,"+
email+" text not null,"+
birthday+" text not null,"+
is_admin+" text not null"+" )";
String Tb2Sql="CREATE TABLE "+table2_name+" ("+
Flights_id+" integer primary key , "+
start_destination+" text not null,"+
end_destination+" text not null,"+
flight_start_time+" text not null,"+
Flight_end_time+" text not null,"+
Price+" text not null"+" )";
String Tb3Sql="CREATE TABLE "+table3_name+" ("+
User_flights_id+" integer primary key , "+
User_fk+" integer not null, "+
"FOREIGN KEY ("+User_fk+") REFERENCES "+table1_name+"("+Users_id+"), "+
Flight_fk+" integer not null, "+
"FOREIGN KEY ("+Flight_fk+") REFERENCES "+table2_name+"("+Flights_id+")"+
" )";
db.setForeignKeyConstraintsEnabled(true); //ERROR IS HERE
//db.execSQL("PRAGMA foreign_keys=ON"); //THIS ALSO DOESNT WORK
db.execSQL(Tb1Sql);
db.execSQL(Tb2Sql);
db.execSQL(Tb3Sql);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table3_name);
db.execSQL("DROP TABLE IF EXISTS " + table1_name);
db.execSQL("DROP TABLE IF EXISTS " + table2_name);
onCreate(db);
}
//*---------------------------USER COMMANDS-------------------------------------------------------
public boolean InsertUser(Users New_User){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Users_id,New_User.getId());
values.put(user_name,New_User.getUserName());
values.put(password,New_User.getPassword());
values.put(email,New_User.getEmail());
values.put(birthday,New_User.getBirthday());
values.put(is_admin,New_User.getIs_Admin());
long result=db.insert(table1_name,null,values);
db.close();
if (result == -1) {
return false;
} else {
return true;
}
}
public Users GetUser(String UserName, String Password){
SQLiteDatabase db=this.getReadableDatabase();
String Query="SELECT * FROM "+ table1_name+" WHERE "+user_name+" = "+UserName+" AND "+
password+" = "+Password;
Cursor c = db.rawQuery(Query, null);
if (c != null)
c.moveToFirst();
Users user= new Users();
user.setId(c.getInt(c.getColumnIndex(Users_id)));
user.setUserName(c.getString(c.getColumnIndex(user_name)));
user.setPassword(c.getString(c.getColumnIndex(password)));
user.setEmail(c.getString(c.getColumnIndex(email)));
user.setBirthday(c.getString(c.getColumnIndex(birthday)));
String IsAdmin=c.getString(c.getColumnIndex(is_admin));
String validation;
if (IsAdmin=="true")
user.setIs_Admin(true);
else
user.setIs_Admin(false);
db.close();
return user;
}
//*---------------------------FLIGTS COMMANDS-------------------------------------------------------
public boolean InsertFlights(Flights New_flight){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(start_destination,New_flight.getStart_destination());
values.put(end_destination,New_flight.getEnd_destination());
values.put(flight_start_time,New_flight.getFlight_start_time());
values.put(Flight_end_time,New_flight.getFlight_end_time());
values.put(Price,New_flight.getPrice());
long result=db.insert(table2_name,null,values);
db.close();
if (result == -1) {
return false;
} else {
return true;
}
}
/*
* getting all flights under single user
* */
public List<Flights> getAllUSersFlights(long user_id) {
List<Flights> flights = new ArrayList<Flights>();
String selectQuery = "SELECT * FROM " + table2_name +" INNER JOIN "+ table3_name+" ON "
+ table2_name+"."+Flights_id+" = "+table3_name+"."+Flight_fk+" WHERE "+table3_name+"."+User_fk+"="+user_id;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Flights td = new Flights();
td.setId(c.getInt((c.getColumnIndex(Flights_id))));
td.setStart_destination(c.getString(c.getColumnIndex(start_destination)));
td.setEnd_destination(c.getString(c.getColumnIndex(end_destination)));
td.setFlight_start_time(c.getString(c.getColumnIndex(flight_start_time)));
td.setFlight_end_time(c.getString(c.getColumnIndex(Flight_end_time)));
td.setPrice(c.getFloat(c.getColumnIndex(Price)));
flights.add(td);
} while (c.moveToNext());
}
db.close();
return flights;
}
//*---------------------------USerFlights COMMANDS-------------------------------------------------------
public boolean InsertUSerFlights(long user_id,long flight_id ){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(User_fk, user_id);
values.put(Flight_fk, flight_id);
long result=db.insert(table3_name,null,values);
if (result == -1) {
return false;
} else {
return true;
}
}
}
Use the onConfigure() callback for calling setForeignKeyConstraintsEnabled().
onCreate() runs is executed in a transaction. It is also run only once and not for any later invocation of your app, so it's unsuitable for setting foreign keys pragma.

Android Studio project

Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.
package ie.wit.andrew.drivingschool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER"; //Making up my
//database of the
//information I will
//be entering into my
//application
public static final String COL_5 = "LESSON NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //when this constructor is
//called your Database has been
//created
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,dateofbirth);
contentValues.put(COL_4,logbooknumber);
contentValues.put(COL_5,lessonnumber);
long result = db.insert(TABLE_NAME,null,contentValues); //This method
//returns -1
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
return res;
}
}
package ie.wit.andrew.drivingschool;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
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;
public class DrivingSchool extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driving_school);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
AddData();
viewAll();
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(editName.getText().toString(),
editDateofBirth.getText().toString(),
editLogbookNumber.getText().toString(),
editLessonNumber.getText().toString());
if(isInserted = true)
Toast.makeText(DrivingSchool.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(DrivingSchool.this,"Data not
Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//Show Message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append("ID : "+ res.getString(0)+"\n");
buffer.append("NAME : "+ res.getString(1)+"\n");
buffer.append("DATE OF BIRTH : "+
res.getString(2)+"\n");
buffer.append("LOGBOOK NUMBER : "+
res.getString(3)+"\n\n");;
}
//showdata
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
Try removing space from your column name's
you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Android app stalls when implementing SQLite database

At first the app would just crash when I started it with an emulator, Not sure what I changed to get it to run but now it will run the onCreate method however, when I implement the addButtonClicked method the app just stalls and the Android Monitor displays "Suspending all threads" every few seconds and I'm not sure where to even begin debugging. Any pointers in the right direction would be greatly appreciated as I'm fairly new to Android development.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText testInput;
TextView testText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testInput = (EditText) findViewById(R.id.testInput);
testText = (TextView) findViewById(R.id.testText);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add product to database
public void addButtonClicked(View view){
Products product = new Products((testInput.getText().toString()));
dbHandler.addProduct(product);
printDatabase();
}
// Delete Items
public void deleteButtonClicked(View view){
String inputText = testText.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
testText.setText(dbString);
testInput.setText("");
}
}
Products.java
public class Products {
private int _id;
private String _productname;
public Products(){
}
public Products(String productname) {
this._productname = productname;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public int get_id() {
return _id;
}
public String get_productname() {
return _productname;
}
}
MyDBHandler.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public MyDBHandler(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_PRODUCTS +"(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLUMN_PRODUCTNAME +" TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete product from database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
//Print of DB as sting
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname"))!= null){
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
for your databaseToString method you are performing a retrieve operation. You should be doing a read operation in a thread other than UI thread. Try fetching in AsyncTask. It should work. Implementation for your databaseToString should be handled by AsyncTask.
Happy Coding..

Cant validate Login on Android app using a SQLite db

I am having a problem validating my login for my android app. I have 2 fields that require user to enter email and password, if both exist in db then they will be taken to mainscreen (log in successful) if incorrect error will appear. I have tried everything but still doesnt work! Please help I have posted my code below.
package com.example.finalproject;
import android.app.Activity;
import android.content.Context;
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.Toast;
public class LoginActivity extends Activity implements OnClickListener{
EditText mEmailAdd;
EditText mPassword;
private SQLiteAdapter mydb = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogMain:
mEmailAdd = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
String uname = mEmailAdd.getText().toString();
String pass = mPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, LoginActivity.this);
if(validLogin){
System.out.println("In Valid");
Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
startActivity(i);
finish();
}
}
break;
}
}
// #SuppressWarnings("deprecation")
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteAdapter db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onDestroy(){
super.onDestroy();
mydb.close();
}
}
DATABASE CLASS
package com.example.finalproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "MY_PROJECT_DATABASE";
public static final String MYDATABASE_TABLE = "MY_USERS_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_EMAIL + " text not null, "
+ KEY_PASSWORD + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String name, String email, String password){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_EMAIL, email);
contentValues.put(KEY_PASSWORD, password);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_NAME, KEY_EMAIL,KEY_PASSWORD};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
not your error, but change
if(uname.equals("") || uname == null){ // throws nullpointerexception if uname == null
to
if(uname == null || uname.length() == 0 ){ // throws no exception and also checks the " "
Not sure if this was just a copy-paste error but the code as provided not only doesn't compile, but never sets up the click listener for the login button either. Here's what I modified to make it both compile and query the database.
In SQLiteAdapter:
public SQLiteDatabase openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return sqLiteDatabase;
}
In LoginActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteDatabase db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
Note also that this code will never insert anything into the database, either. I assume this will be done elsewhere. Further there are many naming convention and general good practices being broken here.
A few issues:
Never do database work on the main thread.
Variables prefixed with 'm' indicate they are member variables of the class.
Be sure to use the #Override notation when appropriate.

Error on Android's rawQuery()

i got nullPointerException when trying to fetch some data from database with rawQuery.
Here's an error:
03-11 18:09:01.522: E/AndroidRuntime(2057): Uncaught handler: thread
main exiting due to uncaught exception 03-11 18:09:01.532:
E/AndroidRuntime(2057): java.lang.NullPointerException 03-11
18:09:01.532: E/AndroidRuntime(2057): at
com.math.scan.FormulaModel.setFormulaList(FormulaModel.java:27)
Look at my code:
DbHelper
package com.math.scan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "formulas";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_UNKNOWN = "unknown";
public static final String COLUMN_FORMULA = "formula";
public static final String COLUMN_CTG = "ctg";
private static final String DB_NAME = "formulas.db";
private static int DB_VERSION = 1;
private static final String DB_CREATE = "CREATE TABLE "+TABLE_NAME+
"("+COLUMN_ID+" integer primary key autoincrement,"
+COLUMN_UNKNOWN+" text not null,"
+COLUMN_FORMULA+" text not null,"
+COLUMN_CTG+" text not null );";
public Context mCtx;
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mCtx = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DB_CREATE);
// reading formulas
AssetManager asset = mCtx.getAssets();
try {
InputStream input = asset.open("formulas");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
String content = new String(buffer);
Scanner scan = new Scanner(content);
String current;
String[] f = new String[2];
String[] formula = new String[2];
while(scan.hasNextLine()) {
current = scan.nextLine();
// get category
f = current.split("!!");
formula = f[1].split(" = ");
database.execSQL("INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
Log.d("DB", "INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DbHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
FormulaModel
package com.math.scan;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class FormulaModel {
private SQLiteDatabase database;
private DbHelper dbHelper;
public FormulaModel(Context context) {
dbHelper = new DbHelper(context);
}
public void open() throws SQLException {
dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void setFormulaList(String ctg) {
open();
// app stops working here
Cursor cursor = database.rawQuery("SELECT unknown, formula FROM formulas WHERE ctg = '"+ctg+"'", null);
int results = cursor.getCount();
cursor.moveToFirst();
Global.FormuleResult = new String[results];
Global.FormuleTable = new String[results];
for(int i = 0; i < results; i++) {
Global.FormuleTable[i] = cursor.getString(1);
Global.FormuleResult[i] = cursor.getString(0);
}
close();
}
}
This is activity, where I call setFormulaList() method in FormulaModel class.
package com.math.scan;
import net.sourceforge.jeval.EvaluationException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ProblemActivity extends Activity {
private EditText prob;
private Button solve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
// text field
prob = (EditText) findViewById(R.id.problem);
// confirm btn
solve = (Button) findViewById(R.id.solve);
// check if confirm button was pressed
solve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get text from the field
String problem = prob.getText().toString();
// check if expression is not empty
if(problem.length() == 0) {
// string is empty!
Toast.makeText(ProblemActivity.this, getString(R.string.empty_field), Toast.LENGTH_SHORT).show();
} else {
FormulaModel f = new FormulaModel(ProblemActivity.this);
f.setFormulaList("mech");
pears.doMagic(problem);
try {
String str = Global.eval.getVariableValue(Global.UNKNOWN);
TextView answ = (TextView) findViewById(R.id.answer);
answ.setText(getString(R.string.prob_answ) + str);
} catch (EvaluationException e) {
Toast.makeText(ProblemActivity.this, getString(R.string.prob_error), Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
I can't figure out what is wrong here.
Any ideas?
You have to set your database variable in open():
database = dbHelper.getWritableDatabase();

Categories