How to resolve SQLiteException error when insert data in database - java

So basically I am stuck as to why I cannot add any data. I have basically followed along with a youtube tutorial from scratch but for some reason, one particular error is quite persistent. (It does not allow me to add data, as such I cannot make any use of it.)
Below is the code I have been running and any help would be appreciated :) of course, point me in the right direction if this has been asked previously...I did try searching first. I can see it says theres no column named name in user_table, but what i dont understand is there was no such step in the youtube video and it worked fine?
Forgot to add error
E/SQLiteLog: (1) table Users_Table has no column named NAME
E/SQLiteDatabase: Error inserting NAME=Kono
android.database.sqlite.SQLiteException: table Users_Table has no column named NAME (code 1 SQLITE_ERROR): , while compiling: INSERT INTO Users_Table(NAME) VALUES (?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1597)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1468)
at com.example.sqldb.dbHelper.insertData(dbHelper.java:46)
at com.example.sqldb.MainActivity$2.onClick(MainActivity.java:55)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
XML Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<ListView
android:id="#+id/usersList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/add_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Name"/>
<Button
android:id="#+id/add_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
</LinearLayout>
</LinearLayout>
Main Java Code
package com.example.sqldb;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
dbHelper db;
Button add_data;
EditText add_name;
ListView usersList;
ArrayList<String> listItem;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new dbHelper(this);
listItem = new ArrayList<>();
add_data = findViewById(R.id.add_data);
add_name = findViewById(R.id.add_name);
usersList = findViewById(R.id.usersList);
viewData();
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = usersList.getItemAtPosition(1).toString();
Toast.makeText(MainActivity.this, "" + text, Toast.LENGTH_SHORT).show();
}
});
add_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = add_name.getText().toString();
if(!name.equals("") && db.insertData(name)) {
Toast.makeText(MainActivity.this, "Data Added", Toast.LENGTH_SHORT).show();
add_name.setText("");
}else {
Toast.makeText(MainActivity.this, "Error: Data has not been added!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void viewData() {
Cursor cursor = db.viewData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
listItem.add(cursor.getString(1));
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
usersList.setAdapter(adapter);
}
}
}
Database Helper Class
package com.example.sqldb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class dbHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Users.db";
private static final String DB_TABLE = "Users_Table";
//Columns
private static final String ID = "ID";
private static final String NAME = "NAME";
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + "(" +
ID + "INTEGER PRIMARY KEY AUTOINCREMENT," +
NAME + " TEXT " + ")";
public dbHelper(Context context){
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
//Method to insert data
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
long result = db.insert(DB_TABLE, null, contentValues);
return result != -1;// if result = -1 data will not be inserted
}
//Method to create view for data
public Cursor viewData(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * from " + DB_TABLE;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
}

Can you please replace below code snippet any try again to insert:
public static final String CREATE_TABLE =
"CREATE TABLE IF NOT EXISTS " + DB_TABLE + "("
+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ NAME + " TEXT"
+ ")";
Hope this may help you.

In Helper Class leave space frond of Integer
In Main Activity
if(!name.equals("")){ db.insertData(name);
Toast.makeText(MainActivity.this, "Data Added", Toast.LENGTH_SHORT).show();
add_name.setText("");
}else {
Toast.makeText(MainActivity.this, "Error: Data has not been added!",
Toast.LENGTH_SHORT).show();
}

Related

Unable to display SQLite database in ListView (Android Studio Java)

I'm not able to display the database in ListView.
I would like to pass the 3 EditText information from DataInput.Java to Database.java in ListView.
Right now I'm able to save the detail form in DataInput.java and it will direct me to Database.java but the details are not shown in Database.java ListView.
I'm new to this so any help would be greatly appreciated!
DataInput.java code (Details Form):
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DataInput extends AppCompatActivity {
EditText event, date, descrip;
Button saveBtn;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_input);
event = (EditText)findViewById(R.id.event_text);
date = (EditText)findViewById(R.id.date_text);
descrip = (EditText)findViewById(R.id.descrip_text);
saveBtn = (Button)findViewById(R.id.save_btn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title_ = event.getText().toString()+"\n";
String date_ = date.getText().toString();
String description_ = descrip.getText().toString();
Helper dbHandler = new Helper(DataInput.this);
dbHandler.insertUserDetails(title_, date_, description_);
intent = new Intent(DataInput.this,Database.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Details Inserted Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Database.java code:
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
public class Database extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
Helper db = new Helper(this);
ArrayList<HashMap<String, String>> userList = db.GetUsers();
ListView lv = (ListView) findViewById(R.id.list_view);
ListAdapter adapter = new SimpleAdapter(Database.this,
userList, R.layout.row, new String[]{"event","description","date"}, new int[]
{R.id.event_text, R.id.date_text, R.id.descrip_text});
lv.setAdapter(adapter);
Button back = (Button)findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Database.this, MainActivity.class);
startActivity(intent);
}
});
}
}
Helper.java code:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
public class Helper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "usersdb";
private static final String TABLE_Users = "userdetails";
public static final String KEY_ID = "_id";
public static final String KEY_EVENT = "event";
public static final String KEY_DATE = "date";
public static final String KEY_DESC = "description";
public Helper(Context context){
super(context,DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_TABLE = "CREATE TABLE " + TABLE_Users + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_EVENT + " TEXT,"
+ KEY_DATE + " TEXT,"
+ KEY_DESC + " TEXT"+ ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Drop older table if exist
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Users);
// Create tables again
onCreate(db);
}
// **** CRUD (Create, Read, Update, Delete) Operations ***** //
// Adding new User Details
void insertUserDetails(String event, String date, String description){
//Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase();
//Create a new map of values, where column names are the keys
ContentValues cValues = new ContentValues();
cValues.put(KEY_EVENT, event);
cValues.put(KEY_DATE, date);
cValues.put(KEY_DESC, description);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(TABLE_Users,null, cValues);
db.close();
}
// Get User Details
public ArrayList<HashMap<String, String>> GetUsers(){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
String query = "SELECT event, date, description FROM "+ TABLE_Users;
Cursor cursor = db.rawQuery(query,null);
while (cursor.moveToNext()){
HashMap<String,String> user = new HashMap<>();
user.put("event",cursor.getString(cursor.getColumnIndex(KEY_EVENT)));
user.put("description",cursor.getString(cursor.getColumnIndex(KEY_DESC)));
user.put("date",cursor.getString(cursor.getColumnIndex(KEY_DATE)));
userList.add(user);
}
return userList;
}
// Get User Details based on userid
public ArrayList<HashMap<String, String>> GetUserByUserId(int userid){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
String query = "SELECT event, date, description FROM "+ TABLE_Users;
Cursor cursor = db.query(TABLE_Users, new String[]{KEY_EVENT, KEY_DATE, KEY_DESC}, KEY_ID+ "=?",new String[]{String.valueOf(userid)},null, null, null, null);
if (cursor.moveToNext()){
HashMap<String,String> user = new HashMap<>();
user.put("event",cursor.getString(cursor.getColumnIndex(KEY_EVENT)));
user.put("description",cursor.getString(cursor.getColumnIndex(KEY_DESC)));
user.put("date",cursor.getString(cursor.getColumnIndex(KEY_DATE)));
userList.add(user);
}
return userList;
}
// Delete User Details
public void DeleteUser(int userid){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Users, KEY_ID+" = ?",new String[]{String.valueOf(userid)});
db.close();
}
// Update User Details
public int UpdateUserDetails(String date, String description, int id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cVals = new ContentValues();
cVals.put(KEY_DATE, date);
cVals.put(KEY_DESC, description);
int count = db.update(TABLE_Users, cVals, KEY_ID+" = ?",new String[]{String.valueOf(id)});
return count;
}
}
row.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/event"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
</LinearLayout>
</LinearLayout>

Android studio SQLite can't add more than one string into database table

I'm creating an app that generates a random recipe based upon certain filters, with features to add and delete recipes. Right now I'm working on adding a recipe (which will be inputted as a URL), which is done by inserting data collected from two EditText boxes into the database. When filling out the text fields and clicking the submit button I keep get the error message "Error. Please enter some data" that I set up. Something about the db.insertData(String recipe, String category) isn't working right. It worked fine when I formatted the code to be db.insertData(String recipe), but for some reason it's not computing with multiple arguments.
MainActivity.java
package com.example.randomrecipeapp;
import com.example.randomrecipeapp.helper.DatabaseHelper;
import com.example.randomrecipeapp.model.Category;
import com.example.randomrecipeapp.model.Recipe;
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 java.util.List;
public class MainActivity extends AppCompatActivity {
//Fields
EditText add_link;
EditText add_category;
Button insert_recipe;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(getApplicationContext());
//Connect fields
add_link = findViewById(R.id.add_link);
add_category = findViewById(R.id.add_category);
insert_recipe = findViewById(R.id.insert_recipe);
insert_recipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String link = add_link.getText().toString();
String category = add_category.getText().toString();
if (!link.equals("") && !category.equals("") && db.insertData(link,category)) {
Toast.makeText(MainActivity.this, "Link and category added to database", Toast.LENGTH_SHORT).show();
add_link.setText("");
add_category.setText("");
} else {
Toast.makeText(MainActivity.this, "Error. Please enter some data", Toast.LENGTH_SHORT).show();
}
}
});
}
}
DatabaseHelper.java
package com.example.randomrecipeapp.helper;
import com.example.randomrecipeapp.model.Category;
import com.example.randomrecipeapp.model.Recipe;
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 java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
// Logcat tag
private static final String LOG = "DatabaseHelper";
//database name
private static final String DATABASE_NAME = "recipes.db";
//table names
private static final String TABLE_RECIPES = "recipes";
//common column name
private static final String KEY_ID = "id";
//RECIPES table - column names
private static final String KEY_RECIPES = "recipes";
private static final String KEY_CATEGORIES = "categories";
//CREATE TABLE statements
//create RECIPES table
private static final String CREATE_TABLE_RECIPES =
"CREATE TABLE " + TABLE_RECIPES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_RECIPES + " TEXT" + KEY_CATEGORIES + "TEXT" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_RECIPES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECIPES);
// create new tables
onCreate(db);
}
//insert data
public boolean insertData(String link, String category) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_RECIPES, link);
contentValues.put(KEY_CATEGORIES, category);
long result = db.insert(TABLE_RECIPES, null, contentValues);
return result != -1;
}
}
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/add_link"
android:layout_weight="1"
android:hint="Recipe Link"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/add_category"
android:layout_weight="1"
android:hint="Recipe Category"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/insert_recipe"
android:text="add"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Your issue is that due to a few errors in the create table SQL, that no column named categories exists and thus the insert fails returning -1.
You have :-
private static final String CREATE_TABLE_RECIPES =
"CREATE TABLE " + TABLE_RECIPES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_RECIPES + " TEXT" + KEY_CATEGORIES + "TEXT" + ")";
It should be :-
private static final String CREATE_TABLE_RECIPES =
"CREATE TABLE " + TABLE_RECIPES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_RECIPES + " TEXT," + KEY_CATEGORIES + " TEXT" + ")";
i.e.
The comma that should separate the recipes column and the categories column has been omitted.
There needs to be a space between categories and TEXT
After amending the code you will need to do one of the following:-
delete the App's data, or,
uninstall the App, or
increase the database version number from 1 i.e. change super(context, DATABASE_NAME, null, 1); to super(context, DATABASE_NAME, null, 2); //<<<<<<<<<< Changed 1 to 2
After doing one of the above you should then rerun the App.

How can I display a column from my database into a text view in Android Studio?

Hey guys I have been trying this for 2 days now and I cant seem to get it to work. I have tried every tutorial! I am new to android studio and have been trying to make a simple app where I can register and login. I was able to create the database and insert a new row(user) to the database.[Register user]. And also I was able to log the user in.
What I am trying to do now, is retrieve a column or column from the row and display it in a text view.
For example, once I login with a user, I want to display their information from the columns, such as phone number, address, etc.
When the app is first launched, there is a registration activity. you can either register or proceed to the login activity. Once you are logged in from the login activity, there is a new activity where I want to display the information of that logged in user.
databasehelper.java
package easy.eightfivehundred.easy;
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="register.db";
public static final String TABLE_NAME="register";
public static final String COL_1="ID";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="HomeAddress";
public static final String COL_5="Phone";
public static final String COL_6="Email";
public static final String COL_7="Password";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, FirstName TEXT, LastName TEXT, HomeAddress TEXT, Phone TEXT, Email TEXT, Password TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
mainactivity
package easy.eightfivehundred.easy;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 MainActivity extends AppCompatActivity {
SQLiteOpenHelper openHelper;
SQLiteDatabase db;
Button Registerbutton, Loginbutton;
EditText Firstnametxt, Lastnametxt, Homeaddresstxt, Phonenumbertxt, Emailtext, Passwordtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openHelper = new DatabaseHelper(this);
Registerbutton =(Button)findViewById(R.id.RegisterButton);
Loginbutton = (Button)findViewById(R.id.LogInButton);
Firstnametxt =(EditText)findViewById(R.id.FirstNameText);
Lastnametxt =(EditText)findViewById(R.id.LastNameText);
Homeaddresstxt =(EditText)findViewById(R.id.HomeAddressText);
Phonenumbertxt =(EditText)findViewById(R.id.PhoneText);
Emailtext =(EditText)findViewById(R.id.EmailText);
Passwordtext =(EditText)findViewById(R.id.PasswordText);
Registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db = openHelper.getWritableDatabase();
String first = Firstnametxt.getText().toString();
String last = Lastnametxt.getText().toString();
String address = Homeaddresstxt.getText().toString();
String phone = Phonenumbertxt.getText().toString();
String email = Emailtext.getText().toString();
String password = Passwordtext.getText().toString();
insertData(first, last, address, phone, email, password);
Toast.makeText(getApplicationContext(), "You Registered Successfully!", Toast.LENGTH_LONG).show();
}
});
Loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, login.class);
startActivity(intent);
}
});
}
public void insertData(String first, String last, String address, String phone, String email, String password) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_2, first);
contentValues.put(DatabaseHelper.COL_3, last);
contentValues.put(DatabaseHelper.COL_4, address);
contentValues.put(DatabaseHelper.COL_5, phone);
contentValues.put(DatabaseHelper.COL_6, email);
contentValues.put(DatabaseHelper.COL_7, password);
long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
}
login
package easy.eightfivehundred.easy;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 login extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Button Loginbutton;
EditText Emailtext, Passwordtext;
Cursor cursor;
public static final String EXTRA_MESSAGE = " ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
openHelper = new DatabaseHelper(this);
db = openHelper.getReadableDatabase();
Loginbutton = (Button)findViewById(R.id.loginbutton);
Emailtext = (EditText)findViewById(R.id.emaillogintext);
Passwordtext = (EditText)findViewById(R.id.passwordlogintext);
Loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = Emailtext.getText().toString();
String password = Passwordtext.getText().toString();
cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.COL_6 + "=? AND " + DatabaseHelper.COL_7 + "=? ", new String[]{email, password});
if(cursor != null){
if(cursor.getCount() > 0){
cursor.moveToNext();
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(login.this, UserHome.class);
intent.putExtra(EXTRA_MESSAGE, email);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
userhome
package easy.eightfivehundred.easy;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import static easy.eightfivehundred.easy.DatabaseHelper.TABLE_NAME;
public class UserHome extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_home);
Intent intent = getIntent();
String email = intent.getStringExtra(login.EXTRA_MESSAGE);
}
}
In the userhome.java file is where I'm having trouble at. I simply want to display the columns from the logged in user on this page.
This should get you on your way:-
Step 1.
Amend the layout to include the TextViews with id's that will be used to show the extracted data e.g. :-
<TextView
android:id="#+id/firstname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/lastname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/homaddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Step 2.
Add a method (added to DatabAseHelper.java although could be elsewhere like your InsertData method in MainActivity.java) to get the data as a Cursor.
e.g. :-
public Cursor getUserInfo(String email) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = COL_6 + "=?"; //<<<< select according to email
String[] whereargs = new String[]{email};
return db.query(
TABLE_NAME,
null,
whereclause,
whereargs,
null,null,null
);
}
The above will equate to
SELECT * FROM register WHERE Email = '??????'
where ?????? will the string as passed to the method.
Step 3.
In Userhome.java declare the class variables for the TextViews, an instance of YOUR DatabaseHelper (not SQLiteOpenHelper) and the Cursor (you already have this).
e.g. :-
TextView mFirstName, mLastName, mHomeAddress, mPhone, mEmail, mPassword;
DatabaseHelper mDBHlpr;
Cursor cursor;
Step 4.
Again in UserHome.java as the onCreate method use :-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //<<<< USE YOUR LAYOUT
Intent intent = getIntent();
String email = intent.getStringExtra(login.EXTRA_MESSAGE);
//<<<<<<<<<< NEW CODE >>>>>>>>>>
mFirstName = (TextView) this.findViewById(R.id.firstname);
mLastName = (TextView) this.findViewById(R.id.lastname);
mHomeAddress = (TextView) this.findViewById(R.id.homaddress);
mPhone = (TextView) this.findViewById(R.id.phone);
mEmail = (TextView) this.findViewById(R.id.email);
mPassword = (TextView) this.findViewById(R.id.password);
mDBHlpr = new DatabaseHelper(this); //<<<< get Instance of DatbaseHelper
cursor = mDBHlpr.getUserInfo(email); //<<< get the Cursor according to email
if (cursor.moveToFirst()) {
mFirstName.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_2)));
mLastName.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_3)));
mHomeAddress.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_4)));
mPhone.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_5)));
mEmail.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_6)));
mPassword.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_7)));
} else {
// HANDLE NO DATA THAT MATCHES WHERE CLAUSE
mFirstName.setText("Sorry No User found that has email as :- " + email);
}
cursor.close(); //<<<< DONE WITH THE CURSOR SO CLOSE IT
}
A Cursor when returned will be positioned at a position before the first row (position -1). To get to the data you need to move to a row.
The move????? methods return true or false. The former if the move could be made (so moveToFirst, if there are no rows will return false, or true if there is at least one row). Hence how you can use if (cursor.moveToFirst()){.....}.
So if there is data (a row or more, one is assumed as there should probably not be users with the same email) the TextView's are populated (otherwise i.e. else, the firstname TextView indicates user not found (shouldn't happen though)).
Data is extracted from the Cursor using get????? (getString in this case, there are other methods such as getInt, getLong ......).
The get???? methods take an integer, the column offset (first column ID is offset 0, the 2nd firstname is offset 1 ......). However, using hard coded offsets can easily result in issues, so it's recommended to use the Cursor getColumnIndex, which returns the column offset according to the column name (more flexible).
Note how the column names are retrieved from the DatabaseHelper, using this way reduces the chance for typing errors.
You could consider changing your onCreate method in the DatabaseHelper to also utilise this single source for column names by using (replaced code commented out).
:-
#Override
public void onCreate(SQLiteDatabase db) {
String crt_sql = "CREATE TABLE " + TABLE_NAME + "(" +
// Note AUTOINCREMENT is very likely not needed
// refer to https://sqlite.org/autoinc.html
COL_1 + " INTEGER PRIMARY KEY, " +
COL_2 + " TEXT, " +
COL_3 + " TEXT, " +
COL_4 + " TEXT, " +
COL_5 + " TEXT, " +
COL_6 + " TEXT, " +
COL_7 + " TEXT " +
")";
db.execSQL(crt_sql);
/*
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FirstName TEXT, LastName TEXT, HomeAddress TEXT, Phone TEXT, Email TEXT, Password TEXT)");
*/
}
You may wish to have a look at SQLite Autoincrement in regads to the exclusion of the AUTOINCREMENT keyword.
You may also wish to have a look at Cursor for the numerous Cursor methods (e.g. get???? and move?????)
Testing
the above was tested by adding a user who's first name was Fred, lastname FlitStone ... using this snippet of code :-
mDBHlpr.insertUser("Fred",
"Flintsone",
"1 The Caves, Bedrock",
"01 2345 6789",
email_for_testing,
"fredflintsone"
);
resulting in :-

Caused by: android.database.sqlite.SQLiteException: no such column: TITLE (code 1): , while compiling: SELECT TITLE, STORY FROM MY_TABLE

I'm working on a simple application that contains short stories and I'm trying to use a database but I got an error:
Caused by: android.database.sqlite.SQLiteException: no such column: TITLE (code 1): , while compiling: SELECT TITLE, STORY FROM MY_TABLE
SQLiteActivity.java
package com.scriptos.testsqlit;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteActivity {
private static String DBNAME = "Sqlite_simple.db";
private static String TABLE = "MY_TABLE";
private static String COLUMN_1 = "TITLE";
private static String COLUMN_2 = "STORY";
private SQLiteDatabase database;
private SQLiteOpenHelper helper_database;
private Context context;
public SQLiteActivity(Context c){
context = c;
}
public SQLiteActivity Read() throws android.database.SQLException {
helper_database = new SQLiteHelper(context, DBNAME, null, 1);
database = helper_database.getReadableDatabase();
return this;
}
public SQLiteActivity Write() throws android.database.SQLException {
helper_database = new SQLiteHelper(context, DBNAME, null, 1);
database = helper_database.getWritableDatabase();
return this;
}
public void close(){
helper_database.close();
}
public long insert(String title, String story){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_1, title);
contentValues.put(COLUMN_2, story);
return database.insert(TABLE, null, contentValues);
}
public int deleteAll(){
return database.delete(TABLE, null, null);
}
public String[] getAll(){
String[] columns = new String[]{COLUMN_1,COLUMN_2};
Cursor cursor = database.query(TABLE, columns,
null, null, null, null, null);
String [] result = new String[cursor.getCount()];
int title = cursor.getColumnIndex(COLUMN_1);
int story = cursor.getColumnIndex(COLUMN_2);
int a = 0;
for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
result [a] =
cursor.getString(title) + " " +
cursor.getString(story) ;
a++;
}
return result;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE + " (ID INTEGER KEY, "+COLUMN_1+ "TEXT, "+COLUMN_2 +"TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
MainActivity.java
package com.scriptos.testsqlit;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView;
SQLiteActivity db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
listView = (ListView) findViewById(R.id.list);
String[] adapter = new String[] { "a", "b", "c",};
ArrayAdapter<String> i = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, adapter);
listView.setAdapter(i);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://andrody.com/"));
startActivity(i);
}
if (position == 1) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.facebook.com/andrody2015"));
startActivity(i);
}
if (position == 2) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.youtube.com/channel/UCAGUgnnL47fU3TMRhKhkQwQ"));
startActivity(i);
}
}
});
db = new SQLiteActivity(this);
db.Write();
db.deleteAll();
db.insert("title1", "story1");
db.insert("title2","story2");
db.insert("title3","story3");
db.close();
SHOW();
}
public void SHOW() {
db.Read();
String [] x = db.getAll();
db.close();
}
}
content_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff5ffcf">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
</ScrollView>
</LinearLayout>
What should I do to correct this?
Your create table line;
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE +
" (ID INTEGER KEY, "+COLUMN_1+ "TEXT, "+COLUMN_2 +"TEXT);");
...generates the SQL...
CREATE TABLE IF NOT EXISTS MY_TABLE (ID INTEGER KEY, TITLETEXT, STORYTEXT);
...which, due to missing spaces is not valid SQL and won't create the table.
Add the missing spaces to your create table, and it should work better.
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE +
" (ID INTEGER KEY, "+COLUMN_1+ " TEXT, "+COLUMN_2 +" TEXT);");
CREATE TABLE IF NOT EXISTS MY_TABLE (ID INTEGER KEY, TITLE TEXT, STORY TEXT);
i think no space is there in your table creation
CREATE TABLE IF NOT EXISTS " + TABLE + " (ID INTEGER KEY, "+COLUMN_1+"
TEXT, "+COLUMN_2 +" TEXT);");
it may be better

Error: deleting all rows instead of 1 row Android

I am currently using Java Eclipse to make an android app. This app has an SQLite database that contains data. I can view this data in a list. And i can also add items to this database fine. I am now tring to delete a specific row from the database. But whenever i try to it deletes all the rows as oppose to the one the user has selected.
Here is my adapter:
package com.example.beer_budget3;
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;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
Here is my deleting page:
package com.example.beer_budget3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
db.open();
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
And here is my XML file for the deleting page:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
I personally think the error is in this line in the adapter:
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
Because i understand you have to be very specific with where you places your spaces and quotations. But i have changed this line of code around a few times and couldn't fix my problem.
Any advice would be much appreciated!
Your function here :
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
should be
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ Pub_Name+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
You specify the column name instead of the value

Categories

Resources