I am having trouble adding another column it just bugs after 5 columns..it says in logs that i have only 5 columns...
check this
Logcat
11-05 03:31:45.455: I/dalvikvm(3845): Turning on JNI app bug workarounds for target SDK version 8...
11-05 03:31:46.395: D/dalvikvm(3845): GC_FOR_ALLOC freed 78K, 8% free 2671K/2884K, paused 80ms, total 82ms
11-05 03:31:46.405: I/dalvikvm-heap(3845): Grow heap (frag case) to 3.341MB for 635812-byte allocation
11-05 03:31:46.475: D/dalvikvm(3845): GC_FOR_ALLOC freed <1K, 7% free 3291K/3508K, paused 67ms, total 67ms
11-05 03:31:46.595: D/Insert:(3845): Inserting ..
11-05 03:31:46.595: D/Reading:(3845): Reading all naps..
11-05 03:31:47.395: D/(3845): HostConnection::get() New Host Connection established 0x2a20c298, tid 3845
11-05 03:32:01.885: D/dalvikvm(3845): GC_FOR_ALLOC freed 220K, 9% free 3584K/3936K, paused 78ms, total 91ms
11-05 03:32:30.646: D/dalvikvm(3895): GC_FOR_ALLOC freed 42K, 7% free 2671K/2848K, paused 90ms, total 93ms
11-05 03:32:30.667: I/dalvikvm-heap(3895): Grow heap (frag case) to 3.341MB for 635812-byte allocation
11-05 03:32:30.796: D/dalvikvm(3895): GC_FOR_ALLOC freed <1K, 6% free 3291K/3472K, paused 100ms, total 100ms
11-05 03:32:30.876: D/Insert:(3895): Inserting ..
11-05 03:32:30.876: D/Reading:(3895): Reading all naps..
11-05 03:32:30.976: E/CursorWindow(3895): Failed to read row 0, column 5 from a CursorWindow which has 11 rows, 5 columns.
11-05 03:32:30.986: D/AndroidRuntime(3895): Shutting down VM
11-05 03:32:30.986: W/dalvikvm(3895): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 03:32:31.016: E/AndroidRuntime(3895): FATAL EXCEPTION: main
11-05 03:32:31.016: E/AndroidRuntime(3895): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.androidsqlite/com.androidhive.androidsqlite.NapDbase}: java.lang.IllegalStateException: Couldn't read row 0, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.os.Looper.loop(Looper.java:137)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 03:32:31.016: E/AndroidRuntime(3895): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 03:32:31.016: E/AndroidRuntime(3895): at java.lang.reflect.Method.invoke(Method.java:525)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 03:32:31.016: E/AndroidRuntime(3895): at dalvik.system.NativeStart.main(Native Method)
11-05 03:32:31.016: E/AndroidRuntime(3895): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.database.CursorWindow.nativeGetString(Native Method)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.database.CursorWindow.getString(CursorWindow.java:434)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.androidhive.androidsqlite.DatabaseHandler.getAllNapChecks(DatabaseHandler.java:110)
11-05 03:32:31.016: E/AndroidRuntime(3895): at com.androidhive.androidsqlite.NapDbase.onCreate(NapDbase.java:75)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.Activity.performCreate(Activity.java:5133)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-05 03:32:31.016: E/AndroidRuntime(3895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-05 03:32:31.016: E/AndroidRuntime(3895): ... 11 more
My Database.
package com.androidhive.androidsqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "NapsManager";
// NapChecks table name
private static final String TABLE_NapS = "Naps";
// NapChecks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_MALL = "mall";
private static final String KEY_LATIT = "latit";
private static final String KEY_LONGIT = "longit";
private static final String KEY_INTER = "inte";
private static final String KEY_CATE = "cate";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NapS_TABLE = "CREATE TABLE " + TABLE_NapS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_MALL + " TEXT," + KEY_LATIT + " TEXT,"
+ KEY_LONGIT + " TEXT," + KEY_INTER + " TEXT,"
+ KEY_CATE + " TEXT" +")";
db.execSQL(CREATE_NapS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NapS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new nap
void addNapCheck(NapCheck nap) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, nap.getName()); // NapCheck Name
values.put(KEY_MALL, nap.getMall()); // NapCheck Phone
values.put(KEY_LATIT, nap.getLatit()); // NapCheck Name
values.put(KEY_LONGIT, nap.getLongit());
values.put(KEY_INTER, nap.getInte());
// Inserting Row
db.insert(TABLE_NapS, null, values);
db.close(); // Closing database connection
}
// Getting single nap
NapCheck getNapCheck(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NapS, new String[] { KEY_ID,
KEY_NAME, KEY_MALL, KEY_LATIT, KEY_LONGIT, KEY_INTER, }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
NapCheck nap = new NapCheck(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3), cursor.getString(4), cursor.getString(5));
// return nap
return nap;
}
// Getting All NapChecks
public List<NapCheck> getAllNapChecks() {
List<NapCheck> NapList = new ArrayList<NapCheck>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NapS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
NapCheck nap = new NapCheck();
nap.setID(Integer.parseInt(cursor.getString(0)));
nap.setName(cursor.getString(1));
nap.setMall(cursor.getString(2));
nap.setLatit(cursor.getString(3));
nap.setLongit(cursor.getString(4));
nap.setLongit(cursor.getString(5));
// Adding nap to list
NapList.add(nap);
} while (cursor.moveToNext());
}
// return nap list
return NapList;
}
// Updating single nap
public int updateNapCheck(NapCheck nap) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, nap.getName());
values.put(KEY_MALL, nap.getMall());
values.put(KEY_LATIT, nap.getLatit());
values.put(KEY_LONGIT, nap.getLongit());
values.put(KEY_INTER, nap.getLongit());
// updating row
return db.update(TABLE_NapS, values, KEY_ID + " = ?",
new String[] { String.valueOf(nap.getID()) });
}
// Deleting single nap
public void deleteNapCheck(NapCheck nap) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NapS, KEY_ID + " = ?",
new String[] { String.valueOf(nap.getID()) });
db.close();
}
// Getting Naps Count
public int getNapChecksCount() {
String countQuery = "SELECT * FROM " + TABLE_NapS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And this is my Getters and Setters
package com.androidhive.androidsqlite;
public class NapCheck {
//private variables
int _id;
String _name;
String _mall;
String latit;
String longit;
String inte;
String cate;
// Empty constructor
public NapCheck(){
}
// constructor
public NapCheck(int id, String name, String _mall,String latit, String longit, String inte){
this._id = id;
this._name = name;
this._mall = _mall;
this.latit = latit;
this.longit = longit;
this.inte = inte;
}
// constructor
public NapCheck(String name, String _mall,String latit, String longit, String inte){
this._name = name;
this._mall = _mall;
this.latit = latit;
this.longit = longit;
this.inte = inte;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getMall(){
return this._mall;
}
// setting phone number
public void setMall(String phone_number){
this._mall = phone_number;
}
public String getLatit(){
return this.latit;
}
// setting phone number
public void setLatit(String latit){
this.latit = latit;
}
public String getLongit(){
return this.longit;
}
// setting phone number
public void setLongit(String longit){
this.longit = longit;
}
public String getInte(){
return this.inte;
}
public void setInte(String inte){
this.inte = inte;
}
public String getCate(){
return this.cate;
}
// setting phone number
public void setCate(String cate){
this.cate = cate;
}
}
I don't know what is wrong everytime i set a column in public List getAllNapChecks() it gets bugged and says i only have five columns i don't know i've been doing this for hours..Thanks in advance..Just tell if you need more
public List<NapCheck> getAllNapChecks() {
List<NapCheck> NapList = new ArrayList<NapCheck>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NapS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
NapCheck nap = new NapCheck();
nap.setID(Integer.parseInt(cursor.getString(0)));
nap.setName(cursor.getString(1));
nap.setMall(cursor.getString(2));
nap.setLatit(cursor.getString(3));
nap.setLongit(cursor.getString(4));
this line is where i get problem most of the time..
nap.setLongit(cursor.getString(5));
// Adding nap to list
NapList.add(nap);
} while (cursor.moveToNext());
}
// return nap list
return NapList;
}
Probably this isn't your first DB-schema, that you created.
You have to increase your DB-version, if you edit your DB-schema. Otherwise neither onUpdate() will not be called.
Try:
private static final int DATABASE_VERSION = 2;
I think the unwanted space and comma after the KEY_INTER(last field) is the problem change that.
Cursor cursor = db.query(TABLE_NapS, new String[] { KEY_ID,
KEY_NAME, KEY_MALL, KEY_LATIT, KEY_LONGIT, KEY_INTER}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
The onCreate (SQLiteDatabase db) method in DatabaseHandler is called only once when the database is accessed for the first time. This means that any changes to the schema will not result in this method being called.
To apply the change in schema, you can take either of two actions:
Uninstall and then install the application in the device/emulator.
Increase the value of DATABASE_VERSION in order to trigger a call to onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion). As per your implementation, this will result in the existing table being dropped and recreated.
Related
I have created a simple Android application which asks for the users information such as name, blood type, contact number, etc., saves it in a database, and displays it in another screen. This is all suppose to happen when the save button is clicked which invokes the saveMe() method. However, when I click the save button, the app does not crash and close instead it gets stuck and then in the logcat I see something like:
08-08 22:41:23.734: D/dalvikvm(365): GC_FOR_MALLOC freed 321K, 50% free 2984K/5959K, external 716K/1038K, paused 18ms
08-08 22:41:23.754: D/dalvikvm(365): GC_FOR_MALLOC freed 322K, 50% free 2984K/5959K, external 716K/1038K, paused 18ms
08-08 22:41:23.784: D/dalvikvm(365): GC_FOR_MALLOC freed 323K, 50% free 2984K/5959K, external 716K/1038K, paused 21ms
08-08 22:41:23.804: D/dalvikvm(365): GC_FOR_MALLOC freed 324K, 50% free 2984K/5959K, external 716K/1038K, paused 19ms
08-08 22:41:23.824: D/dalvikvm(365): GC_FOR_MALLOC freed 324K, 50% free 2984K/5959K, external 716K/1038K, paused 20ms
08-08 22:41:23.844: D/dalvikvm(365): GC_FOR_MALLOC freed 325K, 50% free 2984K/5959K, external 716K/1038K, paused 20ms
08-08 22:41:23.874: D/dalvikvm(365): GC_FOR_MALLOC freed 326K, 50% free 2984K/5959K, external 716K/1038K, paused 25ms
08-08 22:41:23.894: D/dalvikvm(365): GC_FOR_MALLOC freed 327K, 50% free 2984K/5959K, external 716K/1038K, paused 23ms
08-08 22:41:23.934: D/dalvikvm(365): GC_FOR_MALLOC freed 327K, 50% free
These messages keep appearing in log cat. The only way I can stop them is if I close the emulator. Is the app getting stuck in a infinite loop? No data get saved or displayed.
Database Class
package com.example.androidsimpledbapp1;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
/*
* Class for Working with DB
*/
//Update each time DB structure changes e.g. adding new property
private static final int DATABASE_VERSION =1;
//DB Name
private static final String DATABASE_NAME = "deets.db";
//Table name
public static final String TABLE_PRODUCTS = "products";
//DB Columns
public static final String COLUMN_ID = "_Id";
public static final String COLUMN_PERSONNAME = "firstName";
public static final String COLUMN_PERSONBLOOD = "bloodType";
public static final String COLUMN_PERSONCONTACT = "contactName";
public static final String COLUMN_PERSONNUMBER = "phoneNumber";
public static final String COLUMN_PERSONRELATION = "relationship";
//Constructor
/*
* Passing information to super class in SQL
* Context is background information
* name of db
* Database version
*/
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
/*
* What to do first time when you create DB
* Creates the table the very first time
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
* Remember to use Commas as shown below
*/
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+ TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
COLUMN_PERSONNAME + " TEXT, "+
COLUMN_PERSONBLOOD + " TEXT, "+
COLUMN_PERSONCONTACT + " TEXT, "+
COLUMN_PERSONNUMBER + " TEXT, " +
COLUMN_PERSONRELATION + " TEXT " +
");";
//Execute the query
db.execSQL(query);
}
/*
* If ever upgrading DB call this method
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//Delete the current table
db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
//create new table
onCreate(db);
}
//Add new row to the database
public void addProduct(Details details){
//Built in class - set values for different columns
//Makes inserting rows quick and easy
ContentValues values = new ContentValues();
values.put(COLUMN_PERSONNAME, details.get_firstName());
values.put(COLUMN_PERSONBLOOD, details.get_bloodType());
values.put(COLUMN_PERSONCONTACT, details.get_contactName());
values.put(COLUMN_PERSONNUMBER, details.get_phoneNumber());
values.put(COLUMN_PERSONRELATION, details.get_relationship());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
/*
public void deleteProducts(){
SQLiteDatabase = getWritableDatabase();
db.execSQL("DROP TABLE");
How to delete the database...
}
*/
//Take DB and Convert to String
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
}
}
Details Class
package com.example.androidsimpledbapp1;
public class Details {
//primary key
private int _id;
//Properties
private String _firstName;
private String _bloodType;
private String _contactName;
private String _phoneNumber;
private String _relationship;
//Dont Have to Enter Everything each time
public Details(){
}
public Details(String firstName){
this.set_firstName(firstName);
}
//Passing in details
//Setting values from the user
public Details(String firstName, String bloodType,
String contactName, String phoneNumber,
String relationship){
this.set_firstName(firstName);
this.set_bloodType(bloodType);
this.set_contactName(contactName);
this.set_phoneNumber(phoneNumber);
this.set_relationship(relationship);
}
//Retrieve the data
public int get_id() {
return _id;
}
//Setter allows to give property
public void set_id(int _id) {
this._id = _id;
}
public String get_firstName() {
return _firstName;
}
public void set_firstName(String _firstName) {
this._firstName = _firstName;
}
public String get_bloodType() {
return _bloodType;
}
public void set_bloodType(String _bloodType) {
this._bloodType = _bloodType;
}
public String get_contactName() {
return _contactName;
}
public void set_contactName(String _contactName) {
this._contactName = _contactName;
}
public String get_phoneNumber() {
return _phoneNumber;
}
public void set_phoneNumber(String _phoneNumber) {
this._phoneNumber = _phoneNumber;
}
public String get_relationship() {
return _relationship;
}
public void set_relationship(String _relationship) {
this._relationship = _relationship;
}
}
Edit Screen - Where the save button is clicked
public class EditScreen extends Activity {
EditText firstNameInput;
EditText bloodTypeInput;
EditText contacNameInput;
EditText phoneNumberInput;
EditText relationshipInput;
TextView displayName;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_screen);
firstNameInput = (EditText) findViewById(R.id.inputname);
bloodTypeInput = (EditText) findViewById(R.id.inputblood);
contacNameInput = (EditText) findViewById(R.id.inputcontact);
phoneNumberInput = (EditText) findViewById(R.id.inputnum);
relationshipInput = (EditText) findViewById(R.id.inputraltion);
displayName = (TextView) findViewById(R.id.dbname);
dbHandler = new MyDBHandler(this, null, null, 1);
}
/*
* Causing error fix the error
*/
public void saveMe(View v){
Details detail = new Details(firstNameInput.getText().toString(),
bloodTypeInput.getText().toString(),
contacNameInput.getText().toString(),
phoneNumberInput.getText().toString(),
relationshipInput.getText().toString()
);
dbHandler.addProduct(detail);
printDatabase();
}
private void printDatabase() {
//Taking the string
String dbString = dbHandler.databaseToString();
//Display in the textview
displayName.setText(dbString);
}
}
Main Activity
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Changing Activity
public void editBtnPressed(View v){
Intent intent = new Intent(MainActivity.this, EditScreen.class);
startActivity(intent);
}
}
Logcat - Error
08-08 22:41:00.034: D/AndroidRuntime(348): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
08-08 22:41:00.054: D/AndroidRuntime(348): CheckJNI is ON
08-08 22:41:00.273: I/ActivityManager(60): Start proc com.svox.pico for broadcast com.svox.pico/.VoiceDataInstallerReceiver: pid=350 uid=10028 gids={}
08-08 22:41:00.583: I/ActivityThread(350): Pub com.svox.pico.providers.SettingsProvider: com.svox.pico.providers.SettingsProvider
08-08 22:41:00.663: D/GTalkService(185): handlePackageInstalled: re-initialize providers
08-08 22:41:00.663: D/GTalkService(185): [RawStanzaProvidersMgr] ##### searchProvidersFromIntent
08-08 22:41:00.663: D/GTalkService(185): [RawStanzaProvidersMgr] no intent receivers found
08-08 22:41:00.713: D/dalvikvm(335): GC_CONCURRENT freed 211K, 43% free 3575K/6215K, external 716K/1038K, paused 3ms+4ms
08-08 22:41:00.874: D/AndroidRuntime(348): Calling main entry com.android.commands.am.Am
08-08 22:41:00.904: I/ActivityManager(60): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.androidsimpledbapp1/.MainActivity } from pid 348
08-08 22:41:00.974: D/AndroidRuntime(348): Shutting down VM
08-08 22:41:00.984: I/ActivityManager(60): Start proc com.example.androidsimpledbapp1 for activity com.example.androidsimpledbapp1/.MainActivity: pid=365 uid=10045 gids={}
08-08 22:41:00.994: D/dalvikvm(348): GC_CONCURRENT freed 101K, 69% free 318K/1024K, external 0K/0K, paused 1ms+1ms
08-08 22:41:01.004: D/jdwp(348): adbd disconnected
08-08 22:41:01.154: D/dalvikvm(32): GC_EXPLICIT freed 11K, 50% free 2719K/5379K, external 716K/1038K, paused 168ms
08-08 22:41:01.214: D/dalvikvm(32): GC_EXPLICIT freed <1K, 50% free 2719K/5379K, external 716K/1038K, paused 62ms
You're missing c.moveToNext() in your databaseToString() while loop and the loop never terminates.
Trying to retrieve the data from sqLite and show it in Alert Dialog Builder.
But not Showing the data at all. When I click on the View Button nothing happens.
MainActivity.java
package com.example.database;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity{
EditText first,last,age,classc;
Button add,view;
String FirstName;
String LastName;
String Class;
Integer Age;
sqLit myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new sqLit(this);
Link();
addButtonClicked();
viewButtonClicked();
}
public void addButtonClicked()
{
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
xmlToVar();
Integer flag=myDB.insertValue(FirstName, LastName, Class, Age);
if (flag==1)
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Record Added" , Toast.LENGTH_LONG);
toast.show();
}
else
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Error Occured" , Toast.LENGTH_LONG);
toast.show();
}
}
});
}
public void viewButtonClicked()
{
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Cursor res = myDB.getData();
if (res.getCount()==0)
{
showMessage("Error" , "No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext())
{
buffer.append("ID : " + res.getString(0) + "\n");
buffer.append("FirstName : " + res.getString(1) + "\n");
buffer.append("LastName : " + res.getString(2) + "\n");
buffer.append("Class : " + res.getString(3) + "\n");
buffer.append("Age : " + res.getString(4) + "\n");
showMessage("Here is your Data",buffer.toString() );
}
}
});
}
public void showMessage(String title, String message)
{
AlertDialog.Builder Builder = new AlertDialog.Builder(this);
Builder.setCancelable(true);
Builder.setTitle(title);
Builder.setMessage(message);
}
public void Link()
{
first=(EditText) findViewById(R.id.editFirst);
last=(EditText) findViewById(R.id.editLast);
classc=(EditText) findViewById(R.id.editClass);
age=(EditText) findViewById(R.id.editAge);
add=(Button) findViewById(R.id.Add);
view=(Button) findViewById(R.id.ViewAll);
}
public void xmlToVar()
{
FirstName = first.getText().toString();
LastName = last.getText().toString();
Class = classc.getText().toString();
Age = Integer.parseInt(age.getText().toString());
}
}
sqLit.java
package com.example.database;
import org.w3c.dom.Text;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.text.Editable;
public class sqLit extends SQLiteOpenHelper
{
public static final String DB_NAME="student12.db";
public static final String TABLE_NAME="class1";
public static final String COL_1="ROLLNO";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="Class";
public static final String COL_5="Age";
public sqLit(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exist" + TABLE_NAME );
onCreate(db);
}
public Integer insertValue(String firstName, String lastName, String Class, Integer Age)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentV = new ContentValues();
contentV.put(COL_2, firstName);
contentV.put(COL_3, lastName);
contentV.put(COL_4, Class);
contentV.put(COL_5, Age);
long isInserted = db.insert(TABLE_NAME, null, contentV);
if (isInserted == -1){
return 0;
}
else
{
return 1;
}
}
public Cursor getData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * From "+TABLE_NAME, null);
return res;
}
}
LogCat
06-11 22:02:40.728: D/dalvikvm(1576): Not late-enabling CheckJNI (already on)
06-11 22:02:40.737: E/Trace(1576): error opening trace file: No such file or directory (2)
06-11 22:02:40.817: D/gralloc_goldfish(1576): Emulator without GPU emulation detected.
06-11 22:05:14.779: D/dalvikvm(1576): GC_CONCURRENT freed 197K, 5% free 6176K/6471K, paused 15ms+0ms, total 19ms
06-11 22:08:27.242: E/Trace(2066): error opening trace file: No such file or directory (2)
06-11 22:08:27.322: D/gralloc_goldfish(2066): Emulator without GPU emulation detected.
06-11 22:08:31.472: D/dalvikvm(2066): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 17ms+1ms, total 19ms
06-11 22:10:36.644: D/dalvikvm(2290): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 16ms+0ms, total 19ms
06-11 22:10:52.355: D/AndroidRuntime(2290): Shutting down VM
06-11 22:10:52.355: W/dalvikvm(2290): threadid=1: thread exiting with uncaught exception (group=0xb3f1c288)
06-11 22:10:52.355: E/AndroidRuntime(2290): FATAL EXCEPTION: main
06-11 22:10:52.355: E/AndroidRuntime(2290): java.lang.NumberFormatException: Invalid int: ""
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.invalidInt(Integer.java:138)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.parseInt(Integer.java:359)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.parseInt(Integer.java:332)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.example.database.MainActivity.xmlToVar(MainActivity.java:115)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.example.database.MainActivity$1.onClick(MainActivity.java:46)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.view.View.performClick(View.java:4084)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.view.View$PerformClick.run(View.java:16966)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Handler.handleCallback(Handler.java:615)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Looper.loop(Looper.java:137)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.app.ActivityThread.main(ActivityThread.java:4745)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.reflect.Method.invoke(Method.java:511)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-11 22:10:52.355: E/AndroidRuntime(2290): at dalvik.system.NativeStart.main(Native Method)
06-11 22:12:22.676: D/dalvikvm(2455): GC_CONCURRENT freed 201K, 5% free 6172K/6471K, paused 17ms+0ms, total 19ms
06-11 22:14:01.238: D/dalvikvm(2652): Not late-enabling CheckJNI (already on)
06-11 22:14:01.248: E/Trace(2652): error opening trace file: No such file or directory (2)
06-11 22:14:01.338: D/gralloc_goldfish(2652): Emulator without GPU emulation detected.
The Button isn’t working at all.
The below exception from xmlToVar method is the problem, you are calling this in addButtonClicked method
java.lang.NumberFormatException: Invalid int: ""
If the value in Age field is not entered then this error will happen if you make empty check before calling
Age = Integer.parseInt(age.getText().toString());
should solve the issue
Validate input before you use parseInt in xmlToVar():
String ageStr = age.getText().toString();
if (ageStr != "")
r.age = Integer.parseInt(ageStr);
You can also initialize Integer age, if there can be a default value.
You need to provide information about the following :
i) Did you try to debug ?
ii) If yes, does the cursor get any data ?
Now a different approach to the problem :
Create class of data [makes it easier to handle, i.e store and fetch from database]
example :
Class :
public class NoticeInformation {
private String NoticeType, NoticeHeader, NoticeLink;
private int Important, NoticeId, Read;
public NoticeInformation(int NoticeId,
String NoticeType,
String NoticeHeader,
String NoticeLink,
int Important,
int Read){
this.NoticeId = NoticeId;
this.NoticeType = NoticeType;
this.NoticeHeader = NoticeHeader;
this.NoticeLink = NoticeLink;
this.Important = Important;
this.Read = Read;
}
public int getNoticeId() {
return NoticeId;
}
public void setNoticeId(int noticeId) {
NoticeId = noticeId;
}
public String getNoticeType() {
return NoticeType;
}
public void setNoticeType(String noticeType) {
NoticeType = noticeType;
}
public String getNoticeHeader() {
return NoticeHeader;
}
public void setNoticeHeader(String noticeHeader) {
NoticeHeader = noticeHeader;
}
public String getNoticeLink() {
return NoticeLink;
}
public void setNoticeLink(String noticeLink) {
NoticeLink = noticeLink;
}
public int getImportant() {
return Important;
}
public void setImportant(int important) {
Important = important;
}
public int getRead() {
return Read;
}
public void setRead(int read) {
Read = read;
}
}
Database Read :
public List<NoticeInformation> getScheduleNotice(){
SQLiteDatabase db = this.getReadableDatabase();
List<NoticeInformation> res = new ArrayList<>();
String Query = "SELECT * FROM " + TABLE_NAME1 + " WHERE NoticeType = 'Schedule';";
Cursor cursor = db.rawQuery(Query, null);
if (cursor.moveToFirst()){
cursor.moveToFirst();
do
{
NoticeInformation obj = new NoticeInformation(cursor.getInt(0), cursor.getString(1),
cursor.getString(2), cursor.getString(3), cursor.getInt(5),
cursor.getInt(4));
res.add(obj);
}while(cursor.moveToNext());
return res;
}
return null;
}
Instead of handling cursor in the application end, just have the data in a list. It is easier to handle [in my humble opinion].
Try this approach and let me know the result.
I work with SQLite database in my Android application.I want only one column retrieved in spinner. When I run the application ,the application is crashing. And my log cat shows:
Bad request for field slot 0,1. numRows = 1, numColumns = 1
Below are the codes for retrieving data from database and put it into spinner (NewleadActivity.class).
This is my Adapter class
public class DbHelper extends SQLiteOpenHelper
{
// Database Version
#SuppressWarnings("unused")
private static final int DATABASE_VERSION = 1;
// Database Name
static String DATABASE_NAME="define_products_database";
// Labels table name
public static final String TABLE_DEFINE_PRODUCT_NAME="define_products";
// Labels Table Columns names
public static final String KEY_PRODUCTS_NAME="product_name";
public static final String KEY_PRODUCTS_DETAILS="products_details";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_DEFINE_PRODUCT_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_PRODUCTS_NAME+" TEXT, "+KEY_PRODUCTS_DETAILS+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_DEFINE_PRODUCT_NAME);
onCreate(db);
}
/**
* Getting all labels
* returns list of labels
* */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = " SELECT " + KEY_PRODUCTS_NAME + " FROM "+ TABLE_DEFINE_PRODUCT_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
This is the Activity code which is included spiner
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.new_lead_activity5);
spinner_Products=(Spinner)findViewById(R.id.products_Spinner);
loadSpinnerData();
}
private void loadSpinnerData() {
// database handler
DbHelper db = new DbHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_Products.setAdapter(dataAdapter);
}
}
This is my Log cat.
11-27 11:28:28.548: E/AndroidRuntime(2150): FATAL EXCEPTION: main
11-27 11:28:28.548: E/AndroidRuntime(2150): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lead_management_project/com.lead_management_project.New_Lead_Activity5}: java.lang.IllegalStateException: get field slot from row 0 col 1 failed
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.os.Handler.dispatchMessage(Handler.java:99)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.os.Looper.loop(Looper.java:123)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-27 11:28:28.548: E/AndroidRuntime(2150): at java.lang.reflect.Method.invokeNative(Native Method)
11-27 11:28:28.548: E/AndroidRuntime(2150): at java.lang.reflect.Method.invoke(Method.java:507)
11-27 11:28:28.548: E/AndroidRuntime(2150): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-27 11:28:28.548: E/AndroidRuntime(2150): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-27 11:28:28.548: E/AndroidRuntime(2150): at dalvik.system.NativeStart.main(Native Method)
11-27 11:28:28.548: E/AndroidRuntime(2150): Caused by: java.lang.IllegalStateException: get field slot from row 0 col 1 failed
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.database.CursorWindow.getString_native(Native Method)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.database.CursorWindow.getString(CursorWindow.java:329)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
11-27 11:28:28.548: E/AndroidRuntime(2150): at com.db_mgmt.DbHelper.getAllLabels(DbHelper.java:65)
11-27 11:28:28.548: E/AndroidRuntime(2150): at com.lead_management_project.New_Lead_Activity5.loadSpinnerData(New_Lead_Activity5.java:123)
11-27 11:28:28.548: E/AndroidRuntime(2150): at com.lead_management_project.New_Lead_Activity5.onCreate(New_Lead_Activity5.java:80)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-27 11:28:28.548: E/AndroidRuntime(2150): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
11-27 11:28:28.548: E/AndroidRuntime(2150): ... 11 more
Man, you are only quering single column in your statement and requesting for second, just use below method, I only changed Index from 1 to Zero.
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = " SELECT " + KEY_PRODUCTS_NAME + " FROM "+ TABLE_DEFINE_PRODUCT_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
I am getting error in my code which is not understandable.. please help me find out what issue is it.
i have database class and main activity.. it shows in log but when it comes to appear at my emulator's screen it gives me error.
my database class:
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
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;
public class Database extends SQLiteOpenHelper {
//database name & version number
private static final String db_name = "nearby_places";
private static final int db_version = 1;
//tables
private static final String table_placetypes = "placetypes";
private static final String table_places = "table_places";
//column names
private static final String type_id = "type_id";
private static final String type_name = "type_name";
private static final String place_id = "place_id";
private static final String place_name = "place_name";
private static final String place_address = "place_address";
private static final String place_contact = "place_contact";
public Database(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
// create table queries
String create_table_placetypes = "CREATE TABLE IF NOT EXISTS " + table_placetypes + "("
+ type_id + " INTEGER PRIMARY KEY NOT NULL," + type_name + " TEXT" + ")";
String create_table_places = "CREATE TABLE IF NOT EXISTS table_places (place_id INTEGER PRIMARY KEY NOT NULL, place_name TEXT, place_address TEXT, place_contact TEXT, type_id INTEGER, FOREIGN KEY (type_id) REFERENCES table_placetypes(type_id))";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(create_table_placetypes);
Log.d("creating", "placetypes created");
db.execSQL(create_table_places);
Log.d("creating", "places created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + table_placetypes);
db.execSQL("DROP TABLE IF EXISTS " + table_places);
onCreate(db);
}
// add placetypes
void addplacetypes (placetypes pt) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(type_name, pt.getTypename());
db.insert(table_placetypes, null, values);
db.close();
}
// Getting single placetypes
placetypes getPlacetypes(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_placetypes, new String[] {type_id,
type_name }, type_id + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
placetypes pt = new placetypes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return pt;
}
// Getting All placetypes
public List<placetypes> getAllPlacetypes() {
List<placetypes> placetypesList = new ArrayList<placetypes>();
// Select All Query
String selectQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
placetypes pt = new placetypes();
pt.setTypeid(Integer.parseInt(cursor.getString(0)));
pt.setTypename(cursor.getString(1));
//String name = cursor.getString(1);
//MainActivity.ArrayofName.add(name);
// Adding contact to list
placetypesList.add(pt);
} while (cursor.moveToNext());
}
// return placetype list
return placetypesList;
}
// Getting placetypes Count
public int getPlacetypesCount() {
String countQuery = "SELECT * FROM " + table_placetypes;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public void addplaces(places p) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(place_name, p.getPlace_name());
values.put(place_address, p.getPlace_address());
values.put(place_contact, p.getPlace_contact());
values.put(type_id, p.getT_id());
Log.d("Type ID", String.valueOf(p.getT_id()));
db.insert(table_places, null, values);
db.close();
}
places getPlaces(int pid) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(table_places, new String[] {place_id, place_name, place_address, place_contact,type_id}, place_id + "=?", new String[] { String.valueOf(pid) } , null, null, null, null);
if(cursor != null)
cursor.moveToFirst();
places p = new places(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)
);
cursor.close();
return p;
}
public List<places> getAllPlaces(String typeName) {
List<places> placeList = new ArrayList<places>();
//String selectQuery = "SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id ";
//String selectQuery = "SELECT * FROM table_places WHERE table_places.type_id="+Integer.toString(typeid);
String selectQuery ="SELECT * FROM table_places WHERE placetypes.place_name="+typeName+" INNER JOIN placetypes ON placetypes.type_id=table_places.type_id";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst() )
{
do{
places p = new places();
/*p.setT_id(cursor.getColumnIndex(type_id));
p.setPlace_id(cursor.getColumnIndex(place_id));
p.setPlace_name(cursor.getColumnIndex(place_name));
*/
p.setT_id(cursor.getInt(0));
p.setPlace_id(cursor.getInt(1));
p.setPlace_name(cursor.getString(2));
p.setPlace_address(cursor.getString(3));
p.setPlace_contact(cursor.getString(4));
/*String t_id = cursor.getString(4);
String p_name = cursor.getString(2);
String p_address = cursor.getString(3);
String p_contact = cursor.getString(1);*/
placeList.add(p);
}while(cursor.moveToNext());
}
cursor.close();
return placeList;
}
public int getPlaceCount () {
String selectQuery = "SELECT * FROM " +table_places;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(create_table_places, null);
cursor.close();
return cursor.getCount();
}
}
MainActivity
package com.example.nearby_places;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
public static final String PLACETYPE = "com.example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database db = new Database(this);
if(db.getAllPlacetypes().isEmpty())
{
/**
* CRUD Operations
* */
// Inserting Places
Log.d("Insert: ", "Inserting ..");
db.addplacetypes(new placetypes("RESTURAUNTS"));
db.addplacetypes(new placetypes("MALLS"));
db.addplacetypes(new placetypes("GAS STATIONS"));
db.addplacetypes(new placetypes("HOTELS"));
db.addplacetypes(new placetypes("MOTELS"));
}
// Reading all Places
Log.d("Reading: ", "Reading all placetypes..");
if(ArrayofName.isEmpty())
{
List<placetypes> placetypes = db.getAllPlacetypes();
for (placetypes pt : placetypes)
{
String log = "Id: "+pt.getTypeid()+" ,Name: " + pt.getTypename();
// Writing Places to log
Log.d("Name: ", log);
System.out.println(log);
ArrayofName.add(pt.getTypename());
}
}
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String type = ((TextView) v).getText().toString();
Toast.makeText(getApplicationContext(), type, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
i.putExtra(PLACETYPE, type);
startActivity(i);
/*Cursor cursor = (Cursor) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "id: " +id+ "position: " +position+ "row id: " +(cursor.getColumnIndex("" +
"")), Toast.LENGTH_LONG).show();
*/
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
}
);
}
}
Logcat
10-11 17:21:51.871: D/Reading:(4932): Reading all placetypes..
10-11 17:21:51.871: D/Name:(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: I/System.out(4932): Id: 1 ,Name: RESTURAUNTS
10-11 17:21:51.875: D/Name:(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: I/System.out(4932): Id: 2 ,Name: MALLS
10-11 17:21:51.875: D/Name:(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: I/System.out(4932): Id: 3 ,Name: GAS STATIONS
10-11 17:21:51.875: D/Name:(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 4 ,Name: HOTELS
10-11 17:21:51.875: D/Name:(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.875: I/System.out(4932): Id: 5 ,Name: MOTELS
10-11 17:21:51.887: D/AndroidRuntime(4932): Shutting down VM
10-11 17:21:51.887: W/dalvikvm(4932): threadid=1: thread exiting with uncaught exception (group=0x41c77300)
10-11 17:21:51.894: E/AndroidRuntime(4932): FATAL EXCEPTION: main
10-11 17:21:51.894: E/AndroidRuntime(4932): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nearby_places/com.example.nearby_places.MainActivity}: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.os.Looper.loop(Looper.java:137)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): at java.lang.reflect.Method.invoke(Method.java:511)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-11 17:21:51.894: E/AndroidRuntime(4932): at dalvik.system.NativeStart.main(Native Method)
10-11 17:21:51.894: E/AndroidRuntime(4932): Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Activity.performCreate(Activity.java:5008)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-11 17:21:51.894: E/AndroidRuntime(4932): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-11 17:21:51.894: E/AndroidRuntime(4932): ... 11 more
10-11 17:21:53.695: I/Process(4932): Sending signal. PID: 4932 SIG: 9
Your call to getAdapter is returning null because you're calling it before setAdapter, try this instead :
listView.setAdapter(adapter);
int pos = listView.getAdapter().getCount() -1;
listView.getAdapter().getItemId(pos);
If you have a NULLPOINTER Exception please have a deep look at your LogCat. Especial at the Line where it says Caused by.
Learn how to read and use your LogCat, and try to find the Line where it mentions your class/package name and analyse this line.
Caused by: java.lang.NullPointerException
10-11 17:21:51.894: E/AndroidRuntime(4932): at com.example.nearby_places.MainActivity.onCreate(MainActivity.java:62)
The problem is in
List<placetypes> placetypes = db.getAllPlacetypes();
The query you are using is wrong. It should be
`SELECT * FROM table_places INNER JOIN placetypes ON placetypes.type_id=table_places.type_id WHERE placetypes.place_name="+typeName+`"
01-25 23:51:14.507: WARN/System.err(616): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2
I have an android application that would use an SQLite database. But when it gets to the select statement it force closes. I have a class file that I use for doing this :
package com.thesis.menubook;
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 java.util.ArrayList;
import java.util.List;
public class DBConnect {
int id = 0;
public static final String KEY_ROWID = "_id";
public static final String KEY_IP = "saved_ip_address";
private static final String TAG = "DBConnect";
private static final String DATABASE_NAME = "MenuBook";
private static final String DATABASE_TABLE_1 = "ipaddress";
//private static final String DATABASE_TABLE_2 = "menudb";
//private static final String DATABASE_TABLE_3 = "recipelist";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_TABLE_1 =
"CREATE TABLE ipaddress (_id integer primary key autoincrement, " +
"saved_ip_address text not null " +
"); ";
private static final String DATABASE_CREATE_TABLE_2 =
"CREATE TABLE menudb (menu_ID varchar primary key not null, " +
"menu_name longtext, " +
"menu_price double null default, " +
"menu_description longtext, " +
"menu_category text, " +
"menu_status text " +
"); ";
private static final String DATABASE_CREATE_TABLE_3 =
"CREATE TABLE recipelist (recipe_ID integer primary key not null autoincrement, " +
"menu_ID varchar null default, " +
"stock_ID varchar null default, " +
"recipe_quantity double null defualt " +
");" ;
private final Context context;
private static DatabaseHelper DBHelper;
private static SQLiteDatabase db;
public DBConnect(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE_TABLE_1);
db.execSQL(DATABASE_CREATE_TABLE_2);
db.execSQL(DATABASE_CREATE_TABLE_3);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS ipaddress");
db.execSQL("DROP TABLE IF EXISTS menudb");
db.execSQL("DROP TABLE IF EXISTS recipelist");
onCreate(db);
}
}
//---opens the database---
public DBConnect open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertIPAddress(String ipaddress)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_IP, ipaddress);
return db.insert(DATABASE_TABLE_1, null, initialValues);
}
public String getIP()
{
String retrievedIP;
String query = "SELECT saved_ip_address FROM ipaddress WHERE _id = (SELECT MAX(_id) FROM ipaddress)";
Cursor cursor = db.rawQuery(query, null);
retrievedIP= cursor.getString(cursor.getColumnIndex("saved_ip_address"));
cursor.close();
return retrievedIP;
}
public List<ColumnValue[]> select(final String query)
{
List<ColumnValue[]> result = null;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst())
{
result = new ArrayList<ColumnValue[]>();
do
{
int columns = cursor.getColumnCount();
ColumnValue[] cvarray = new ColumnValue[columns];
for (int i=0; i<columns; i++)
{
String key = cursor.getColumnName(i);
String value = cursor.getString(i);
ColumnValue cv = new ColumnValue(key, value);
cvarray[i] = cv;
}
result.add(cvarray);
}
while (cursor.moveToNext());
}
cursor.close();
return result;
}
public class ColumnValue
{
public String column, value;
public ColumnValue(String c, String v)
{
column = c; value = v;
}
}
}
I think it is on the getID() clause but I can't see anything wrong with it nor my SELECT statetment. What I am trying to do here is to get the value of the saved_ip_address which is at the very bottom of the ipaddress table.
Here is my LogCat where the start of error is bolded out.
Thank You
01-25 23:51:14.507: WARN/System.err(616): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2
01-25 23:51:14.568: WARN/System.err(616): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:421)
01-25 23:51:14.568: WARN/System.err(616): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:117)
01-25 23:51:14.578: WARN/System.err(616): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:31)
01-25 23:51:14.590: WARN/System.err(616): at com.thesis.menubook.DBConnect.getIP(DBConnect.java:113)
01-25 23:51:14.590: WARN/System.err(616): at com.thesis.menubook.ChooseTable$GetTableDetails$1.run(ChooseTable.java:103)
01-25 23:51:14.622: WARN/System.err(616): at android.os.Handler.handleCallback(Handler.java:587)
01-25 23:51:14.622: WARN/System.err(616): at android.os.Handler.dispatchMessage(Handler.java:92)
01-25 23:51:14.622: WARN/System.err(616): at android.os.Looper.loop(Looper.java:132)
01-25 23:51:14.648: WARN/System.err(616): at android.app.ActivityThread.main(ActivityThread.java:4025)
01-25 23:51:14.688: WARN/System.err(616): at java.lang.reflect.Method.invokeNative(Native Method)
01-25 23:51:14.688: WARN/System.err(616): at java.lang.reflect.Method.invoke(Method.java:491)
01-25 23:51:14.688: WARN/System.err(616): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
01-25 23:51:14.688: WARN/System.err(616): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
01-25 23:51:14.688: WARN/System.err(616): at dalvik.system.NativeStart.main(Native Method)
01-25 23:51:14.998: DEBUG/AndroidRuntime(616): Shutting down VM
01-25 23:51:15.008: WARN/dalvikvm(616): threadid=1: thread exiting with uncaught exception (group=0x40014760)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): FATAL EXCEPTION: main
01-25 23:51:15.138: ERROR/AndroidRuntime(616): java.lang.IllegalArgumentException: Host name may not be null
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at com.thesis.menubook.JSONParser.makeHttpRequest(JSONParser.java:62)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at com.thesis.menubook.ChooseTable$GetTableDetails$1.run(ChooseTable.java:119)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at android.os.Handler.handleCallback(Handler.java:587)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at android.os.Handler.dispatchMessage(Handler.java:92)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at android.os.Looper.loop(Looper.java:132)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at android.app.ActivityThread.main(ActivityThread.java:4025)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at java.lang.reflect.Method.invokeNative(Native Method)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at java.lang.reflect.Method.invoke(Method.java:491)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
01-25 23:51:15.138: ERROR/AndroidRuntime(616): at dalvik.system.NativeStart.main(Native Method)
01-25 23:51:15.328: WARN/ActivityManager(83): Force finishing activity com.thesis.menubook/.ChooseTable
01-25 23:51:15.958: WARN/ActivityManager(83): Activity pause timeout for ActivityRecord{408b4228 com.thesis.menubook/.ChooseTable}
01-25 23:51:20.048: INFO/Process(616): Sending signal. PID: 616 SIG: 9
01-25 23:51:21.068: INFO/ActivityManager(83): Process com.thesis.menubook (pid 616) has died.
01-25 23:51:21.089: ERROR/InputDispatcher(83): channel '408408d0 com.thesis.menubook/com.thesis.menubook.IPAddress (server)' ~ Consumer closed input channel or an error occurred. events=0x8
01-25 23:51:21.098: ERROR/InputDispatcher(83): channel '408408d0 com.thesis.menubook/com.thesis.menubook.IPAddress (server)' ~ Channel is unrecoverably broken and will be disposed!
01-25 23:51:21.768: INFO/WindowManager(83): WIN DEATH: Window{408408d0 com.thesis.menubook/com.thesis.menubook.IPAddress paused=false}
01-25 23:51:22.108: INFO/WindowManager(83): WIN DEATH: Window{407b66d8 com.thesis.menubook/com.thesis.menubook.ChooseTable paused=false}
01-25 23:51:22.246: INFO/WindowManager(83): WIN DEATH: Window{4097d668 com.thesis.menubook/com.thesis.menubook.ChooseTable paused=false}
01-25 23:51:22.358: INFO/WindowManager(83): WINDOW DIED Window{408408d0 com.thesis.menubook/com.thesis.menubook.IPAddress paused=false}
01-25 23:51:22.449: ERROR/InputDispatcher(83): Received spurious receive callback for unknown input channel. fd=188, events=0x8
01-25 23:51:22.449: ERROR/InputDispatcher(83): Received spurious receive callback for unknown input channel. fd=190, events=0x8
01-25 23:51:23.468: DEBUG/dalvikvm(147): GC_EXPLICIT freed <1K, 4% free 12942K/13383K, paused 285ms+19ms
01-25 23:51:23.858: WARN/InputManagerService(83): Got RemoteException sending setActive(false) notification to pid 616 uid 10004
01-25 23:52:15.278: DEBUG/SntpClient(83): request time failed: java.net.SocketException: Address family not supported by protocol
01-25 23:57:15.589: DEBUG/SntpClient(83): request time failed: java.net.SocketException: Address family not supported by protocol
after getting a Cursor object you need to advance to the first row...
cursor.moveToFirst();
prior to fetching from the cursor. also you'll need to check if indeed there are any rows present in the cursor.