Error: deleting all rows instead of 1 row Android - java

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

Related

How to resolve SQLiteException error when insert data in database

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();
}

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.

Beginner level SQLite Android App no print result

this app Able to run however it cannot print the data from the database,
i also dont know if the data is able to insert or not.
This is MainActivity.java
package com.zikri.sqlitetuto3;
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.TextView;
public class MainActivity extends AppCompatActivity {
EditText dataET;
Button addB, delB;
TextView dataTV;
MyDBHandler dbHandler;
String getProduct;
Products products;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAndroidApp();
}
public void startAndroidApp(){
dbHandler = new MyDBHandler(this,null,null,1);
dataET = (EditText) findViewById(R.id.dataET);
addB = (Button) findViewById(R.id.addB);
delB = (Button) findViewById(R.id.delB);
dataTV = (TextView) findViewById(R.id.dataTV);
getProduct = dataET.getText().toString();
PrintProduct();
addB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddProduct(getProduct);
}
});
delB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DelProduct(getProduct);
}
});
}
public void PrintProduct(){
dataTV.setText(dbHandler.PrintProduct());
dataET.setText("");
}
public void AddProduct(String p){
products = new Products(p);
dbHandler.AddProduct(products);
PrintProduct();
}
public void DelProduct(String p){
dbHandler.DelProduct(p);
PrintProduct();
}
}
This is MyDBHandler.java
package com.zikri.sqlitetuto3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "products.db";
private static final String PRODUCT_TABLE = "product";
private static final String COL_ID = "id";
private static final String COL_PRODUCTNAME = "product_name";
public MyDBHandler(Context context,
String name,SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+PRODUCT_TABLE+" ("+
COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_PRODUCTNAME+" TEXT"+");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
String query = "DROP IF EXIST "+PRODUCT_TABLE;
db.execSQL(query);
onCreate(db);
}
public void AddProduct(Products products){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_PRODUCTNAME,products.get_productname());
db.insert(PRODUCT_TABLE,null,values);
db.close();
}
public void DelProduct(String product){
SQLiteDatabase db = getWritableDatabase();
String query = "DELETE FROM "+PRODUCT_TABLE+
"WHERE "+COL_PRODUCTNAME+" = "+product+";";
db.execSQL(query);
db.close();
}
public String PrintProduct(){
SQLiteDatabase db = getWritableDatabase();
String printproductstring = "";
String query = "SELECT * FROM "+PRODUCT_TABLE+";";
Cursor cur = db.rawQuery(query,null);
cur.moveToFirst();
while(cur.moveToNext()){
printproductstring =
printproductstring+cur.getString(cur.getColumnIndex("product_name"));
printproductstring = printproductstring + "\n";
}
db.close();
return printproductstring;
}
}
This is Product.java
package com.zikri.sqlitetuto3;
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 int get_ID() {
return _ID;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public String get_productname() {
return _productname;
}
}
this is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.zikri.sqlitetuto3.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/dataET" />
<Button
android:text="INSERT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/dataET"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/addB" />
<Button
android:text="Delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/addB"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/delB" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/dataTV" />
it it very difficult to see database in android is stoered or not you can see eror on logcate if no error means it is stored but not every time .if you want still you have to see in devide manager its difficult onother solution tack one rooted mobile and intrall root brouser go to android folder inside android folder go to dada inside again go to data and then your package name then database then see there is any file which name related to your database copy this into pc and download sqllite brouser . this long process you can do you will get 100% chance to get database file.if it is created
You should take input when the button is clicked otherwise getProduct will always be empty
addB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProduct = dataET.getText().toString();
// ^^^ fetch value when button is clicked
AddProduct(getProduct);
}
});
and do the same while deletion
delB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProduct = dataET.getText().toString();
// ^^^ fetch value when button is clicked
DelProduct(getProduct);
}
});
Furthermore you can confirm the successful insertion of data by the return value of insert which is long type and defined as
the row ID of the newly inserted row, or -1 if an error occurred
so use it
long id = db.insert(PRODUCT_TABLE,null,values);
// you can now check the value of id through Logs or Toast
db.close();

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

showing the content of the table in database a list cannot be undone

I have just started to learn programming and I try to build a simple database for my exercise and I try to show all the content of the table in my database into a list in another layout but I don't know why the content isn't showing up in the list.. please help me ..
here is my apps sample
here is my activity for putting all the content in the list:
package com.DennisTA;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DaftarIstilah extends Activity{
private DataKamus dbhelper;
private SQLiteDatabase db = null;
private ListView listContent = null;
private Cursor kamusCursor = null;
CustomCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbhelper = new DataKamus(this);
setContentView(R.layout.daftaristilah);
listContent = (ListView) findViewById(R.id.list1);
isDataListView();
}
private void isDataListView() {
try {
db = dbhelper.getWritableDatabase();
kamusCursor = db.query("kamus", new String[] { "_id", "inggris",
"arti", "penjelasan" }, "_id>0", null, null, null, null);
// startManagingCursor( jasaCursor);
/*
* Create an array to specify the fields we want to display in the
* list (only the 'inggris,arti,penjelasan' column in this case)
*/
String[] from = new String[] { "inggris", "arti", "penjelasan" };
/*
* and an array of the fields we want to bind those fieiplds to (in
* this case just the textView 'inggris,arti,penjelasan' from our new row.xml
* layout above)
*/
int[] to = new int[] { R.id.inggris, R.id.arti, R.id.penjelasan };
/* Now create a simple cursor adapter.. */
adapter = new CustomCursorAdapter(this, R.layout.baris, kamusCursor,
from, to);
// listView.setAdapter(adapter);
listContent.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
} catch (Exception e) {
}
}
protected class CustomCursorAdapter extends SimpleCursorAdapter {
private int layout;
private LayoutInflater inflater;
private Context context;
public CustomCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super (context, layout, c, from, to);
this.layout = layout;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Log.d("NewView", "*****xxx");
View v = inflater.inflate(R.layout.baris, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
// 1 is the column where you're getting your data from
String inggris = c.getString(1);
String penjelasan = c.getString(3);
String arti = c.getString(2);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.inggris);
TextView des_text = (TextView) v.findViewById(R.id.penjelasan);
TextView id_text = (TextView) v.findViewById(R.id.arti);
des_text.setText(penjelasan);
id_text.setText(arti);
if (name_text != null) {
name_text.setText(inggris);
}
}
}
}
here is my baris.xml sample :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingBottom="5sp"
android:paddingTop="5sp" >
<TextView
android:id="#+id/inggris"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/arti"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/inggris" />
<TextView
android:id="#+id/penjelasan"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/arti" />
</RelativeLayout>
here is my daftar istilah.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text = "Inggris"
android:textSize="20sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text = "Arti"
android:textSize="20sp" />
<TextView
android:id="#+id/textView3"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView2"
android:text = "Penjelasan"
android:textSize="20sp" />
<ListView android:id="#+id/list1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight = "1"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"/>
</RelativeLayout>
here is my class that contain the database:
package com.DennisTA;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataKamus extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbkamus";
public static final String INGGRIS= "inggris";
public static final String ARTI = "arti";
public static final String PENJELASAN = "penjelasan";
//Constructor DataKamus untuk initiate database
public DataKamus(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//method createTable untuk membuat table kamus
public void createTable(SQLiteDatabase db){
db.execSQL("DROP TABLE IF EXISTS kamus");
db.execSQL("CREATE TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"inggris TEXT, arti TEXT, penjelasan TEXT);");
}
//method generateData untuk mengisikan data ke kamus.
public void generateData(SQLiteDatabase db){
ContentValues cv=new ContentValues();
cv.put(INGGRIS, "run");
cv.put(ARTI, "lari");
cv.put(PENJELASAN, "laufen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "walk");
cv.put(ARTI, "jalan");
cv.put(PENJELASAN, "gehen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "read");
cv.put(ARTI, "membaca");
cv.put(PENJELASAN, "lesen");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
createTable(db);
generateData(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show();
createTable(db);
generateData(db);
}
}
here is my main activity :
package com.DennisTA;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db = null;
private Cursor kamusCursor = null;
private EditText txtInggris;
private EditText txtArti;
private EditText txtPenjelasan;
private DataKamus datakamus = null;
public static final String INGGRIS = "inggris";
public static final String ARTI = "arti";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datakamus = new DataKamus(this);
db = datakamus.getWritableDatabase();
setContentView(R.layout.activity_main);
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtArti = (EditText) findViewById(R.id.txtArti);
txtPenjelasan = (EditText) findViewById(R.id.txtPenjelasan);
}
public void getTerjemahan(View view) {
String bhsindonesia = "";
String bhsjerman="";
String englishword = txtInggris.getText().toString();
kamusCursor = db.rawQuery("SELECT _ID, INGGRIS, INDONESIA, JERMAN " + "FROM kamus where INGGRIS='" + englishword + "' ORDER BY INGGRIS", null);
if (kamusCursor.moveToFirst()) {
for (; !kamusCursor.isAfterLast();
kamusCursor.moveToNext()) {
bhsindonesia = kamusCursor.getString(2);
bhsjerman = kamusCursor.getString(3);
}
}else{
Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show();
}
txtArti.setText(bhsindonesia);
txtPenjelasan.setText(bhsjerman);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
db.close();
}catch (Exception e){
}
}
}
Retrieving from database as follows:
String selectQuery = "SELECT * FROM " + Variables.TABLE_ORDER
+ " WHERE " + Variables.TABLE_ORDER_CATEGORY ;
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Food_Id", cursor.getString(0));
cart_Array_List.add(map);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
}
Try extending a BaseAdapter and ovverride the following method:
#Override
public int getCount() {
return arraylist.size();
}

Categories

Resources