SQLite database connection issue - java

Hi i am trying to make give connection with SQLlite database. Code is looking fine but database table is not created.App is running well but database is not created. Any suggestions?? My codes:
DatabaseManager.java
package com.step2rock.www.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import com.step2rock.www.model.User;
/**
* Created by Sushimz on 5/15/2016.
*/
public class DatabaseManager extends SQLiteOpenHelper {
Context context;
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "photography";
// Users table name
private static final String TABLE_USERS = "users";
//blog table name
private static final String TABLE_BLOG = "blog";
// Users Table Columns names
private static final String KEY_USER_ID = "id";
private static final String KEY_USER_first_NAME = "f_name";
private static final String KEY_USER_last_NAME = "l_name";
private static final String KEY_USER_PASS = "password";
private static final String KEY_USER_PIC = "profilepic";
private static final String KEY_USER_Address = "address";
private static final String KEY_USER_Exp = "exp_level";
private static final String KEY_USER_link = "link";
private static final String KEY_USER_TYPE = "type";
// Blog Table Columns names
private static final String KEY_Blog_ID = "id";
private static final String KEY_Blog_Title = "blog_tilte";
private static final String KEY_Blog_Desc = "blog_desc";
private static final String KEY_Blog_Image = "blog_image";
private static final String KEY_Blog_Link = "blog_link";
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("users",TABLE_USERS);
Log.d("blog",TABLE_BLOG);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS
+ "("
+ KEY_USER_ID + " INTEGER PRIMARY KEY,"
+ KEY_USER_first_NAME + " TEXT,"
+ KEY_USER_last_NAME + " TEXT,"
+ KEY_USER_PASS + " TEXT,"
+ KEY_USER_PIC + " TEXT,"
+ KEY_USER_Address + " TEXT,"
+ KEY_USER_Exp + " TEXT,"
+ KEY_USER_link + " TEXT,"
+ KEY_USER_TYPE + " TEXT,"
+ ")";
db.execSQL(CREATE_USERS_TABLE);
String CREATE_BLOG_TABLE = "CREATE TABLE " + TABLE_BLOG
+ "("
+ KEY_Blog_ID + " INTEGER PRIMARY KEY,"
+ KEY_Blog_Title + " TEXT,"
+ KEY_Blog_Desc + " TEXT,"
+ KEY_Blog_Image + " TEXT,"
+ KEY_Blog_Link + " TEXT ,"
+ " FOREIGN KEY(" + KEY_USER_ID + ") REFERENCES Users(id) ON DELETE CASCADE "
+ ")";
db.execSQL(CREATE_BLOG_TABLE);
Toast.makeText(this.context, "AAA", Toast.LENGTH_SHORT).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLOG);
// Create tables again
onCreate(db);
}
public void resetDB() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLOG);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new USER
public int addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user.get_user_id());
values.put(KEY_USER_first_NAME, user.get_first_name());
values.put(KEY_USER_last_NAME, user.get_last_name());
values.put(KEY_USER_PASS, user.get_user_pass());
values.put(KEY_USER_PIC, user.get_user_pic());
values.put(KEY_USER_Address, user.get_user_address());
values.put(KEY_USER_Exp, user.get_user_exp());
values.put(KEY_USER_link, user.get_user_link());
values.put(KEY_USER_TYPE, user.get_user_type());
// Inserting Row
int last_id = (int) db.insert(TABLE_USERS, null, values);
db.close(); // Closing database connection
return last_id;
}
// Updating single User
public int updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user.get_user_id());
values.put(KEY_USER_first_NAME, user.get_first_name());
values.put(KEY_USER_last_NAME, user.get_last_name());
values.put(KEY_USER_PASS, user.get_user_pass());
values.put(KEY_USER_PIC, user.get_user_pic());
values.put(KEY_USER_Address, user.get_user_address());
values.put(KEY_USER_Exp, user.get_user_exp());
values.put(KEY_USER_link, user.get_user_link());
values.put(KEY_USER_TYPE, user.get_user_type());
// updating row
return db.update(TABLE_USERS, values, KEY_USER_ID + " = ?",
new String[]{String.valueOf(user.get_user_id())});
}
}
RegistrationActivity.java
package com.step2rock.www.crudproject;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.step2rock.www.database.DatabaseManager;
/**
* Created by Sushimz on 5/15/2016.
*/
public class RegistrationActivity extends AppCompatActivity {
Button btnSaveRecord;
DatabaseManager databaseManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_activity);
btnSaveRecord = (Button) findViewById(R.id.btnSaveRecord);
databaseManager = new DatabaseManager(RegistrationActivity.this);
btnSaveRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast toast = Toast.makeText(RegistrationActivity.this,"welcome",Toast.LENGTH_SHORT);
toast.show();
}
});
}
}

The SQLiteOpenHelper you have there looks quite good.
Confusingly onCreate(...) is never called because it does not have the same behavior as an Activity.onCreate(...).
From the documentation:
Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
As far as I understand your code, the database is never created (unless you did it elsewhere). To create it you need to try to execute something on the database. For example, try to add a User on your button click. This will call getWriteableDdatabase() and should invoke onCreate(...):
btnSaveRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int id = databaseManager.addUser(new User(...));
Toast toast = Toast.makeText(RegistrationActivity.this,"Welcome User #" + id,Toast.LENGTH_SHORT);
toast.show();
}
});
Check if this calls your onCreate(...) method.
I'd also suggest you to add IF NOT EXISTS to your createTable Strings like so:"CREATE TABLE IF NOT EXISTS " + TABLE_USERS. This way, if you ever add a table, the others will not throw an error or be overwritten when the new table is created.

Related

SQLite query not creating a table; no errors generated

I am trying to create a table using SQLite however the Create Table query does not seem to be working. When i open the .db file in an online viewer there is no data/table in the file (attached). I am not getting any errors when debugging; the issue. I have been deleting old .db files and making sure the onCreate code is running.
https://wsi.li/OzOSD2tTsB1qua/
Database Helper Code below:
package com.example.lewis.food;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Food.db";
public static final String TABLE_NAME = "food_table";
public static final String ID = "ID";
public static final String DESCRIPTION = "DESCRIPTION";
public static final String INGREDIENTS = "INGREDIENTS";
public static final String METHOD = "METHOD";
public static final String NOTES = "NOTES";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
try {
SQLiteDatabase db = this.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" CREATE TABLE " + TABLE_NAME + " (" +
ID + " TEXT PRIMARY KEY, " +
DESCRIPTION + " TEXT, " +
INGREDIENTS + " TEXT, " +
METHOD + " TEXT, " +
NOTES + " TEXT NOT NULL);"
);
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Issue 1.
The onUpgrade method is part of the onCreate method move it to be out side the onCreate method. e.g. :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Food.db";
public static final String TABLE_NAME = "food_table";
public static final String ID = "ID";
public static final String DESCRIPTION = "DESCRIPTION";
public static final String INGREDIENTS = "INGREDIENTS";
public static final String METHOD = "METHOD";
public static final String NOTES = "NOTES";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
try {
SQLiteDatabase db = this.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" CREATE TABLE " + TABLE_NAME + " (" +
ID + " TEXT PRIMARY KEY, " +
DESCRIPTION + " TEXT, " +
INGREDIENTS + " TEXT, " +
METHOD + " TEXT, " +
NOTES + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade (SQLiteDatabase db,int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Note this may well just be that you dropped in the wrong code, as the code you have shown would very likely not compile.
Issue 2.
You are likely looking in the wrong place for the database/table.
The following code as the invoking activity (MainActivity used in the code) will confirm that the database is being created as well as the table, it will also print out the location of the database :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DatabaseHelper(this);
Cursor csr = mDBHlpr.getReadableDatabase().query("sqlite_master",null,null,null,null,null,null);
Log.d("DBLOCATION",this.getDatabasePath(DatabaseHelper.DATABASE_NAME).getAbsolutePath());
while (csr.moveToNext()) {
Log.d(
"DBINFO",
"Found a " + csr.getString(csr.getColumnIndex("type")) +
" named " + csr.getString(csr.getColumnIndex("name"))
);
}
csr.close();
}
}
When run (using only the above code) the result is :-
11-14 00:33:23.565 1246-1246/? D/DBLOCATION: /data/data/so53291104.so53291104/databases/Food.db
11-14 00:33:23.565 1246-1246/? D/DBINFO: Found a table named android_metadata
11-14 00:33:23.565 1246-1246/? D/DBINFO: Found a table named food_table
11-14 00:33:23.565 1246-1246/? D/DBINFO: Found a index named sqlite_autoindex_food_table_1
That is the above code creates the database, the table and the index on the food column (unless it already exists) and then logs some information about the actual database.
Note the DBLOCATION will depend upon your package and will not be the same as above.
You may wish to delete the App's data or uninstall the App before running any amended code.

SQLiteException: no such table Android Studio [duplicate]

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

execSQL only displayng last line of XML

I have seen a lot of similar problems here, but none solved my problem.
Im making an app that put the contents of a XML in a database. Everything is working fine but when I open the app for a second time more and more values are added. I was trying to drop table, drop database, and even deleting the file and none of these worked.
Now I added this code and the app is only parsing the LAST line of the xml to the database, and I really dont know why this happens.
myDatabase.execSQL("DROP TABLE " + DATABASE_TABLE);
myDatabase.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_LINK + " TEXT NOT NULL);"
);
Full code:
XMLHelper:
package com.example.partedoxml;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHelper extends DefaultHandler {
private String URL_MAIN = "http://he4dless.webege.com/packages.xml";
String TAG = "XMLHelper";
Boolean currTag = false;
String currTagVal = "";
public PostValue menes = null;
public ArrayList<PostValue> he4dless = new ArrayList<PostValue>();
public void get() {
try{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser mSaxParser = factory.newSAXParser();
XMLReader mXmlReader = mSaxParser.getXMLReader();
mXmlReader.setContentHandler(this);
InputStream mInputStream = new URL(URL_MAIN).openStream();
mXmlReader.parse(new InputSource(mInputStream));
}catch(Exception e){
Log.e(TAG, "Exeption:"+e.getMessage());
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(currTag){
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currTag = false;
//if(localName.equalsIgnoreCase("id"))
//packages.setId(currTagVal);
if(localName.equalsIgnoreCase("name"))
menes.setName(currTagVal);
else if(localName.equalsIgnoreCase("link"))
menes.setLink(currTagVal);
else if(localName.equalsIgnoreCase("menes"))
he4dless.add(menes);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i(TAG, "TAG:"+localName);
currTag = true;
currTagVal = "";
if(localName.equals("menes"))
menes = new PostValue();
}
}
SQLHelper:
package com.example.partedoxml;
import java.io.File;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLHelper {
public static final String DATABASE_NAME = "he4dless";
public static final String DATABASE_TABLE = "menes";
public static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_LINK = "link";
public static final String TAG_1 = "tag1";
public static final String TAG_2 = "tag2";
public static final String TAG_3 = "tag3";
private DbHelper myHelper;
private Context myContext;
private SQLiteDatabase myDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_LINK + " TEXT NOT NULL);"
//TAG_1 + " TEXT NOT NULL, " +
//TAG_2 + " TEXT NOT NULL, " +
//TAG_3 + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public SQLHelper(Context c){
myContext = c;
}
public SQLHelper open(){
myHelper = new DbHelper(myContext);
myDatabase = myHelper.getWritableDatabase();
myDatabase.execSQL("DROP TABLE " + DATABASE_TABLE);
myDatabase.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_LINK + " TEXT NOT NULL);"
);
return this;
}
public void close(){
myHelper.close();
}
public long create(String name, String link) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_LINK, link);
return myDatabase.insert(DATABASE_TABLE, null, cv);
}
}
MainActivity:
package com.example.partedoxml;
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
new PostAsync().execute();
}
class PostAsync extends AsyncTask<Void, Void, Void>{
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Esta porra esta carregando", "Baixando o XML", true, false);
}
#Override
protected Void doInBackground(Void... params) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for(PostValue post : helper.he4dless){
//builder.append("\nId: "+ post.getId());
builder.append("\nName: "+ post.getName());
builder.append("\nSection: "+ post.getLink());
builder.append("\n");
String name = post.getName();
String link = post.getLink();
SQLHelper entry = new SQLHelper(MainActivity.this);
entry.open();
entry.create(name, link);
entry.close();
}
tv.setText(builder.toString());
pd.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I will be very glad if someone solves this problem
Your open() drops and recreates the table, and you reopen the database in each for loop iteration.
Leave schema setup to the helper callbacks such as onCreate(). Also, you don't need to reopen the database inside the loop.
The problem you have is that the method open() in SQLHelper performs the following:
//You are calling here an instance of your helper. Good.
myHelper = new DbHelper(myContext);
//This step will get you a database. See my explanatino below to understand what happens here
myDatabase = myHelper.getWritableDatabase();
//THIS LINES SHOULD BE REMOVED
//In this step you will delete the database (actually only the table) and ALL data
myDatabase.execSQL("DROP TABLE " + DATABASE_TABLE);
//You create the same database again.
myDatabase.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_LINK + " TEXT NOT NULL);"
);
You are actually doing some work twice. When you try to get the writable database you are already calling the method onCreate if the database does not exists. So that you create the database, you delete it, and you create back again empty.
Your code should be the following in open() method and everything should work:
public SQLHelper open(){
myHelper = new DbHelper(myContext);
myDatabase = myHelper.getWritableDatabase();
Finally, I would like also to highlight a potential problem. On the method OnUpgrade you are setting up that your database is also deleted and created back again when you change the version of the database. That means that everytime you modify the value of DATABASE_VERSION the complete data will dissapear.
If you are interested in modifying a value already in the database, you can update it, for example, for the item with KEY_NAME name you can update the value of KEY_LINK adding link2:
public int create(String name, String link2) {
ContentValues cv = new ContentValues();
cv.put(KEY_LINK, link2);
return myDatabase.update(DATABASE_TABLE, cv, KEY_NAME + "=" + name, null );
}

SQLLite Android table not acknowledging database changes - "no such column: type (code 1):"

I am trying to add a key to my SQLite DB but when I try to access the new column, the program throws "no such column type (code 1)". I verified in SQLite Editor that the new column is in fact present. Am I missing something?
SOLUTION FOUND
My Database creation was NOT taking in the DATABASE_VERSION, I had simply set it to use "1". As soon as I set it to use that variable, and changed it from 1 to 2, it updated my database!
Here is my class
package com.example.blizz_000.lureorganizer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.sql.SQLException;
public class LureOrganizer {
public com.example.blizz_000.lureorganizer.DatabaseHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public static final String KEY_NAME = "model";
public static final String KEY_MAKER = "company";
public static final String KEY_SIZE = "size";
public static final String KEY_COLOR = "color";
public static final String KEY_TYPE = "TEST";
public static final String KEY_ROWID = "_id";
private static final String DATABASE_NAME = "fishing_db";
private static final String DATABASE_TABLE = "LURES";
public static int DATABASE_VERSION = 1;
// DATABASE HELPER CLASS*********************************************************
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE +" (" +
KEY_ROWID +"INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT, " +
KEY_MAKER + " TEXT, " +
KEY_COLOR + " TEXT, " +
"TEST text, " +
KEY_SIZE + " TEXT);");
//db.execSQL("ALTER TABLE LURES ADD COLUMN TEST TEST"); // Won't find the table
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
// END DATABASE HELPER CLASS *********************************************************
//*********************BEGIN MY METHODS**************************
public LureOrganizer(Context c) {
ourContext = c;}
//Opens Db
public LureOrganizer open() throws SQLException{
ourHelper = new com.example.blizz_000.lureorganizer.DatabaseHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;}
//Opens Db NO EXCEPTION
public LureOrganizer opennoe() {
ourHelper = new com.example.blizz_000.lureorganizer.DatabaseHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;}
//Closes Db
public void close() {
ourHelper.close();}
//Entries
public long createEntry(String name, String maker, String color, String size, String type) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_MAKER, maker);
cv.put(KEY_COLOR, color);
cv.put(KEY_SIZE, size);
cv.put(KEY_TYPE, type);
return ourDatabase.insert(DATABASE_TABLE, null, cv);}
//RETRIEVE ALL PIECES OF THE DATA *****************************************************************************************************//
//Retrive Data for SINGLE PIECE
public String[] getData(String id) {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_MAKER, KEY_COLOR, KEY_SIZE};
Cursor d = ourDatabase.rawQuery("select * from LURES WHERE _id = ?",
new String[]{id});
String[] resultarray = new String[5];
int iName = d.getColumnIndex(KEY_NAME);
int iMaker = d.getColumnIndex(KEY_MAKER);
int iColor = d.getColumnIndex(KEY_COLOR);
int iSize = d.getColumnIndex(KEY_SIZE);
int iType = d.getColumnIndex(KEY_TYPE);
for (d.moveToFirst(); !d.isAfterLast(); d.moveToNext()) {
resultarray[0] = d.getString(iMaker);
resultarray[1] = d.getString(iName);
resultarray[2] = d.getString(iColor);
resultarray[3] = d.getString(iSize);
resultarray[4] = d.getString(iType);
}
return resultarray;
}
//Retrieve Data
public String[] getName() {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_MAKER, KEY_COLOR, KEY_SIZE, KEY_TYPE};
Cursor d = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result ="";
String[] resultarray = new String[5];
int iRow = d.getColumnIndex(KEY_ROWID);
int iName = d.getColumnIndex(KEY_NAME);
int iMaker = d.getColumnIndex(KEY_MAKER);
int iColor = d.getColumnIndex(KEY_COLOR);
int iSize = d.getColumnIndex(KEY_SIZE);
int iType = d.getColumnIndex(KEY_TYPE);
for(d.moveToFirst(); !d.isAfterLast(); d.moveToNext()){
resultarray[0] = d.getString(iMaker);
resultarray[1] = d.getString(iName);
resultarray[2] = d.getString(iColor);
resultarray[3] = d.getString(iSize);
resultarray[4] = d.getString(iType);
}
return resultarray;
}
//CURSOR READER
public Cursor readEntry() {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_MAKER, KEY_COLOR, KEY_SIZE, KEY_TYPE};
Cursor d = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
return d;
}
public void DeleteRow(String id) {
ourDatabase.delete(DATABASE_TABLE, "_id = ?",
new String[]{id});
}
}
I know that the code works other than the KEY_TYPE stuff, so I don't feel it is necessary to include other classes, but I will if it helps.
When you change your database structure (i.e.: altering a table), you have to inform it that your db has changed.
This is done by setting the DATABASE_VERSION constant to a higher value, i.e.: 2.
So:
public static int DATABASE_VERSION = 2;
This will let the onUpgrade() method fire and recreate the table.
And you miss a space after KEY_ROWID:
db.execSQL("CREATE TABLE " + DATABASE_TABLE +" (" +
KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT, " + KEY_MAKER + " TEXT, " +
KEY_COLOR + " TEXT, " + "TEST text, " + KEY_SIZE + " TEXT)");
Whenever you are creating the object to Database open helper it wont call onCreate of that class. only first time that too when you call getWritableDatabse() or getReadableDatabase() at that time only it will call if the database file not exist in your application. why i am saying this because you have written some alter command over there.
If you run the application with out uninstalling at that time database file will not be deleted so it wont call oncreate of that class.
while writing database related code better to uninstall and run the application.
and you are missing one space after the id coloumn.
db.execSQL("CREATE TABLE " + DATABASE_TABLE +" (" +
KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT, " +
KEY_MAKER + " TEXT, " +
KEY_COLOR + " TEXT, " +
"TEST text, " +
KEY_SIZE + " TEXT);");
I hope this will help you.

Android Saving String to Database

I am new in Android development, And right now what I am trying to do is to save Message that I type and Username. I got this code from vogella.com, but it was written only for messages. And I have tried to add Username, but I get an error "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdatabaseactivity/com.example.testdatabaseactivity.TestDatabaseActivity}: android.database.sqlite.SQLiteException: no such column: SENDER (code 1): , while compiling: SELECT _id, SENDER, MESSAGE FROM MESSAGES"
And I can't figure out what Is wrong. Need a little help.
MessagesDataSource.java
package com.example.testdatabaseactivity;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class MessagesDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_SENDER, MySQLiteHelper.COLUMN_MESSAGE};
public MessagesDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Message createMessage(String sender, String message) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_MESSAGE, message);
values.put(MySQLiteHelper.COLUMN_SENDER, sender);
long insertId = database.insert(MySQLiteHelper.TABLE_MESSAGES, null,values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,null, null, null);
cursor.moveToFirst();
Message newMessage = cursorToMessage(cursor);
cursor.close();
return newMessage;
}
public List<Message> getAllMessages() {
List<Message> messages = new ArrayList<Message>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Message message = cursorToMessage(cursor);
messages.add(message);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return messages;
}
private Message cursorToMessage(Cursor cursor) {
Message message = new Message();
message.setId(cursor.getLong(0));
message.setMessage(cursor.getString(2));
message.setSender(cursor.getString(1));
return message;
}
}
Message.java
package com.example.testdatabaseactivity;
public class Message {
private long id;
private String message;
private String sender;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return message;
}
}
MySQLiteHelper.java
package com.example.testdatabaseactivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_MESSAGES = "MESSAGES";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_MESSAGE = "MESSAGE";
public static final String COLUMN_SENDER = "SENDER";
private static final String DATABASE_NAME = "message.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_SENDER + "sender not null, "
+ COLUMN_MESSAGE + " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),"Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
onCreate(db);
}
}
TestDatabaseActivity.java
package com.example.testdatabaseactivity;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class TestDatabaseActivity extends ListActivity {
private MessagesDataSource datasource;
public String sender = "Suren";
EditText edittext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittext = (EditText) findViewById(R.id.txt_message);
datasource = new MessagesDataSource(this);
datasource.open();
List<Message> values = datasource.getAllMessages();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(this,android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
String text = edittext.getText().toString();
ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
Message message = null;
if(edittext.length() == 0){
return;
}else{
// save the new message to the database
message = datasource.createMessage(sender, text);
adapter.add(message);
edittext.getText().clear();
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Correct your CREATE Table Query need space between Column Name and Column Type
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_SENDER + " text not null, "
+ COLUMN_MESSAGE + " text not null);";
You Forget to add space over here in your Query COLUMN_SENDER + "sender not null, "
// Database creation sql statement
private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_MESSAGES + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SENDER + " text not null, "
+ COLUMN_MESSAGE + " text not null)";
"sender" is not a type. You need put "text".
And give the appropriate spaces.

Categories