I am getting error in writing query get error at DESC in function getfood.Here is my exception.
Exception:
beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.caloriescounter.admin.caloriescounter, PID: 2759
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.app.caloriescounter.admin.caloriescounter/com.app.caloriesc
ounter.admin.caloriescounter.Main2Activity}:
java.lang.IllegalArgumentException: **invalid LIMIT clauses: DESC**
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at
android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: invalid LIMIT clauses: DESC
at
android.database.sqlite.SQLiteQueryBuilder.buildQueryString(SQLiteQueryBuilde
r.java:209)
at
android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1160)
at
android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at
android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1240)
at
data.Databasehandler.getfood(Databasehandler.java:86)
at
com.app.caloriescounter.admin.caloriescounter.Main2Activity.refreshdata(Main2Activity.java:38)
at com.app.caloriescounter.admin.caloriescounter.Main2Activity.onCreate(Main2Activity.java:32)
at android.app.Activity.performCreate(Activity.java:6237)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-
wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at
android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at
android.app.ActivityThread.main(ActivityThread.java:5417)
this is my Source Code: of Databasehandler class.
package data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import model.Food;
/**
* Created by Admin on 9/10/2016.
*/
public class Databasehandler extends SQLiteOpenHelper {
private static final String LOGCAT = null;
private final ArrayList<Food> foodArrayList=new ArrayList<>();
public Databasehandler(Context context) {
super(context,Constsnts.databasename,null,Constsnts.databaseversion);
Log.d(LOGCAT,"Database Created");
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String Crete_Table="CREATE TABLE "+ Constsnts.food_table+" ( " +
Constsnts.KeyId +"INTEGER PRIMARY KEY, " + Constsnts.food_name +"TEXT, "
+Constsnts.foodcalories +"INT , "+Constsnts.datename +"LONG );";
sqLiteDatabase.execSQL(Crete_Table);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+Constsnts.food_table);
//new one
onCreate(sqLiteDatabase);
}
//item all
public int getTotalitem(){
int totalitem=0;
String query=" SELECT * FROM "+Constsnts.food_table;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery(query,null);
totalitem=cursor.getCount();
cursor.close();
return totalitem;
}
public int Caloriesall(){
int calories=0;
String query="SELECT SUM ( "+Constsnts.foodcalories +")"+"FROM
"+Constsnts.food_table;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery(query,null);
if(cursor.moveToNext()){
calories=cursor.getInt(0);
}
cursor.close();
db.close();
return calories;
}
//deletefood
public void deletefood(int id){
SQLiteDatabase db=this.getWritableDatabase();
db.delete(Constsnts.food_table,Constsnts.KeyId+" =? ",new String[]
{String.valueOf(id)});
db.close();
}
//add food
public void addfood(Food food){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Constsnts.food_name,food.getFoodname());
values.put(Constsnts.foodcalories,food.getCaleries());
values.put(Constsnts.datename,System.currentTimeMillis());
db.insert(Constsnts.food_table,null,values);
Log.v("Added food item","yess");
db.close();
}
//get all food
public ArrayList<Food> getfood(){
foodArrayList.clear();
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(Constsnts.food_table,new String[]
{Constsnts.KeyId,Constsnts.databasename,
Constsnts.foodcalories,Constsnts.datename},null,null,null,null,Constsnts.datename," DESC ");
if(cursor.moveToFirst()){
do {
Food food=new Food();
food.setFoodname(cursor.getString(cursor.getColumnIndex(Constsnts.food_name)));
food.setCaleries(cursor.getInt(cursor.getColumnIndex(Constsnts.foodcalories)));
food.setFoodid(cursor.getInt(cursor.getColumnIndex(Constsnts.KeyId)));
DateFormat dateFormat=DateFormat.getDateInstance();
String data=dateFormat.format(new
Date(cursor.getLong(cursor.getColumnIndex(Constsnts.datename))).getTime());
food.setRecorddate(data);
foodArrayList.add(food);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return foodArrayList;
}
}
Thanks in advance.
Cursor cursor=db.query(...,Constsnts.datename," DESC ");
The DESC must be part of the ORDER BY clause. You have put it into the next parameter, which makes it end up in the LIMIT clause.
You have to put the column name and the DESC into the same parameter:
Cursor cursor=db.query(...,Constsnts.datename+" DESC");
Related
i want to get two column from my SQLite DB and return it like Arraylist<myObjectModel> but i faced this error
05-12 03:31:37.763 15166-15166/com.example.abdullah.newstroynory E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abdullah.newstroynory, PID: 15166
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abdullah.newstroynory/com.example.abdullah.newstroynory.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.abdullah.newstroynory.SQLForMyStroies.getTitleAndImage(SQLForMyStroies.java:58)
at com.example.abdullah.newstroynory.MainActivity.onCreate(MainActivity.java:75)
My error
com.example.abdullah.newstroynory.SQLForMyStroies.getTitleAndImage(SQLForMyStroies.java:58)
start in this line in my SQlite class
forDoing.setTitle(cursor.getString(cursor.getColumnIndex("story_title")));
My SQLiteOpenHelper class
public class SQLForMyStroies extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "newStoryNory5";
public SQLForMyStroies(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE stories (story_id INTEGER PRIMARY KEY AUTOINCREMENT,story_title VARCHAR,story_image VARCHAR,story_body VARCHAR,story_audio VARCHAR )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS stories");
onCreate(db);
}
public boolean CreateNewStory( String t, String i, String b){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("story_title" , t);
contentValues.put("story_image" , i);
contentValues.put("story_body" , b);
// contentValues.put("story_audio" , a);
db.insert("stories",null,contentValues);
return true;
}
public ArrayList<StoryModel> getTitleAndImage(){
ArrayList<StoryModel> myData = new ArrayList <> ();
SQLiteDatabase db= this.getReadableDatabase();
Cursor cursor =db.rawQuery("SELECT * FROM stories ",null);
cursor.moveToFirst();
do {
StoryModel forDoing=new StoryModel();
forDoing.setTitle(cursor.getString(cursor.getColumnIndex("story_title")));
forDoing.setImage(cursor.getString(cursor.getColumnIndex("story_image")));
myData.add(forDoing);
}while (cursor.moveToNext());
cursor.close();
db.close();
return(myData);
}
My MainActivity class
ArrayList<StoryModel> TitleAndImage =mySQL.getTitleAndImage();
for (StoryModel storyModel : TitleAndImage) {
Log.d("story_title", storyModel.getTitle());
Log.d("story_image", storyModel.getImage());
}
i think it's logical error in java code!
can you correct me please!
i'm new in android and not familiar in java
the Error was because my DB SQlite empty because every time i run the App it's make a new DB for me ...
solution
so I deleted all my DB SQLite and I put condition,
my condition is " if there is data in my DB SQLite don't take data from internt"
My MainActivity
if(mySQL.checktitle (storyObject.getTitle().toString())) {
Log.d("--------------------", "data is exist ");
break;
}
My SQLiteOpenHelper class
public boolean checktitle ( String title){
SQLiteDatabase db= this.getWritableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM stories where story_title='"+title+"'" ,null);
if(cur.getCount()>0)
return true;
return false;
}
I am trying to load data (specific column from a table) into a spinner.
I created a class DatabaseHelper where I define the database/tables and where the data for the spinner are selected.
My class Allgemein is the class where I save the spinner data among other things.
I created a class Unterkunft where I implemented a spinner. When I click on this spinner the data from class Allgemein should be shown.
Everytime I save data in Allgemein and then try to open the Unterkunft Activity my app crashes.
I added the code from DatabaseHelper and Unterkunft and the Logcat.
I hope someone could help me with this!!
Thank you
Class DatabaseHelper
package com.group6.TakeOff;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by STzavelas on 28.06.17.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "TakeOff.db";
//Table Names
public static final String TABLE_PROJEKT = "create_project";
public static final String TABLE_UNTERKUNFT = "unterkunft";
public static final String TABLE_AUTO = "auto";
public static final String TABLE_FLUGZEUG = "flugzeug";
public static final String TABLE_TAXI = "taxi";
public static final String TABLE_BAHN = "bahn";
//Common column names
public static final String KEY_ID = "ID";
public static final String KEY_PROJECT = "PROJEKT";
//create project column names
public static final String KEY_DATE_FROM= "DATE_FROM";
public static final String KEY_DATE_TO= "DATE_TO";
public static final String KEY_NAME = "NACHNAME";
public static final String KEY_VORNAME = "VORNAME";
public static final String KEY_KOSTENST = "KOSTENSTELLE";
//Expenses column names
public static final String KEY_ENTFERNUNG= "ENTFERNUNG";
public static final String KEY_PRICE= "PRICE";
public static final String KEY_MWST= "MWST";
public static final String KEY_RECHNUNG_IMG= "RECHNUNG_IMG";
//Übersicht column names
//TABLE CREATE STATEMENTS
private static final String CREATE_TABLE_PROJEKT = "create table " + TABLE_PROJEKT + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"PROJEKT TEXT, " +
"DATE_FROM TEXT, " +
"DATE_TO TEXT, " +
"NACHNAME TEXT, " +
"VORNAME TEXT, " +
"KOSTENSTELLE TEXT)";
private static final String CREATE_TABLE_UNTERKUNFT = "create table " + TABLE_UNTERKUNFT +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"PROJEKT TEXT, " +
"ENTFERNUNG INT, " +
"PRICE INT, " +
"MWST INT)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROJEKT);
db.execSQL(CREATE_TABLE_UNTERKUNFT);
//db.execSQL(CREATE_TABLE_AUTO);
//db.execSQL(CREATE_TABLE_FLUGZEUG);
//db.execSQL(CREATE_TABLE_BAHN);
//db.execSQL(CREATE_TABLE_TAXI);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROJEKT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_UNTERKUNFT);
onCreate(db);
}
//+++++++++++++CREATE A PROJECT++++++++++++//
public boolean createProject(String project, String date_from, String date_to, String name, String vorname, String kostenstelle){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_PROJECT, project);
contentValues.put(KEY_DATE_FROM, date_from);
contentValues.put(KEY_DATE_TO, date_to);
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_VORNAME, vorname);
contentValues.put(KEY_KOSTENST, kostenstelle);
long result = db.insert(TABLE_PROJEKT,null,contentValues);
if(result == -1)
return false;
else
return true;
}
//+++++++++++++CREATE A UNTERKUNFT++++++++++++//
public boolean createUnterkunft(String project, String date_from, String date_to, String name, String vorname, String kostenstelle){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_PROJECT, project);
contentValues.put(KEY_DATE_FROM, date_from);
contentValues.put(KEY_DATE_TO, date_to);
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_VORNAME, vorname);
contentValues.put(KEY_KOSTENST, kostenstelle);
long result = db.insert(TABLE_PROJEKT,null,contentValues);
if(result == -1)
return false;
else
return true;
}
//Getting values from spinner (Drop-Down)
public List<String> getAllProjects(){
List<String> projects = new ArrayList<String>();
String selectQuery = "SELECT " + KEY_PROJECT + "FROM " + TABLE_PROJEKT;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
if (cursor.moveToFirst()) {
do {
projects.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return projects;
}
}
Unterkunft Class
package com.group6.TakeOff;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ArrayAdapter;;
import java.util.List;
/**
* Created by STzavelas on 24.06.17.
*/
public class activity_unterkunft extends AppCompatActivity {
DatabaseHelper myDb;
Button btn_save;
Spinner ChooseProject;
EditText Entfernung,Price,MWST;
private BottomNavigationView bottomNavigationView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unterkunft);
myDb = new DatabaseHelper(this);
ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
Entfernung = (EditText) findViewById(R.id.Entfernung);
Price = (EditText) findViewById(R.id.Preis);
MWST = (EditText) findViewById(R.id.MwSt);
btn_save=(Button) findViewById(R.id.btn_save);
//ChooseProject.setOnItemSelectedListener(this);
loadSpinnerData();
//SaveData();
//++++++++++++BOTTOM NAVIGATION BAR++++++++++++//
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
if (item.getItemId()==R.id.menu_start){
startActivity(new Intent(activity_unterkunft.this, MainActivity.class));
} else if(item.getItemId()==R.id.menu_allgemein){
startActivity(new Intent(activity_unterkunft.this, activity_allgemein.class));
} else if(item.getItemId()==R.id.menu_transport){
startActivity(new Intent(activity_unterkunft.this, activity_transport.class));
} else if(item.getItemId()==R.id.menu_rechnung){
startActivity(new Intent(activity_unterkunft.this, activity_rechnung.class));
} else if(item.getItemId()==R.id.menu_unterkunft){
startActivity(new Intent(activity_unterkunft.this, activity_unterkunft.class));
}
return true;
}
});
bottomNavigationView.setSelectedItemId(R.id.menu_unterkunft);
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHelper db = new DatabaseHelper (getApplicationContext());
// Spinner Drop down elements
List<String> projects = db.getAllProjects();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
ChooseProject.setAdapter(dataAdapter);
}
}
Runtime Exception from logcat:
8-04 15:09:28.193 10721-10721/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.group6.travlhoe, PID: 10721
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft}: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.group6.TakeOff.DatabaseHelper.getAllProjects(DatabaseHelper.java:141)
at com.group6.TakeOff.activity_unterkunft.loadSpinnerData(activity_unterkunft.java:77)
at com.group6.TakeOff.activity_unterkunft.onCreate(activity_unterkunft.java:41)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
08-04 15:09:29.375 1518-1531/? E/memtrack: Couldn't load memtrack module
08-04 15:09:30.634 1518-1575/? E/InputDispatcher: channel '160c8 com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft (server)' ~ Channel is unrecoverably broken and will be disposed!
08-04 15:09:30.634 1518-1575/? E/InputDispatcher: channel '8a33e37 com.group6.travlhoe/com.group6.TakeOff.activity_allgemein (server)' ~ Channel is unrecoverably broken and will be disposed!
08-04 15:09:30.636 1518-1575/? E/InputDispatcher: channel '32f6f4d com.group6.travlhoe/com.group6.TakeOff.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
08-04 15:09:30.703 1349-1368/? E/SurfaceFlinger: Failed to find layer (com.group6.travlhoe/com.group6.TakeOff.activity_allgemein#0) in layer parent (no-parent).
08-04 15:09:30.732 11098-11105/? E/zygote: Failed sending reply to debugger: Broken pipe
08-04 15:09:30.753 1518-2450/? E/ActivityManager: applyOptionsLocked: Unknown animationType=0
08-04 15:09:31.387 11098-11098/? E/CursorWindow: Failed to read row 0, column 1 from a CursorWindow which has 1 rows, 1 columns.
08-04 15:09:31.389 11098-11098/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.group6.travlhoe, PID: 11098
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft}: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.group6.TakeOff.DatabaseHelper.getAllProjects(DatabaseHelper.java:141)
at com.group6.TakeOff.activity_unterkunft.loadSpinnerData(activity_unterkunft.java:77)
at com.group6.TakeOff.activity_unterkunft.onCreate(activity_unterkunft.java:41)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
08-04 15:09:31.563 1518-1606/? E/TaskPersister: File error accessing recents directory (directory doesn't exist?).
08-04 15:09:32.694 1518-1528/? E/ActivityManager: Found activity ActivityRecord{1e06b4f u0 com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft t-1 f} in proc activity list using null instead of expected ProcessRecord{9c4d79f 11098:com.group6.travlhoe/u0a86}
08-04 15:09:33.051 1415-1496/? E/AudioFlinger: not enough memory for AudioTrack size=131296
08-04 15:09:33.052 1415-1496/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
08-04 15:09:33.054 2179-10736/? E/AudioRecord: AudioFlinger could not create record track, status: -12
08-04 15:09:33.093 2179-10736/? E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
08-04 15:09:33.093 2179-10736/? E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
You need a space before FROM in your select query string:
String selectQuery = "SELECT " + KEY_PROJECT + " FROM " + TABLE_PROJEKT;
^
HERE
Look at the SQLiteException in the logcat:
Caused by: SQLiteException: no such column: PROJEKTFROM (code 1):
Crash after making the above change:
In your select statement you are selecting a single column:
String selectQuery = "SELECT " + KEY_PROJECT + " FROM " + TABLE_PROJEKT;
But while accessing the data from the cursor you are doing:
projects.add(cursor.getString(1));
Now cursor index are zero-based and you don't have a 1st column only 0th.
Apparently you are selecting a single column KEY_PROJECT and trying to access index = 1.
Couldn't read row 0, col 1 from CursorWindow.
According to Android's Cursor documentation, the index is zero-based.
Parameters
columnIndex int: the zero-based index of the target column.
Just change the following line of code from 1 to 0.
projects.add(cursor.getString(1));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I'm not familiar with SQlite so I'm not sure if I'm passing incorrect data type to the DBHelper class or what I'm doing wrong.
This is my logcat
04-16 22:31:07.341 21052-21052/com.example.android.inputtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.inputtest, PID: 21052
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.database.sqlite.SQLiteException: near "jordytip": syntax error (code 1): , while compiling: CREATE TABLE Tips(_id INTEGER PRIMARY KEY AUTOINCREMENT jordytip INTEGER mariatip INTEGER )
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1795)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1726)
at com.example.android.inputtest.MyDBHandler.onCreate(MyDBHandler.java:32)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.android.inputtest.MyDBHandler.addJordyTip(MyDBHandler.java:44)
at com.example.android.inputtest.MainActivity.submit(MainActivity.java:50)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
This is my main activity:
package com.example.android.inputtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int jordyTips = 388;
int mariaTips = 388;
int more;
int less;
EditText tipInput;
TextView jordyOutput;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tipInput = (EditText) findViewById(R.id.tipInput);
jordyOutput = (TextView) findViewById(R.id.jordyOutput);
dbHandler = new MyDBHandler(this,null, null,1);
}
public void submit (View view){
String value= tipInput.getText().toString();
int newTip =Integer.parseInt(value);
if (newTip % 2 == 0){
more = newTip/2;
less = newTip/2;
} else {
more = newTip/2 + 1;
less = newTip/2;
}
if (jordyTips <= mariaTips) {
jordyTips += more;
TipData tip = new TipData(more);
dbHandler.addJordyTip(tip);
printDatabase();
mariaTips += less;
} else {
jordyTips += less;
TipData tip = new TipData(less);
dbHandler.addJordyTip(tip);
printDatabase();
mariaTips += more;}
displayQuantity();
}
public void displayQuantity() {
TextView quantityTextView1 = jordyOutput;
TextView quantityTextView2 = (TextView)findViewById(R.id.mariaOutput);
quantityTextView1.setText((jordyTips-more)+ "+" + more + " " + String.valueOf(jordyTips));
quantityTextView2.setText(String.valueOf(mariaTips)+ "+" + less);
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
jordyOutput.setText(dbString);
tipInput.setText("");
}
}
This is my TipData class:
package com.example.android.inputtest;
/**
* Created by jordy on 4/16/2017.
*/
public class TipData {
private int _id;
private int _jordytip;
public TipData(int jordytip) {
this._jordytip = jordytip;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_jordytip(int _jordytip) {
this._jordytip = _jordytip;
}
public int get_id() {
return _id;
}
public int get_jordytip() {
return _jordytip;
}
}
and this is my DBHandler class:
package com.example.android.inputtest;
/**
* Created by jordy on 4/16/2017.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "tips.db";
public static final String TABLE_NAME = "Tips";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_JORDYTIP = "jordytip";
public static final String COLUMN_MARIATIP = "mariatip";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
COLUMN_JORDYTIP + " INTEGER " +
COLUMN_MARIATIP + " INTEGER " +
")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public void addJordyTip(TipData jordytip){
ContentValues values = new ContentValues();
values.put(COLUMN_JORDYTIP,jordytip.get_jordytip() );
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
public void deleteTip(String jordyTip){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM" + TABLE_NAME + " WHERE " + COLUMN_JORDYTIP + "=\"" + jordyTip + "\";");
}
public String databaseToString(){
String dbString= "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM" + TABLE_NAME + "WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if (c.getString(c.getColumnIndex("jordytip"))!=null){
dbString += c.getString(c.getColumnIndex("jordytip"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Getting this now:
04-17 00:17:58.181 20893-20893/com.example.android.inputtest E/SQLiteLog: (1) near "1": syntax error
04-17 00:17:58.191 20893-20893/com.example.android.inputtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.inputtest, PID: 20893
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.database.sqlite.SQLiteException: near "1": syntax error (code 1): , while compiling: SELECT * FROM TipsWHERE 1
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1437)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1376)
at com.example.android.inputtest.MyDBHandler.databaseToString(MyDBHandler.java:63)
at com.example.android.inputtest.MainActivity.printDatabase(MainActivity.java:83)
at com.example.android.inputtest.MainActivity.submit(MainActivity.java:51)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
However when I add the space before where
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
I get "app not responding".
Caused by: android.database.sqlite.SQLiteException: near "jordytip":
syntax error (code 1): , while compiling: CREATE TABLE Tips(_id
INTEGER PRIMARY KEY AUTOINCREMENT jordytip INTEGER mariatip INTEGER )
At first Rectify Query
String query = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"
+ COLUMN_JORDYTIP + " INTEGER ,"
+ COLUMN_MARIATIP + " INTEGER" + ")";
I've gone through a lot of the forum answers and usually the problem is not
adding a "," or a space where it should be, that will change the SQL statement into something it's not supposed to be.
I tried taking a look at mine and I still can't find the error in my onCreate. And I use Genymotion to emulate the app each time so it can't be that the emulator has a previous database version, so it shouldn't be a problem with the onUpgrade method.
Here's the logcat
09-19 07:54:26.137 7344-7344/com.example.cartermah.mywishlist E/SQLiteLog﹕ (1) table wishes has no column named content
09-19 07:54:26.137 7344-7344/com.example.cartermah.mywishlist E/SQLiteDatabase﹕ Error inserting content=jalksjldk title=HIHI recorddate=1442663666139
android.database.sqlite.SQLiteException: table wishes has no column named content (code 1): , while compiling: INSERT INTO wishes(content,title,recorddate) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
at data.DatabaseHandler.addWishes(DatabaseHandler.java:67)
at com.example.cartermah.mywishlist.MainActivity.saveToDB(MainActivity.java:53)
at com.example.cartermah.mywishlist.MainActivity.access$000(MainActivity.java:15)
at com.example.cartermah.mywishlist.MainActivity$1.onClick(MainActivity.java:36)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
09-19 07:54:26.137 7344-7344/com.example.cartermah.mywishlist V/Wished saved!﹕ yeah
And the database handler code is
package data;
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.Toast;
import com.example.cartermah.mywishlist.MainActivity;
import java.sql.Date;
import java.util.ArrayList;
import model.MyWish;
/**
* Created by CarterMah on 14/09/2015.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
public final ArrayList<MyWish> wishList = new ArrayList<>();
public DatabaseHandler(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
//This is where the table is created
String CREATE_WISHES_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "(" + Constants.KEY_ID +
" INTEGER PRIMARY KEY, " + Constants.TITLE_NAME + " TEXT, " + Constants.CONTENT_NAME +
" TEXT, " + Constants.DATE_NAME + " LONG" + ");";
db.execSQL(CREATE_WISHES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_NAME);
//Create a new table
onCreate(db);
}
public void addWishes (MyWish wish) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.TITLE_NAME, wish.getTitle());
values.put(Constants.CONTENT_NAME, wish.getContent());
values.put(Constants.DATE_NAME, java.lang.System.currentTimeMillis());
db.insert(Constants.TABLE_NAME, null, values);
Log.v("Wished saved!","yeah");
db.close();
}
// Get all wishes
public ArrayList<MyWish> getWishes() {
String selectQuery = "SELECT * FROM " + Constants.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Constants.TABLE_NAME, new String[]{Constants.KEY_ID,
Constants.TITLE_NAME, Constants.CONTENT_NAME, Constants.DATE_NAME,},
null, null, null, null, Constants.DATE_NAME + " DESC");
// loop through cursor to get every row of data
if (cursor.moveToFirst()) {
do{
MyWish wish = new MyWish();
wish.setTitle(cursor.getString(cursor.getColumnIndex(Constants.TITLE_NAME)));
wish.setContent(cursor.getString(cursor.getColumnIndex(Constants.CONTENT_NAME)));
java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance();
String dataData = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Constants.DATE_NAME))).getTime());
wish.setRecordDate(dataData);
wishList.add(wish);
}while (cursor.moveToNext());
}
return wishList;
}
}
Constants.java
public class Constants {
public static final String DATABASE_NAME = "wishdb";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "wishes";
public static final String TITLE_NAME = "title";
public static final String CONTENT_NAME = "content";
public static final String DATE_NAME = "recorddate";
public static final String KEY_ID = "_id";
}
MainActivity
package com.example.cartermah.mywishlist;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
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 data.DatabaseHandler;
import model.MyWish;
public class MainActivity extends AppCompatActivity {
private EditText title;
private EditText content;
private Button saveButton;
private DatabaseHandler dba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dba = new DatabaseHandler(MainActivity.this);
title = (EditText)findViewById(R.id.titleEditText);
content = (EditText)findViewById(R.id.wishEditText);
saveButton = (Button)findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToDB();
}
});
}
private void saveToDB() {
MyWish wish = new MyWish();
wish.setTitle(title.getText().toString().trim());
wish.setContent(content.getText().toString().trim());
dba.addWishes(wish);
dba.close();
// clear the form once users click the save button.
title.setText("");
content.setText("");
// Intent i = new Intent(MainActivity.this, WishDetailActivity.class);
// startActivity(i);
}
}
You need to add id when you insert because id is not autoincrement.OR make id autoincrement.
You mention using Genymotion as a reason an existing DB wouldn't be a problem but I don't think that's an accurate assumption. Unless you are completely uninstalling the app before you launch the new one the previous database version is still on the device and won't be overriden. I would recommend completely uninstalling the app from Genymotion and then install it with the latest onCreate statement and see if a fresh install would overwrite any possible occurrence of a previous database version.
I got into the same problems, but All I've done is just to uninstall the apps and reinstall again, it's worked perfectly.
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+`"