E/SQLiteLog: (1) no such column: 100 - java

I had a long time to fix this issue but couldn't solve it.
I was sure there were no wrong codes, but if I execute the emulator then the problem is when I click the specific item on the listview, it is shown, "open app again". I made database and put datas in it from csv file. Here are the codes:
word_db.csv
word_db.csv
DB_Word.java
public class DB_Word extends SQLiteOpenHelper {
public DB_Word(Context context){
super(context, "word.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists word (word_id integer primary key, category_id_fk integer, word_kor text, word_eng text, word_pro text, foreign key(category_id_fk) references category(category_id));");
System.out.println("Create table word success");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table word;");
onCreate(db);
}
}
Categories_wordview1.java
public class Categories_wordview1 extends AppCompatActivity {
ArrayAdapter<String> Adapter;
ListView wordlist;
DB_Word dbc;
SQLiteDatabase db;
String sql;
Cursor cursor;
String[] result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_wv);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
wordlist = (ListView) findViewById(R.id.wordlist);
dbc = new DB_Word(this);
delete();
insertAll();
select();
}
public void delete(){
try {
System.out.println("delete complete");
db = dbc.getWritableDatabase();
db.execSQL("delete from word;");
} catch (Exception e) {
e.printStackTrace();
}
}
public void select(){
System.out.println("select");
try {
System.out.println("select try");
db = dbc.getReadableDatabase();
sql = "select word_kor, word_eng, word_pro from word;";
cursor = db.rawQuery(sql, null);
int count = cursor.getCount();
result = new String[count];
for(int i = 0; i < count; i++){
System.out.println("select for");
cursor.moveToNext();
String str_kor = cursor.getString(0);
String str_eng = cursor.getString(1);
String str_pro = cursor.getString(2);
result[i] = str_kor + " " + str_eng + " " + str_pro;
}
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
wordlist.setAdapter(Adapter);
wordlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
} catch (Exception e) {
e.printStackTrace();
}
}
public void insertAll(){
System.out.println("insert");
db = dbc.getWritableDatabase();
InputStream is = this.getResources().openRawResource(R.raw.word_db);
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String tableName ="word";
String columns = "word_id, category_id_fk, word_kor";
String str1 = "insert into " + tableName + "(" + columns + ") values(";
String str2 = ");";
String line ="";
db.beginTransaction();
try {
System.out.println("transaction try");
while ((line = buffer.readLine()) != null) {
System.out.println("transaction while");
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
sb.append(str[0] + ", ");
sb.append(str[1] + ", '");
sb.append(str[2] + "'");
sb.append(str2);
System.out.println(sb.toString());
db.execSQL(sb.toString());
//db.rawQuery(sb.toString(), null);
}
db.setTransactionSuccessful();
db.endTransaction();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here is the logcat showing:
12-28 00:04:05.106 1554-1651/? E/TaskPersister: File error accessing recents directory (directory doesn't exist?).
12-28 00:04:15.182 1554-1795/? I/ActivityManager: START u0 {cmp=com.example.project2/.Categories_word.Categories_wordview1} from uid 10009
12-28 00:04:15.194 1380-2231/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 3729276 , only wrote 3728880
12-28 00:04:15.315 3259-3259/? I/System.out: delete complete
12-28 00:04:15.401 3259-3259/? I/System.out: Create table word success
12-28 00:04:15.409 3259-3259/? I/System.out: insert
12-28 00:04:15.411 3259-3259/? I/System.out: transaction try
12-28 00:04:15.412 3259-3259/? I/System.out: transaction while
12-28 00:04:15.412 3259-3259/? I/System.out: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');
12-28 00:04:15.413 3259-3259/? E/SQLiteLog: (1) no such column: 100
12-28 00:04:15.413 3259-3259/? D/AndroidRuntime: Shutting down VM
12-28 00:04:15.418 3259-3259/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.project2, PID: 3259
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project2/com.example.project2.Categories_word.Categories_wordview1}: android.database.sqlite.SQLiteException: no such column: 100 (code 1): , while compiling: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');
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:6541)
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: android.database.sqlite.SQLiteException: no such column: 100 (code 1): , while compiling: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');
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.executeSql(SQLiteDatabase.java:1677)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
at com.example.project2.Categories_word.Categories_wordview1.insertAll(Categories_wordview1.java:117)
at com.example.project2.Categories_word.Categories_wordview1.onCreate(Categories_wordview1.java:51)
at android.app.Activity.performCreate(Activity.java:6975)
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:6541) 
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) 
12-28 00:04:15.483 1554-1566/? W/ActivityManager: Force finishing activity com.example.project2/.Categories_word.Categories_wordview1
12-28 00:04:15.503 1554-1566/? W/ActivityManager: Force finishing activity com.example.project2/.Categories
This is the issue:
E/SQLiteLog: (1) no such column: 100
android.database.sqlite.SQLiteException: no such column: 100 (code 1): , while compiling: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');

The first line of your CSV file contains an invisible control character (zero width no-break space) that is written by some Windows programs to mark the file as containing Unicode. Remove it.

Related

How to show multiple data from SQLite database inside ListView in Android

I am a newcomer to Android development.
I can't figure out how to get Android Studio to just take what's in my SQLite database and paste its contents into a listview. I thought there would be a easy way after Log the output but can able to display everything there is in a database in a ListView but it appears to be much more in a different way of doing it.
public class MainActivity extends AppCompatActivity {
EditText nameEditText;
EditText phoneEditText;
ListView updateListView;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.nameEditText);
phoneEditText = findViewById(R.id.phoneEditText);
updateListView = findViewById(R.id.updatedListView);
sqLiteDatabase = this.openOrCreateDatabase("Contact", MODE_PRIVATE, null);
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS users(name VARCHAR, phone INT(11),id INTEGER PRIMARY KEY)");
}
public void OnClick(View view) {
if (nameEditText.equals("") || phoneEditText.equals("")) {
Toast.makeText(this, "Fields shouldn't be empty", Toast.LENGTH_SHORT).show();
} else {
sqLiteDatabase.execSQL("INSERT INTO users(name, phone) VALUES('" + nameEditText.getText().toString() + "','" + phoneEditText.getText().toString() + "')");
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM users", null);
int nameIndex = c.getColumnIndex("name");
int phoneIndex = c.getColumnIndex("phone");
int idIndex = c.getColumnIndex("id");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
String str = c.getString(0);
String UpdatedList = (c.getString(nameIndex));
String phonelist = (c.getString(phoneIndex));
String list = (UpdatedList+phonelist);
ArrayList<String> arrayList = new ArrayList<String>(Integer.parseInt(list));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
updateListView.setAdapter(arrayAdapter);
Log.i("User Name", c.getString(nameIndex));
Log.i("userResults - age", Integer.toString(c.getInt(phoneIndex)));
Log.i("userResults - id", Integer.toString(c.getInt(idIndex)));
c.moveToNext();
}
}
}
}
}
My Logput
2020-01-22 20:22:48.353 28783-28783/? D/AndroidRuntime: Shutting down VM
2020-01-22 20:22:48.357 28783-28783/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mysqlapp, PID: 28783
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6669)
at android.view.View.performClickInternal(View.java:6638)
at android.view.View.access$3100(View.java:789)
at android.view.View$PerformClick.run(View.java:26145)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6669) 
at android.view.View.performClickInternal(View.java:6638) 
at android.view.View.access$3100(View.java:789) 
at android.view.View$PerformClick.run(View.java:26145) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6898) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.mysqlapp.MainActivity.OnClick(MainActivity.java:65)
call setAdapter method outside, after you declare whole arrayList from sql, outside of for loop

Populate spinner with data from sqlite database - App crashes

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

getting runtime error "java.lang.IllegalStateException: Could not execute method for android:onClick" [closed]

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" + ")";

SQLite Exception: near "=" on delete query

I am having an issue with my college project. I am trying to delete a row from my one of my tables using the following query.
//---deletes a particular match---
public boolean deleteMatch(String name) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
return sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = " + name, null) > 0;
}
Here I am trying to delete a record based upon the match_opponent and passing the String value name.
I am then calling this method in my EditSchedule activity below:
public class EditSchedule extends AppCompatActivity {
public Button fixtureSearch;
public EditText opponentName;
public String searchTerm;
ListView editMatch;
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase sqLiteDatabase;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editfixture);
editMatch = (ListView) findViewById(R.id.listViewEditMatch);
opponentName = (EditText) findViewById(R.id.fixtureOpponentDelete);
searchTerm = opponentName.getText().toString();
fixtureSearch = (Button) findViewById(R.id.fixtureSearchButton);
fixtureSearch.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteMatch(searchTerm);
}
}
);
}
}
So when I test my application by typing in a name of an opponent that I have in the fixture table and clicking on the delete button, I get the following error:
01-06 07:49:42.476 25778-25778/com.example.myacer.clubhub E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: DELETE FROM fixtures WHERE match_opponent =
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.delete(SQLiteDatabase.java:1494)
at com.example.myacer.clubhub.database.DBHelper.deleteMatch(DBHelper.java:243)
at com.example.myacer.clubhub.manager.EditSchedule$1.onClick(EditSchedule.java:47)
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)
Can anyone see where I am going wrong? All help greatly appreciated.
You are passing blank value in deleteMatch(), put searchTerm = opponentName.getText().toString(); inside onClick()
fixtureSearch.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
searchTerm = opponentName.getText().toString();
dbHelper.deleteMatch(searchTerm);
}
}
);
As well as change your deleteMatch() method
sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = ?",new String[]{name});
try this:
sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = ?", new String[]{name})

Null Pointer Exception : coudnt find solution

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+`"

Categories

Resources