SQL Database Error : Table has no column name - java

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.

Related

Error in inserting record due to 787 SQLite exception

I've been for some days now having this error of trying to insert an object, check that it has actually been inserted, then retrieve that object id to create the record in the many-to-many table, but for some reason, I always get the 787 error saying that I'm basically creating this record without existing in the parent table in the first place, which is impossible since, well, I check it just as I create it, and it is there. How can I fix this?
This is the activity where I insert both records (bottom part):
package com.gmproxy.pastilarma;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.gmproxy.DAO.AlarmRepository;
import com.gmproxy.DAO.AlarmUserRepository;
import com.gmproxy.Entities.Alarm;
import com.gmproxy.Entities.Medicine;
import com.gmproxy.Entities.User;
import com.gmproxy.Alarm.UtilAlarma;
import com.gmproxy.ViewModels.AlarmViewModel;
import com.gmproxy.ViewModels.MedicineViewModel;
import com.gmproxy.ViewModels.UserViewModel;
import java.util.Calendar;
public class UserAlarmScreen extends AppCompatActivity {
TextView usernameAlarm,numHabText,medicineText,notificationsTime;
EditText medicineQuantityText;
Button gotoBackBtn,gotoMedicinesBtn,confirmAlarmBtn;
int alarmID = 1;
int idM,idU;
SharedPreferences settings;
User user;
Medicine medicine;
Alarm alarm;
AlarmUserRepository alUsRe;
AlarmRepository alRe;
AlarmViewModel alarmViewModel;
UserViewModel userViewModel;
MedicineViewModel medicineViewModel;
String medicineQuantity;
int med_record;
Calendar today;
String message;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_alarm_screen);
context = this.getApplicationContext();
idU = getIntent().getIntExtra("id_userA",0);
Log.println(Log.INFO,"id",String.valueOf(idU));
idM = getIntent().getIntExtra("med",0);
Log.println(Log.INFO,"Id medicina",String.valueOf(idM));
med_record = getIntent().getIntExtra("med-record",0);
/*
If we come back from medicine search, we actually reload everything that was writter before, so that the user doesn't have to rewrite it
*/
if (med_record == 1){
loadPreferences();
}
userViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(UserViewModel.class);
alarmViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(AlarmViewModel.class);
medicineViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MedicineViewModel.class);
alUsRe = new AlarmUserRepository(this.getApplication());
alRe = new AlarmRepository(this.getApplication());
user = userViewModel.getObjectById(idU);
medicine = medicineViewModel.getMedicineById(idM);
usernameAlarm = findViewById(R.id.UsernameAlarm);
usernameAlarm.setText(user.getUser_name() + " " + user.getUser_surname());
numHabText = findViewById(R.id.NumHabText);
numHabText.setText(String.valueOf(user.getRoom_number()));
medicineText = findViewById(R.id.MedicineText);
if (idM > 0){
medicineText.setText(medicine.getMedicineName());
}
medicineQuantityText = findViewById(R.id.MedicineQuantity);
medicineQuantity = medicineQuantityText.getText().toString();
gotoBackBtn = findViewById(R.id.gotoBack);
notificationsTime = findViewById(R.id.HoraInput);
gotoMedicinesBtn = findViewById(R.id.gotoMedicines);
confirmAlarmBtn = findViewById(R.id.ConfirmAlarm);
/*
Now this is pod racing. From here on out until the create method ends, we'll be creating the actual alarm+notification!
Isn't it exciting!?
No it's not, please do keep reading.
*/
settings = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
String hour, minute;
hour = settings.getString("hour","");
minute = settings.getString("minute","");
if(hour.length() > 0)
{
notificationsTime.setText(hour + ":" + minute);
}
/*
This displays the TimePicker and automatically writes it down for the notification to be created
*/
findViewById(R.id.CambiarNotificacion).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(UserAlarmScreen.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String finalHour, finalMinute;
finalHour = "" + selectedHour;
finalMinute = "" + selectedMinute;
if (selectedHour < 10) finalHour = "0" + selectedHour;
if (selectedMinute < 10) finalMinute = "0" + selectedMinute;
notificationsTime.setText(finalHour + ":" + finalMinute);
today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, selectedHour);
today.set(Calendar.MINUTE, selectedMinute);
today.set(Calendar.SECOND, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("hour", finalHour);
edit.putString("minute", finalMinute);
//SAVE ALARM TIME TO USE IT IN CASE OF REBOOT
edit.putInt("alarmID", alarmID);
edit.putLong("alarmTime", today.getTimeInMillis());
edit.commit();
Toast.makeText(UserAlarmScreen.this, "Alarma puesta a las " + finalHour + ":" + finalMinute, Toast.LENGTH_LONG).show();
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Escoge una hora");
mTimePicker.show();
}
});
}
private void loadPreferences(){
SharedPreferences preferences = getSharedPreferences("dataA",Context.MODE_PRIVATE);
idU = preferences.getInt("idU",0);
}
private void savePreferences(){
SharedPreferences preferences = getSharedPreferences("dataA",Context.MODE_PRIVATE);
SharedPreferences.Editor editer = preferences.edit();
editer.putInt("idU",idU);
editer.commit();
}
public void gotoBack(View view){
Intent mainAct = new Intent(UserAlarmScreen.this, UserInfoScreen.class);
mainAct.putExtra("id_user",idU);
startActivity(mainAct);
}
public void gotoMedicines(View view){
Intent mainAct = new Intent(UserAlarmScreen.this, PillsSearchScreen.class);
mainAct.putExtra("id_userB",idU);
savePreferences();
startActivity(mainAct);
}
/**
* Pretty much self explanatory, confirms the alarm and adds it to the database, both to the alarm table and
* the alarm-user table in order to be shown in the recycler view back at user-info-screen.
* #param view
*/
public void confirmAlarm(View view) throws InterruptedException {
alRe.insertAlarm(medicine.getId_medicine(),
notificationsTime.getText().toString());
Log.println(Log.INFO,"Med check null",String.valueOf(medicine.getId_medicine()));
Log.println(Log.INFO,"Hour check null",notificationsTime.getText().toString());
int idAl = alarmViewModel.getAlarmbyTimeAndMedId(notificationsTime.getText().toString(),medicine.getId_medicine());
Log.println(Log.INFO,"Alarm Id Res check null",String.valueOf(alRe.getAlarmbyTimeAndMedId(notificationsTime.getText().toString(),medicine.getId_medicine())));
Log.println(Log.INFO,"Alarm Id check null",String.valueOf(idAl));
alUsRe.insertObjectById(idAl,idU);
message = "El paciente " + user.getUser_name() + " " + user.getUser_surname()
+ " tiene apuntada la medicación " + medicine.getMedicineName() + " a las " + notificationsTime.getText().toString() + " horas.";
UtilAlarma.setAlarm(idAl, today.getTimeInMillis(), UserAlarmScreen.this, message);
Intent mainAct = new Intent(UserAlarmScreen.this, UserInfoScreen.class);
int id = 1;
mainAct.putExtra("alar-record",id);
startActivity(mainAct);
}
}
And this is the stack trace:
I/Med check null: 12684
I/Hour check null: 01:28
I/Alarm Id Res check null: 26
I/Alarm Id check null: 0
E/AndroidRuntime: FATAL EXCEPTION: pool-3-thread-2
Process: com.gmproxy.pastilarma, PID: 6015
android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787 SQLITE_CONSTRAINT_FOREIGNKEY)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:938)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:790)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:88)
at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
at com.gmproxy.DAO.AlarmUserDAO_Impl.insertIntoAlarmUser(AlarmUserDAO_Impl.java:150)
at com.gmproxy.DAO.AlarmUserRepository.lambda$insertObjectById$1$AlarmUserRepository(AlarmUserRepository.java:41)
at com.gmproxy.DAO.-$$Lambda$AlarmUserRepository$2T5LlZH-RbFoUm3l2obKvPWaNZU.run(Unknown Source:6)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
So, it all went down to making sure that the object in java was first created, then inserted. I was getting that error becuase it was being inserted wrongly with id=0, therefore returning error 787.

SQLite Database not being created in Android Studio when the project is run on a new machine or if the Database folder is deleted

I have built an application where using fusedlocation provider I get the location and based on the location on I display a report card of a particular location from an SQLiteDatabase.
The database worked fine initially but then when I ran the same android project on another machine it wasn't creating the database. Once the database folder was being created by Android in Device File Explorer -> Data -> Data -> Package Name -> Databases. I was manually loading the following Database file by right clicking on the the Database folder and clicking upload.
Database file link: https://drive.google.com/file/d/197MHiLl8nvFZ5eHStrBR9WfeYvQTtDKm/view?usp=sharing
To try to understand what the issue is I deleted the database folder from my project on my own machine as well and now the Database folder isn't created on my machine as well.
Before you mark this as a duplicate I have already tried the methods from the following questions but it still didn't work.
Android SQLite database table not being created
sqlite database not created
https://alvinalexander.com/android/sqliteopenhelper-does-not-call-oncreate-failing-database
Please find my code below:
DatabaseHelper.java
package edu.cpsc6150.co2ut;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME = "states";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "States_Report";
public static final String KEY_ID = "id";
public static final String STATE_NAME = "name";
public static final String STATE_GRADE = "grade";
public static final String EXTREME_HEAT = "heat";
public static final String DROUGHT = "Drought";
public static final String WILDFIRES = "wildfires";
public static final String INLAND_FLOODING = "inlandflooding";
public static final String COASTAL_FLOODING = "coastalflooding";
public static final String CREATE_TABLE_STUDENTS = "CREATE TABLE "
+ TABLE_NAME + "(" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ STATE_NAME + " TEXT,"
+ STATE_GRADE + " TEXT,"
+ EXTREME_HEAT + " TEXT,"
+ DROUGHT + " TEXT,"
+ WILDFIRES + " TEXT,"
+ INLAND_FLOODING + " TEXT,"
+ COASTAL_FLOODING + " TEXT)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//Log.d("table", CREATE_TABLE_STUDENTS);
} //end DatabaseHelper constructor
/**
* Functionality: Creates tables
* PreConditions: needs table names and column names
* PostConditions: Table is created
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENTS);
} //end onCreate method
/**
* Functionality: Drop existing table and create new table if table already exists
* PreConditions: Database name, oldversion number and newVersion number are required to create a new table
* PostConditions: Old table should be dropped and new table should be created
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS '" + TABLE_NAME + "'");
onCreate(db);
} //end onUpgrade method
/*
public long addStudentDetail(String state, String grade, String heat, String drought, String wildfires, String iflooding, String cflooding) {
SQLiteDatabase db = this.getWritableDatabase();
// Creating content values
ContentValues values = new ContentValues();
values.put(STATE_NAME, state);
values.put(STATE_GRADE, grade);
values.put(EXTREME_HEAT, heat);
values.put(DROUGHT, drought);
values.put(WILDFIRES, wildfires);
values.put(INLAND_FLOODING, iflooding);
values.put(COASTAL_FLOODING, cflooding);
// insert row in students table
long insert = db.insert(TABLE_NAME, null, values);
return insert;
}*/
/**
* Functionality: Get data from database and Update UI
* PreConditions: requires existing populated database
* PostConditions: Update reportcard in the UI from the database
*/
public String[] getData(String state) {
/*SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from States_Report where name = '"+state+"'", null );
return res;*/
String State = state;
String[] name = new String[7];
String password;
//SQLiteDatabase db = getWritableDatabase();
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = {DatabaseHelper.STATE_NAME,DatabaseHelper.STATE_GRADE,DatabaseHelper.EXTREME_HEAT,DatabaseHelper.DROUGHT,DatabaseHelper.WILDFIRES,DatabaseHelper.INLAND_FLOODING,DatabaseHelper.COASTAL_FLOODING};
Cursor cursor =db.query(DatabaseHelper.TABLE_NAME,columns,"name = '"+state+"' ",null,null,null,null);
StringBuffer buffer= new StringBuffer();
while (cursor.moveToNext())
{
name[0] =cursor.getString(cursor.getColumnIndex(DatabaseHelper.STATE_NAME));
name[1] =cursor.getString(cursor.getColumnIndex(DatabaseHelper.STATE_GRADE));
name[2] =cursor.getString(cursor.getColumnIndex(DatabaseHelper.EXTREME_HEAT));
name[3] =cursor.getString(cursor.getColumnIndex(DatabaseHelper.DROUGHT));
name[4] =cursor.getString(cursor.getColumnIndex(DatabaseHelper.WILDFIRES));
name[5] =cursor.getString(cursor.getColumnIndex(DatabaseHelper.INLAND_FLOODING));
name[6] =cursor.getString(cursor.getColumnIndex(DatabaseHelper.COASTAL_FLOODING));
}
return name;
} //end getData method
} //end DatabaseHelper class
ReportCardActivity.java (Which is like the MainActivity.java for this particular feature)
package edu.cpsc6150.co2ut;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ReportCardActivity extends AppCompatActivity {
private static final String TAG = ReportCardActivity.class.getSimpleName();
#BindView(R.id.location_result)
TextView txtLocationResult;
#BindView(R.id.btn_start_location_updates)
Button btnStartUpdates;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
private static final int REQUEST_CHECK_SETTINGS = 100;
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private Boolean mRequestingLocationUpdates;
private DatabaseHelper databaseHelper;
private TextView statedisplay, gradedisplay, heat, drought, wildfires, inlandFlooding,coastalFlooding;
/**
* Functionality: Instantiates the DatabaseHelper class and other UI Components like textviews
* PreConditions: DatabaseHelper and textviews must be declared
* PostConditions: Textviews are assigned and DatabaseHelper initialized
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_card);
ButterKnife.bind(this);
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = new DatabaseHelper(this).getReadableDatabase();
statedisplay = (TextView) findViewById(R.id.statedisplay);
gradedisplay = (TextView) findViewById(R.id.gradedisplay);
heat = (TextView) findViewById(R.id.heat);
drought = (TextView) findViewById(R.id.drought);
wildfires = (TextView) findViewById(R.id.wildfires);
inlandFlooding = (TextView) findViewById(R.id.inlandFlooding);
coastalFlooding = (TextView) findViewById(R.id.coastalFlooding);
// initialize the necessary libraries
init();
// restore the values from saved instance state
restoreValuesFromBundle(savedInstanceState);
} //end onCreate method
/**
* Functionality: Initializes the necessary libraries to get location updates
* PreConditions: Library's required for the location updates must be declared
* PostConditions: All necessary Libraries are intialized
*/
private void init() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mSettingsClient = LocationServices.getSettingsClient(this);
mLocationCallback = new LocationCallback() {
/**
* Functionality: Updates Last location on receiving location updates
* PreConditions: Needs to receive locationResult as a parameter
* PostConditions: Return updated last location to the UI
*/
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
// location is received
mCurrentLocation = locationResult.getLastLocation();
updateLocationUI();
}
};
mRequestingLocationUpdates = false;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
} //end init method
/**
* Functionality: Restores the savedState of the activity
* PreConditions: Needs the instance state to be saved
* PostConditions: Retrieve the saved state and update the UI
*/
private void restoreValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("is_requesting_updates")) {
mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates");
}
if (savedInstanceState.containsKey("last_known_location")) {
mCurrentLocation = savedInstanceState.getParcelable("last_known_location");
}
}
updateLocationUI();
} //end restoreValuesFromBundle method
/**
* Functionality: Update the UI displaying the location data
* PreConditions: Requires the current location
* PostConditions: Updates the UI with the current location and the states report card from the database
*/
String state;
private void updateLocationUI() {
if (mCurrentLocation != null) {
Geocoder gcd = new Geocoder(this, Locale.getDefault());
try{
List<Address> addresses = gcd.getFromLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), 1);
if (addresses.size() > 0) {
state = addresses.get(0).getAdminArea();
String output[] = databaseHelper.getData(state);
statedisplay.setText(" State: "+output[0]);
gradedisplay.setText(" Average: "+output[1]);
heat.setText(" Extreme Heat: "+output[2]);
drought.setText(" Drought: "+output[3]);
wildfires.setText(" Wildfires: "+output[4]);
inlandFlooding.setText(" Inland Flooding: "+output[5]);
coastalFlooding.setText(" Coastal Flooding: "+output[6]);
/*Cursor rs = databaseHelper.getData(state);
if (rs.moveToFirst()){
// do the work
String username = rs.getString(1);
String password = rs.getString(2);
//String nam = rs.getString(rs.getColumnIndex(DatabaseHelper.STATE_NAME));
//String phon = rs.getString(rs.getColumnIndex(DatabaseHelper.STATE_GRADE));
statedisplay.setText(username);
gradedisplay.setText(password);
}*/
//arrayList = databaseHelper.getAllStudentsList();
//tvnames.setText("");
/*for (int i = 0; i < arrayList.size(); i++){
tvnames.setText(tvnames.getText().toString()+", "+arrayList.get(i));
}*/
}
else {
// do your stuff
}
} catch (IOException e1) {
e1.printStackTrace();
} //end try-catch block
txtLocationResult.setText(
getString(R.string.welcome_message,state)
);
// location last updated time
}
} //end updateLocationUI method
/**
* Functionality: Saves the Activities current state
* PreConditions: Needs the values of mCurrentLocation and mRequestingLocationUpdates
* PostConditions: The Instance state should be saved to the Bundle
*/
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("is_requesting_updates", mRequestingLocationUpdates);
outState.putParcelable("last_known_location", mCurrentLocation);
} //end onSaveInstanceState method
/**
* Functionality: Starting location updates
* PreConditions: Check whether location settings are satisfied
* PostConditions: Location updates will be requested
*/
private void startLocationUpdates() {
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#SuppressLint("MissingPermission")
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i(TAG, "All location settings are satisfied.");
Toast.makeText(getApplicationContext(), "Started location updates!", Toast.LENGTH_SHORT).show();
//noinspection MissingPermission
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
updateLocationUI();
} //end onSuccess method
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
"location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(ReportCardActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.i(TAG, "PendingIntent unable to execute request.");
} //end try-catch block
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText(ReportCardActivity.this, errorMessage, Toast.LENGTH_LONG).show();
} //end switch statement
updateLocationUI();
} //end onFailure method
});
} //end startLocationUpdates method
/**
* Functionality: OnClick will start receiving location updates
* PreConditions: Permissions must be granted
* PostConditions: Location Updates started
*/
#OnClick(R.id.btn_start_location_updates)
public void startLocationButtonClick() {
// Requesting ACCESS_FINE_LOCATION using Dexter library
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
mRequestingLocationUpdates = true;
startLocationUpdates();
} //end onPermissionGranted method
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response.isPermanentlyDenied()) {
// open device settings when the permission is
// denied permanently
openSettings();
}
} //end onPermuissionDenied method
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
} //end onPermissionRationaleShouldBeShown method
}).check();
} //end startLocationButtonClick method
/**
* Functionality: Stop or pause location updates when the app pauses
* PreConditions: FusedLocationClient must be intialized
* PostConditions: Stop Location updates
*/
public void stopLocationUpdates() {
// Removing location updates
mFusedLocationClient
.removeLocationUpdates(mLocationCallback)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
/**
* Functionality:
* PreConditions:
* PostConditions:
*/
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Location updates stopped!", Toast.LENGTH_SHORT).show();
}
});
} //end stopLocationUpdates method
/**
* Functionality: Check whether user has granted permissions or not
* PreConditions: Needs requestCode, resultCode and data as parameters
* PostConditions: Log the ActivityResult as an error log
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.e(TAG, "User agreed to make required location settings changes.");
// Nothing to do. startLocationupdates() gets called in onResume again.
break;
case Activity.RESULT_CANCELED:
Log.e(TAG, "User chose not to make required location settings changes.");
mRequestingLocationUpdates = false;
break;
} //end switch statement
break;
} //end switch statement
} //end onActivityResult method
/**
* Functionality: Open settings if permissions is denied
* PreConditions: Settings URI
* PostConditions: Open Application details settings page
*/
private void openSettings() {
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} //end openSettings method
/**
* Functionality: Check for permissions again onResume
* PreConditions: App must be paused or stopped before this function is called
* PostConditions: onResume the locationupdates must be resume and the UI must be updated
*/
#Override
public void onResume() {
super.onResume();
// Resuming location updates depending on button state and
// allowed permissions
if (mRequestingLocationUpdates && checkPermissions()) {
startLocationUpdates();
}
updateLocationUI();
} //end onResume()
/**
* Functionality: Checks if permission to access location is granted
* PreConditions: Permission must be mentioned in the manifest file
* PostConditions: Return permission granted if Uses-Permission is mentioned in the activity file
*/
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
} //end checkPermissions method
/**
* Functionality: Stops location updates when the application is paused
* PreConditions: Application must be paused
* PostConditions: Location updates must be stopped
*/
#Override
protected void onPause() {
super.onPause();
if (mRequestingLocationUpdates) {
// pausing location updates
stopLocationUpdates();
}
} //end onPause method
} //end ReportCardActivity class
Let me know if you need any more information regarding the code or dependencies.
I believe that the database is being created BUT you don't appear to be populating it.
Using your Databasehelper (with addStudentDetail uncommented as the only change) then using :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHelper = new DatabaseHelper(this);
mDBHelper.addStudentDetail("STATE1","GRADE1","HIGH","YES","NO","NO","NO");
mDBHelper.addStudentDetail("STATE1","GRADE2","HIGH","YES","NO","NO","NO");
mDBHelper.addStudentDetail("STATE1","GRADE3","HIGH","YES","NO","NO","NO");
mDBHelper.addStudentDetail("STATE1","GRADE4","HIGH","YES","NO","NO","NO");
for (String s: mDBHelper.getData("STATE1")){
Log.d("INFO",s);
}
}
}
results in :-
12-05 16:38:19.211 3764-3764/? D/INFO: STATE1
12-05 16:38:19.211 3764-3764/? D/INFO: GRADE4
12-05 16:38:19.211 3764-3764/? D/INFO: HIGH
12-05 16:38:19.211 3764-3764/? D/INFO: YES
12-05 16:38:19.211 3764-3764/? D/INFO: NO
12-05 16:38:19.211 3764-3764/? D/INFO: NO
12-05 16:38:19.211 3764-3764/? D/INFO: NO
I can't see anywhere in your code where you are adding data to the database. rather you just try to get data using String output[] = databaseHelper.getData(state);, which will retrieve nothing as there is no data.
Below I have attached a solution where you just need to add two lines of code to the ReportCardActivity.java code. The two lines of code to be added are commented as "//add this line" and have a line of astrix (*) before and after it.
private Boolean mRequestingLocationUpdates;
DatabaseHelper databaseHelper;
*********************************************************
SQLiteDatabase database; //add this line
*********************************************************
private TextView statedisplay, gradedisplay, heat, drought, wildfires, inlandFlooding,coastalFlooding;
/**
* Functionality: Instantiates the DatabaseHelper class and other UI Components like textviews
* PreConditions: DatabaseHelper and textviews must be declared
* PostConditions: Textviews are assigned and DatabaseHelper initialized
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_card);
ButterKnife.bind(this);
databaseHelper = new DatabaseHelper(this);
*********************************************************
database = databaseHelper.getWritableDatabase(); //add this line
*********************************************************
statedisplay = (TextView) findViewById(R.id.statedisplay);
gradedisplay = (TextView) findViewById(R.id.gradedisplay);
heat = (TextView) findViewById(R.id.heat);
drought = (TextView) findViewById(R.id.drought);
wildfires = (TextView) findViewById(R.id.wildfires);
inlandFlooding = (TextView) findViewById(R.id.inlandFlooding);
coastalFlooding = (TextView) findViewById(R.id.coastalFlooding);
// initialize the necessary libraries
init();
// restore the values from saved instance state
restoreValuesFromBundle(savedInstanceState);
} //end onCreate method
One you paste the code run the application. This should create the database directory in the Device File Explorer -> Data -> Data -> Package Name directory.
The database folder might not be visible immediately. You may have to restart android studio after you run the app once.
When you restart android studio and go to Device File Explorer -> Data -> Data -> Package Name directory the databases directory should be created.
Once it is created right click on the databases folder and click upload then upload the database file you have provided in the link.

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

Sqlite in android studio 2.2

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

E/SQLiteLog: (1) near "ENTER": syntax error

I'm getting this weird error while trying to create a database. I'm building an expense manager app and want to store the data from textview into SQLite database but I'm getting these errors when I press the save button. IS This because I'm trying to create database in another activity rather than the MainActivity??
07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 E/SQLiteLog: (1) near "ENTER": syntax error
07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 D/AndroidRuntime: Shutting down VM
--------- beginning of crash
07-20 01:49:31.042 28795-28795/com.example.alkesh.expensemanager101 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alkesh.expensemanager101, PID: 28795
Theme: themes:{default=overlay:com.baranovgroup.nstyle, iconPack:com.baranovgroup.nstyle, fontPkg:com.baranovgroup.nstyle, com.android.systemui=overlay:com.baranovgroup.nstyle, com.android.systemui.navbar=overlay:com.baranovgroup.nstyle}
android.database.sqlite.SQLiteException: near "ENTER": syntax error (code 1): , while compiling: ENTER INTO money (name) VALUES ('25');
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:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.alkesh.expensemanager101.AddMoney.insertIntoDatabase(AddMoney.java:95)
at com.example.alkesh.expensemanager101.AddMoney.onClick(AddMoney.java:63)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
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)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
Here's my code for the AddMoney Activity
package com.example.alkesh.expensemanager101;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddMoney extends AppCompatActivity implements View.OnClickListener{
Button Save,Cancel;
EditText expText;
int[] expense=new int[100];
int temp=900;
int c=0;
int sum=0;
String DBOnce;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money);
expText=(EditText)findViewById(R.id.expense);
Cancel=(Button)findViewById(R.id.cancelbutton);
Cancel.setOnClickListener(this);
Save = (Button)findViewById(R.id.savebutton);
Save.setOnClickListener(this);
CreateDatabase();
}
#Override
public void onClick(View view) {
if(view== Save){
insertIntoDatabase();
}
if(view==Cancel){
Intent intent =new Intent(AddMoney.this,MainActivity.class);
startActivity(intent);
finish();
}
}
protected void CreateDatabase(){
db=openOrCreateDatabase("MoneyDB", Context.MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS money(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR);");
}
protected void insertIntoDatabase(){
String amount = expText.getText().toString().trim();
if(amount.equals("")){
Toast.makeText(this,"Please enter your expense or press Cancel to go back",Toast.LENGTH_LONG).show();
return;
}
String query="ENTER INTO money (name) VALUES ('"+amount+"');";
db.execSQL(query);
Toast.makeText(this,"Expense Saved",Toast.LENGTH_LONG).show();
}
}
Here's my code for MainActivity.
package com.example.alkesh.expensemanager101;
import android.content.Intent;
import android.os.Parcelable;
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.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button Add;
TextView expense;
int c=0;
String DBonce="0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add = (Button) findViewById(R.id.addbutton);
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddMoney.class);
intent.putExtra("counter", DBonce);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menuhome,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.feedback:{}
break;
case R.id.exit: finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
In AddMoney Activity function insertIntoDatabase() change your query Enter to INSERT

Categories

Resources