SQL database in android , Index -1 requested with size 0 - java

I have been working on an android app which requires to retrieve some information from the SQL database. Initially I was trying to do that form a function named getRemainingAmount() in databaseHelper1 class but that caused an error
FATAL EXCEPTION: main Process: com.carrot.wallet, PID: 30591 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.wallet/com.carrot.wallet.MainActivity}: android.view.InflateException: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Error inflating class fragment at
After that when I tried to ritrive data from the addTransaction class then I started getting the folowing error:
2020-05-30 09:25:12.946 11239-11239/com.carrot.wallet E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.carrot.wallet, PID: 11239
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.carrot.wallet.AddTransaction$4.onClick(AddTransaction.java:102)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
This is my databaseHeleper1 class which contains the function getRemainingAmount()
package com.carrot.wallet.Database;
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 androidx.annotation.Nullable;
public class DatabaseHelper1 extends SQLiteOpenHelper {
private static final int version = 3;
private static final String name = "YEAR_DETAILS";
private static final String COL0 = "YEAR";
private static final String COL1 = "MONTH";
private static final String COL2 = "SPENT";
private static final String COL3 = "REMAINING";
private static final String TAG = "Database Helper 1";
public DatabaseHelper1(#Nullable Context context) {
super(context, name, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG , "Database 1 is being created");
String create_table = "CREATE TABLE "+name+"("+
COL0+" INTEGER, "+
COL1+" TEXT, "+
COL2+" DOUBLE, "+
COL3+" DOUBLE);";
db.execSQL(create_table);
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+name);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private boolean createMonth(String month , String year){
Log.d(TAG , "month row is being created");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL0 , year);
contentValues.put(COL1 , month);
contentValues.put(COL2 , 0.0);
contentValues.put(COL3 , 0.0);
long result = db.insert(name,null , contentValues);
return result != -1;
}
public boolean spentChange(String month , String year , Double newAmount){
Log.d(TAG , "spent amount is being changed");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL2 , newAmount);
long result = db.update(name, values , "MONTH = ? AND YEAR = ?", new String[]{month , year});
return result != -1;
}
public boolean remainingChange(String month ,String year, Double newAmount){
Log.d(TAG , "Remaining amount is being changed");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues =new ContentValues();
contentValues.put(COL3 , newAmount);
long result = db.update(name , contentValues , "MONTH = ? AND YEAR = ?" , new String[]{month , year});
return result != -1;
}
public void checkExistance(String month, String year){
Log.d(TAG , "Checking if month already exits");
SQLiteDatabase database = this.getWritableDatabase();
Cursor cur = database.query(name , null , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
System.out.println(cur);
if(cur.getCount() <= 0) {
boolean b = createMonth(month , year);
if(b)
Log.d(TAG , "checkExistance: failed to create month");
else
Log.d(TAG, "checkExistance: month created successfully");
}
}
public Cursor getdata(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM YEAR_DETAILS;";
return db.rawQuery(query , null);
}
public Cursor getSpentAmount(String month , String year){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
return db.rawQuery(query , null);
}
public Cursor getRemainingAmount(String month , String year){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.query(name , new String[]{COL3} , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
return cur;
}
}
AddTransaction class (where i am retrieving the data)
package com.carrot.wallet;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import com.carrot.wallet.ArrayListClasses.add_transaction_data;
import com.carrot.wallet.Database.DatabaseHelper1;
import com.carrot.wallet.Database.DatabaseHelper2;
import com.carrot.wallet.recyclerview.at_btn_adapter;
import java.util.ArrayList;
import java.util.Calendar;
import com.carrot.wallet.recyclerview.onClickRecyclerButtion;
public class AddTransaction extends AppCompatActivity {
int type1 ;
int type2;
double amount;
ArrayList<add_transaction_data> data;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_transaction);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
populateList();
final ImageButton cancel = findViewById(R.id.at_btn_cancel);
final EditText EditAmount = findViewById(R.id.at_enter_amount);
ImageButton save = findViewById(R.id.at_btn_save);
ImageButton income = findViewById(R.id.at_btn_income);
ImageButton loan = findViewById(R.id.at_btn_loan);
RecyclerView recyclerView = findViewById(R.id.at_btn_recyclerview);
recyclerView.setLayoutManager(new GridLayoutManager(this , 5));
recyclerView.setAdapter(new at_btn_adapter(data, new onClickRecyclerButtion() {
#Override
public void onPositionClicked(int position) {
type1 = 2;
type2 = position;
}
}));
income.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
type1 = 1;
type2 = -1;
}
});
loan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
type1 = 1;
type2 = -2;
}
});
context = this;
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("it is all cool here");
DatabaseHelper1 databaseHelper1 = new DatabaseHelper1(getBaseContext());
DatabaseHelper2 databaseHelper2 = new DatabaseHelper2(getBaseContext());
double amount = Double.parseDouble(EditAmount.getText().toString());
System.out.println(amount);
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
String m = changeString(month);
System.out.println(type1);
String mRamount = "ds";
if(type1 == 1){
SQLiteDatabase database = databaseHelper1.getReadableDatabase();
String ca = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
Cursor cursor = database.rawQuery(ca , null);
mRamount = cursor.getString(1);
System.out.println(mRamount);//printing amount.
}
startActivity(new Intent(AddTransaction.this , MainActivity.class));
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(AddTransaction.this , MainActivity.class));
}
});
}
void populateList(){
data = new ArrayList<>();
data.add(new add_transaction_data("Add" , R.drawable.ic_add_black_24dp));
data.add(new add_transaction_data("Shopping" , R.drawable.at_ic_shopping));
data.add(new add_transaction_data("Food" , R.drawable.at_ic_food));
data.add(new add_transaction_data("Traveling" , R.drawable.at_ic_travel));
data.add(new add_transaction_data("Education" , R.drawable.at_ic_education));
data.add(new add_transaction_data("Energy" , R.drawable.at_ic_energy));
data.add(new add_transaction_data("House" , R.drawable.at_ic_home));
data.add(new add_transaction_data("Fitness" , R.drawable.at_ic_sports));
data.add(new add_transaction_data("Personal" , R.drawable.at_ic_personal));
data.add(new add_transaction_data("Other" , R.drawable.at_ic_other));
}
String changeString(int month){
String m;
switch (month){
case 0:
m = "January";
break;
case 1:
m = "Feburary";
break;
case 2:
m = "March";
break;
case 3:
m = "April";
break;
case 4:
m = "May";
break;
case 5:
m = "June";
break;
case 6:
m = "July";
break;
case 7:
m = "August";
break;
case 8:
m = "September";
break;
case 9:
m = "October";
break;
case 10:
m = "November";
break;
case 11:
m = "December";
break;
default:
m = " ";
}
return m;
}
}
activity_main xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="#+id/fragNavHost"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/mobile_navigation" />
<me.ibrahimsn.lib.SmoothBottomBar
android:elevation="30dp"
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
app:iconTint="#color/colorPrimary"
app:indicatorColor="#EFEFEF"
app:iconTintActive="#color/colorPrimaryDark"
app:textColor="#color/colorPrimaryDark"
android:layout_height="70dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_navigation_bar"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Can someone help me understand what is causing these two errrors.

in your getData() method you have double semicolon
String query = "SELECT * FROM YEAR_DETAILS;";
try changing it to
String query = "SELECT * FROM YEAR_DETAILS"
and I suggest you migrate to Room library

Related

Using integer value to get SQLite database table row data of row index in order to display said data in textviews in new activity

I am trying to display my FLIGHTS table row data depending on the index in a activity using textviews. How do I get the index of the table row and display the table rows columns in textviews in an activity.
Here is my activity where I am trying to display the data in textviews:
package com.example.shashank.fffffffffffffffffffffffffff;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class BookingActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
textView = findViewById(R.id.textView);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
textView.setText(Integer.toString(intValue));
}
}
the intValue variable I am getting from another activity which represents the position being clicked on a listview.
I am then trying to use that variable to display the row index of the FLIGHTS table into textviews.
Here is my DBHelper class:
package com.example.shashank.fffffffffffffffffffffffffff;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "Login.db";
public static final String FLIGHTS = "FLIGHTS";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_DESTINATION = "DESTINATION";
public static final String COLUMN_PRICE = "PRICE";
public static final String COLUMN_DEPARTURE_TIME = "DEPARTURE_TIME";
public static final String COLUMN_ARRIVAL_TIME = "ARRIVAL_TIME";
public static final String COLUMN_DURATION = "DURATION";
public static final String COLUMN_AVAILABLE_SEATS = "AVAILABLE_SEATS";
public DBHelper(Context context) {
super(context, "Login.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase MyDB) {
String createTable1 = "create Table users(username TEXT primary key, password TEXT)";
MyDB.execSQL(createTable1);
MyDB.execSQL("CREATE TABLE " + FLIGHTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_DESTINATION + " TEXT, " + COLUMN_PRICE + " REAL, " + COLUMN_DEPARTURE_TIME + " TEXT, " + COLUMN_ARRIVAL_TIME + " TEXT, " + COLUMN_DURATION + " TEXT, " + COLUMN_AVAILABLE_SEATS + " INTEGER )");
ContentValues insertValues = new ContentValues();
insertValues.put(COLUMN_DESTINATION, "Cape Town");
insertValues.put(COLUMN_PRICE, 500);
insertValues.put(COLUMN_DEPARTURE_TIME, "1200");
insertValues.put(COLUMN_ARRIVAL_TIME, "1400");
insertValues.put(COLUMN_DURATION, "2");
insertValues.put(COLUMN_AVAILABLE_SEATS, 10);
MyDB.insert(FLIGHTS, null, insertValues);
ContentValues insertValues2 = new ContentValues();
insertValues2.put(COLUMN_DESTINATION, "Johannesburg");
insertValues2.put(COLUMN_PRICE, 1000);
insertValues2.put(COLUMN_DEPARTURE_TIME, "1400");
insertValues2.put(COLUMN_ARRIVAL_TIME, "1600");
insertValues2.put(COLUMN_DURATION, "2");
insertValues2.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues2);
}
#Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
MyDB.execSQL("drop Table if exists users");
MyDB.execSQL("drop Table if exists " + FLIGHTS);
onCreate(MyDB);
}
public Boolean insertData(String username, String password){
SQLiteDatabase MyDB = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put("username", username);
contentValues.put("password", password);
long result = MyDB.insert("users", null, contentValues);
if(result==-1) return false;
else
return true;
}
public Boolean checkusername(String username) {
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from users where username = ?", new String[]{username});
if (cursor.getCount() > 0)
return true;
else
return false;
}
public Boolean checkusernamepassword(String username, String password){
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from users where username = ? and password = ?", new String[] {username,password});
if(cursor.getCount()>0)
return true;
else
return false;
}
public List<FlightsModel> getEveryone(){
List<FlightsModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + FLIGHTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
do {
int id = cursor.getInt(0);
String destination = cursor.getString(1);
double price = cursor.getDouble(2);
String departure = cursor.getString(3);
String arrival = cursor.getString(4);
String duration = cursor.getString(5);
int space = cursor.getInt(6);
FlightsModel newFlight = new FlightsModel(id, destination, price, departure, arrival, duration, space);
returnList.add(newFlight);
}while (cursor.moveToNext());
}
else{
}
cursor.close();
db.close();
return returnList;
}
}
add the following method to the DBHelper class
:-
#SuppressLint("Range") // suppress Bug/issue with getColumnIndex
public FlightsModel getFlightById(int id) {
FlightsModel rv;
SQLiteDatabase db = this.getWritableDatabase();
// Uses the query convenience method rather than raw query
Cursor csr = db.query(FLIGHTS,null,COLUMN_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = new FlightsModel(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_DESTINATION)),
csr.getDouble(csr.getColumnIndex(COLUMN_PRICE)),
csr.getString(csr.getColumnIndex(COLUMN_DEPARTURE_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_ARRIVAL_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_DURATION)),
csr.getInt(csr.getColumnIndex(COLUMN_AVAILABLE_SEATS))
);
} else {
rv = new FlightsModel();
}
csr.close();
// No need to close the database (inefficient to keep opening and clsoing db)
return rv;
}
note that getWritableDatabase has been used, it doesn't really matter which is used as getReadableDatabase will, unless the database can only be read, get a writeable database. i.e. getReadableDatabase will not protect against writes.
it is better to use getColumnIndex than hard code column indexes. Thus irrespective of the position of the column the column will be found, thus reducing potential maintenance issues.
Change the BookingActivity to retrieve the respective FlightsModel
:-
public class BookingActivity extends AppCompatActivity {
TextView textView;
DBHelper dbHelper; //<<<<< ADDED
FlightsModel flightsModel; //<<<<< ADDED
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
dbHelper = new DBHelper(this); //<<<<< ADDED
textView = findViewById(R.id.textView);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
flightsModel = dbHelper.getFlightById(intValue); //<<<<< get the flightModel from the database
if (flightsModel.id > 1) {
// set the appropriate textviews
} else {
// do something here to indicate no FlightsModel found in database
}
textView.setText(Integer.toString(intValue));
}
}

How to show records from sqlite database on my app in a listview

I'm creating an app for doctor's appointment.. So I want to see the booked appointments records in the listview for different activities with a delete button to delete a specific record..
this is my code for making appointments...
that is Appo.java
package com.example.medilyf;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class Appo extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet, confirm, seeappo;
TextView tvw, text, receiver_msg;
DBHelper myDB;
CheckBox android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appo);
tvw = findViewById(R.id.textView1);
eText = findViewById(R.id.editText1);
myDB = new DBHelper(Appo.this);
android = findViewById(R.id.checkBox);
angular = findViewById(R.id.checkBox1);
java = findViewById(R.id.checkBox2);
python = findViewById(R.id.checkBox3);
text = findViewById(R.id.txt);
Button btn = findViewById(R.id.getbtn);
receiver_msg =findViewById(R.id.textView5);
// create the get Intent object
Intent intent = getIntent();
String str = intent.getStringExtra("dr_name");
// display the string into textView
receiver_msg.setText(str);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(Appo.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet = findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt = eText.getText().toString();
tvw.setText(txt);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result ="";
if (android.isChecked()) {
result += "\n9:00 - 10:30";
}
if (angular.isChecked()) {
result += "\n10:30 -11:30";
}
if (java.isChecked()) {
result += "\n11:30 -12:30";
}
if (python.isChecked()) {
result += "\n2:00 - 3:00";
}
text.setText(result);
}
});
confirm = findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = text.getText().toString();
String date = tvw.getText().toString();
if (str.equals("")) {
Toast.makeText(Appo.this, "Blank values", Toast.LENGTH_SHORT).show();
} else {
boolean booking = myDB.insertData2(str, time, date);
if (booking) {
Toast.makeText(Appo.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Appo.this, "Booking not confirmed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox:
str = checked?"9:00 - 10:30 Selected":"9:00 - 10:30 Deselected";
break;
case R.id.checkBox1:
str = checked?"10:30 -11:30 Selected":"10:30 -11:30 Deselected";
break;
case R.id.checkBox2:
str = checked?"11:30 -12:30 Selected":"11:30 -12:30 Deselected";
break;
case R.id.checkBox3:
str = checked?"2:00 - 3:00 Selected":"2:00 - 3:00 Deselected";
break;
}
Toast.makeText(Appo.this, str, Toast.LENGTH_SHORT).show();
}
}
This is the code for sqlite database... that is DBHelper.java
package com.example.medilyf;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
public static final String col1="name";
public static final String col2="username";
public static final String col3="email";
public static final String col4="PhoneNo";
public static final String col5="password";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String col6="Appointment_id ";
public static final String col7="full_Name ";
public static final String col9="Doc_name ";
public static final String col12="ATime ";
public static final String col8="Phone_Number";
public DBHelper(#Nullable Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(name Text, username Text primary key, email Text, PhoneNo Text, password Text)");
myDB.execSQL("create table appo(Dr Text,time Text, date Text)");
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
myDB.execSQL("Drop Table if exists users");
myDB.execSQL("Drop Table if exists appo");
}
public boolean insertData(String name, String username, String email, String PhoneNo, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1,name);
contentValues.put(col2,username);
contentValues.put(col3,email);
contentValues.put(col4,PhoneNo);
contentValues.put(col5,password);
long result = myDB.insert("users",null,contentValues);
return result != -1;
}
public boolean insertData2(String Dr, String time, String date){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Dr",Dr);
contentValues.put("time",time);
contentValues.put("date",date);
long result = myDB.insert("appo",null,contentValues);
return result != -1;
}
public boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?", new String[] {username});
return cursor.getCount() > 0;
}
public boolean checkusernamepassword(String username, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?", new String[] {username,password});
return cursor.getCount() > 0;
}
}
Can anyone help me with the code to retrieve and display the records of the appointment for another activity in list view..???

no such table: reward (code 1): , while compiling: INSERT INTO reward(Reward2,Reward1,Reward3) VALUES (?,?,?)

Hello I'm a student and doing my final year project using sql and android studio. I want to create multiple table and I've trying to follow the example but it doesn't work. the error was no table created. Here my coding
DatabaseHelper.java
package com.example.multipletable;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import androidx.annotation.Nullable;
import static android.content.ContentValues.TAG;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MultipleTable";
private static final int DATABASE_VERSION = 3;
private static final String TABLE_1 = "register";
private static final String TABLE_2 = "activity";
private static final String TABLE_3 = "reward";
String table_1 = "CREATE TABLE "+TABLE_1+" (matricno TEXT PRIMARY KEY, password TEXT, email TEXT)";
String table_2 = "CREATE TABLE "+TABLE_2+" (id INTEGER PRIMARY KEY AUTOINCREMENT, t_question TEXT, date DEFAULT CURRENT_DATE)";
String table_3 = "CREATE TABLE "+TABLE_3+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, badge_green TEXT, badge_purple TEXT, badge_maroon TEXT)";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(table_1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Current version"+db.getVersion());
for (int version=oldVersion+1; version<=newVersion; version++) {
switch (version) {
case 2:
db.execSQL(table_2);
case 3:
db.execSQL(table_3);
}
}
// Log.e("DATABASE VERSION", db.getVersion()+" ");
//
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_1);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_2);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_3);
//
// onCreate(db);
}
public boolean insert(String matNo, String pswd, String email) {
SQLiteDatabase db_1 = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put("MatricNo", matNo);
contentValues1.put("Password", pswd);
contentValues1.put("Email", email);
db_1.insert(TABLE_1, null, contentValues1);
return true;
}
public boolean insert2(String question) {
SQLiteDatabase db_2 = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put("Question", question);
contentValues2.put("Date", getDate());
db_2.insert(TABLE_2, null, contentValues2);
return true;
}
public boolean insert3(String green, String purple, String maroon) {
SQLiteDatabase db_3 = this.getWritableDatabase();
ContentValues contentValues3 = new ContentValues();
contentValues3.put("Reward1", green);
contentValues3.put("Reward2", purple);
contentValues3.put("Reward3", maroon);
db_3.insert(TABLE_3, null, contentValues3);
return true;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
MainActiviti.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name, pswd, email;
Button btn_1;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.txt_name);
pswd = findViewById(R.id.txt_password);
email = findViewById(R.id.txt_email);
btn_1 = findViewById(R.id.btn_next_1);
db = new DatabaseHelper(this);
btn_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String person = name.getText().toString();
String pass = pswd.getText().toString();
String mail = email.getText().toString();
Boolean insert = db.insert(person, pass, mail);
if (insert==true) {
Toast.makeText(getApplicationContext(), "Data 1 saved", Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
startActivity(intent1);
}
else {
Toast.makeText(getApplicationContext(), "Data 1 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity2.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity2 extends AppCompatActivity {
EditText question;
Button btn2;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
question = findViewById(R.id.txt_question);
btn2 = findViewById(R.id.btn_next_2);
db = new DatabaseHelper(this);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ques = question.getText().toString();
Boolean insert2 = db.insert2(ques);
if (insert2==true) {
Toast.makeText(getApplicationContext(), "Data 2 saved", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Activity2.this, Activity3.class);
startActivity(intent2);
}
else {
Toast.makeText(getApplicationContext(), "Data 2 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity3.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity3 extends AppCompatActivity {
EditText green, purple, maroon;
Button btn3;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
green = findViewById(R.id.txt_green);
purple = findViewById(R.id.txt_purple);
maroon = findViewById(R.id.txt_maroon);
btn3 = findViewById(R.id.btn_next_3);
db = new DatabaseHelper(this);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String grn = green.getText().toString();
String ppl = purple.getText().toString();
String mrn = maroon.getText().toString();
Boolean insert3 = db.insert3(grn, ppl, mrn);
if (insert3==true) {
Toast.makeText(getApplicationContext(), "Data 3 saved", Toast.LENGTH_SHORT).show();
Intent intent3 = new Intent(Activity3.this, FINISH.class);
startActivity(intent3);
}
else {
Toast.makeText(getApplicationContext(), "Data 3 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Can you please help me find the solution and tell me what is wrong :(
I am not sure where your error comes from but, I am assuming its on launch or when you insert the data.
I create my SQL table like below.
However, I did encounter a really annoying issue of if I change my table my app would crash as it would not find it. The fix was I needed to uninstall the app on my phone before uploading the application from android studio to my phone. Hope it helps
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="TESTING.db";
// Database Version
private static final int DATABASE_VERSION = 1;
public static final String TABLE_1 = "T1";
public static final String TABLE_2 = "T2";
public static final String TABLE_3 = "T3";
public static final String COL1 = "ID";
public static final String COL2 = "D1";
public static final String COL3 = "D2";
public static final String COL4 = "D3";
public static final String COL5 = "D4";
public static final String COL6 = "D5";
public static final String COL7 = "D6";
public static final String COL8 = "time";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
String Created_TABLE_1= "CREATE TABLE " + TABLE_1 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_2= "CREATE TABLE " + TABLE_2 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_3= "CREATE TABLE " + TABLE_3 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
db.execSQL(Created_TABLE_1);
db.execSQL(Created_TABLE_2);
db.execSQL(Created_TABLE_3);
}
Ps Stay safe all
Thank you Eugene Troyanskii, forpas and Thomas Morris. I've solved the problem. Supposed to be assign with correct name for column according to create table statement at inserting data code, but I write it different.
Again thanks guys!

Creating a GraphView with date as X axis from SQLite [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to create a graph from my sqlite values for example here Date vs Weight. Later on I will add Date vs Fat etc. But the apps forced close by the phone with these Logcat:
08-19 21:58:50.313 25858-25858/example.christopher.bd E/AndroidRuntime: FATAL EXCEPTION: main Process: example.christopher.bd, PID: 25858 java.lang.RuntimeException: Unable to start activity ComponentInfo{example.christopher.bd/example.christopher.bd.VIewGraph}: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference at com.jjoe64.graphview.series.DataPoint.(DataPoint.java:45) at example.christopher.bd.VIewGraph.onCreate(VIewGraph.java:48) at android.app.Activity.performCreate(Activity.java:7136) at android.app.Activity.performCreate(Activity.java:7127) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
activity to show the graph:
package example.christopher.bd;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class VIewGraph extends AppCompatActivity {
LineGraphSeries<DataPoint> series;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_graph);
mDatabaseHelper = new DatabaseHelper(this);
String y;
Float z;
Date d1;
Cursor data = mDatabaseHelper.readEntry();
int rows = data.getCount();
data.moveToFirst();
GraphView graph = (GraphView) findViewById(R.id.graph11);
series = new LineGraphSeries<DataPoint>();
for(int i = 0; i <rows; i++){
data.moveToNext();
String x = data.getString(2);
y = data.getString(3);
z = Float.parseFloat(y);
Date date1 = null;
try {
date1 = new SimpleDateFormat("dd/MM/yyyy").parse(x);
} catch (Exception e) {
e.printStackTrace();
}
series.appendData(new DataPoint(date1, z), true, 25);
}
graph.addSeries(series);
graph.getGridLabelRenderer().setNumHorizontalLabels(3);
graph.getGridLabelRenderer().setHumanRounding(false);
}
}
Here is the code for databasehelper
package example.christopher.bd;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.util.Calendar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class DatabaseHelper extends SQLiteOpenHelper{
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "BodyData";
private static final String COL1 = "ID";
private static final String COL2 = "tdate";
private static final String COL2a = "ttime";
private static final String COL3 = "weight";
private static final String COL4 = "fat";
private static final String COL5 = "hydration";
private static final String COL6 = "muscle";
private static final String COL7 = "bone";
//private static final String COL8 = "time";
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = " CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, tdate string, ttime string, weight float, fat float, hydration float, muscle float, bone float)";
//String createTable = " CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, tday integer, tmonth integer, tyear integer, weight float, fat float, hydration float, muscle float, bone float)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String tdate, String ttime, String weight, String fat, String hydration, String muscle, String bone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, tdate);
contentValues.put(COL2a, ttime);
contentValues.put(COL3, weight);
contentValues.put(COL4, fat);
contentValues.put(COL5, hydration);
contentValues.put(COL6, muscle);
contentValues.put(COL7, bone);
//contentValues.put(COL8, time);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
db.execSQL("delete from "+ TABLE_NAME);
db.close();
}
public Cursor readEntry(){
SQLiteDatabase db = this.getWritableDatabase();
String[] allColumns = new String[]{
DatabaseHelper.COL1,
DatabaseHelper.COL2,
DatabaseHelper.COL2a,
DatabaseHelper.COL3,
DatabaseHelper.COL4,
DatabaseHelper.COL5,
DatabaseHelper.COL6,
DatabaseHelper.COL7,
};
Cursor c = db.query(DatabaseHelper.TABLE_NAME, allColumns, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
activity to log the data (date, weight etc)
package example.christopher.bd;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class Logging extends AppCompatActivity {
private static final String TAG = "Logging";
DatabaseHelper mDatabaseHelper;
EditText editWeight, editFat, editHydration, editMuscle, editBone, editTime, editASD;
private Button button2;
private TextView mDisplayDate, mDisplayTime;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private TimePickerDialog.OnTimeSetListener mTimeSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logging);
button2 = (Button) findViewById(R.id.button2);
mDisplayDate = (TextView) findViewById(R.id.tvDate);
mDatabaseHelper = new DatabaseHelper(this);
mDisplayTime = (TextView) findViewById(R.id.tvTime);
editWeight = (EditText) findViewById(R.id.editWeight);
editFat = (EditText) findViewById(R.id.editFat);
editHydration = (EditText) findViewById(R.id.editHydration);
editMuscle = (EditText) findViewById(R.id.editMuscle);
editBone = (EditText) findViewById(R.id.editBone);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
Logging.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: mm/dd/yyyy: " + day + "/" + month + "/" + year);
String date = day + "/" + month + "/" + year;
mDisplayDate.setText(date);
}
};
mDisplayTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar mTime = Calendar.getInstance();
int mHour = mTime.get(Calendar.HOUR_OF_DAY);
int mMinute = mTime.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(Logging.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
mDisplayTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, true);
timePickerDialog.show();
}
});
LogData();
}
public void LogData(){
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = mDatabaseHelper.addData(
mDisplayDate.getText().toString(),
mDisplayTime.getText().toString(),
editWeight.getText().toString(),
editFat.getText().toString(),
editHydration.getText().toString(),
editMuscle.getText().toString(),
editBone.getText().toString()
);
if (isInserted == true)
Toast.makeText(Logging.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(Logging.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
});
}
}
Can anyone help me?
java.lang.NullPointerException: Attempt to invoke virtual method 'long
java.util.Date.getTime()' on a null object reference
means that you are calling/the code you are using is calling getTime() on a Date object that is null.
In more detail
Attempt to invoke virtual method 'long java.util.Date.getTime()' on a
null object reference at
com.jjoe64.graphview.series.DataPoint.(DataPoint.java:45) at
example.christopher.bd.VIewGraph.onCreate(VIewGraph.java:48)
means that this was initiated in VIewGraph.java on line 48.
Just above that there is a try-catch block to catch problems in parsing a date, but you don't check was the Date object non-null in the end. Any error is just ignored. You then feed this null Date object to series in series.appendData(new DataPoint(date1, z), true, 25);
A quick fix would be to change
try {
date1 = new SimpleDateFormat("dd/MM/yyyy").parse(x);
} catch (Exception e) {
e.printStackTrace();
}
series.appendData(new DataPoint(date1, z), true, 25);
..to...
try {
date1 = new SimpleDateFormat("dd/MM/yyyy").parse(x);
series.appendData(new DataPoint(date1, z), true, 25);
} catch (Exception e) {
e.printStackTrace();
}
It looks like you have made changes to the columns of the table (COL2a instead of COL8) If this is the case, did you uninstall the app from the device/emulator where you test it? If not you must.
The table schema dos not change every time you make changes in onCreate() of DatabaseHelper class. onCreate() is executed when the db does not exist.
Now a logical problem:
In your activity's onCreate() you execute:
data.moveToFirst();
So the cursor data is pointing at its 1st row.
Then in the 1st line of the for loop you execute:
data.moveToNext();
So the cursor data is pointing at its 2nd row (if there is a 2nd row).
So you miss the 1st row's data for sure.
But since the number of iterations is equal as the number of rows the last iteration will fetch null data!
Suggestion move data.moveToNext(); as the last statement of the for loop.

SQLite with android error

i am relatively new to programming and android,and i am working on a little notepad app. I learned how to use SQLite from a tutorial on the web,but something is wrong..when i am running the app,it keeps telling me that there are no columns in the name... but there are! what am i doing wrong? i checked the syntax a dozens of times,and i did it like the tutorial did one by one. I know this question was here before more than one time,but when reading the answers, i still couldnt find a solution to my specific problem. basically i just added 2 notes with title and text and wanted to present them in the main activity in a ListView,but nothing is showing up because of the database problem.
Help is very very appreciated :) thx in advance
this is the classes:
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseManager extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "notesDb";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "notes";
private static final String NOTE_ID = "_id";
private static final String NOTE_TITLE = "title";
private static final String NOTE_TEXT = "text";
private static final String NOTE_CREATION_DATE = "creationDate";
public DatabaseManager(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NOTES_TABLE = "CREATE TABLE "+TABLE_NAME+"(" + NOTE_ID +" INTEGER PRIMARY KEY,"+ NOTE_TITLE + "TEXT,"
+ NOTE_TEXT + "TEXT," + NOTE_CREATION_DATE + "TEXT" + ")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public void addNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NOTE_TITLE, note.getTitle());
values.put(NOTE_TEXT, note.getText());
values.put(NOTE_CREATION_DATE, note.getCurrentTime());
db.insert(TABLE_NAME, null, values);
db.close();
}
public void deleteNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, NOTE_ID + "?=",new String[]{String.valueOf(note.getId())} );
db.close();
}
public String[] listNotes(){
ArrayList<String> tempArray = new ArrayList<String>();
String[]notesArray = new String[0];
String sqlQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(sqlQuery,null);
if(c.moveToFirst()){
do{
tempArray.add(c.getString(c.getColumnIndex(NOTE_TITLE)));
}
while(c.moveToNext());
}
c.close();
notesArray = tempArray.toArray(notesArray);
return notesArray;
}
}
the note object:
import java.util.Calendar;
public class Note {
private int id;
private String text;
private String title;
private String creationTime;
private String currentTime;
public Note(){
}
public String getCurrentTime(){
return getDayOfMonth()+"/"+getMonth()+"/"+getYear()+" "+getDay()+", "+getHour()+":"+getMinutes();
}
public String getMonth(){
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
String month = new String();
switch(currentMonth){
case 0:
month = "01";
break;
case 1:
month = "02";
break;
case 3:
month = "04";
break;
case 4:
month = "05";
break;
case 5:
month = "06";
break;
case 6:
month = "07";
break;
case 7:
month = "08";
break;
case 8:
month = "09";
break;
case 9:
month = "10";
break;
case 10:
month = "11";
break;
case 11:
month = "12";
break;
}
return month;
}
public String getDayOfMonth(){
int currentDayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
String dayOfMonth = new String();
if(currentDayOfMonth<10){
dayOfMonth = "0"+currentDayOfMonth;
}
else{
dayOfMonth = ""+currentDayOfMonth;
}
return dayOfMonth;
}
public String getYear(){
String year = ""+Calendar.getInstance().get(Calendar.YEAR);
return year;
}
public String getDay(){
int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
String day = new String();
switch(currentDay){
case 1:
day = "Sun";
break;
case 2:
day = "Mon";
break;
case 3:
day = "Tue";
break;
case 4:
day = "Wed";
break;
case 5:
day = "Thu";
break;
case 6:
day = "Fri";
break;
case 7:
day = "Sat";
break;
}
return day;
}
public String getHour(){
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
String hour = new String();
if(currentHour<10){
hour = "0"+currentHour;
}
else{
hour = ""+currentHour;
}
return hour;
}
public String getMinutes(){
int currentMinutes = Calendar.getInstance().get(Calendar.MINUTE);
String minutes = new String();
if(currentMinutes<10){
minutes = "0"+currentMinutes;
}
else{
minutes = ""+currentMinutes;
}
return minutes;
}
public void setText(String text){
this.text = text;
}
public String getText(){
return this.text;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return this.id;
}
}
the main activity:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseManager db = new DatabaseManager(this);
Note n1 = new Note();
Note n2 = new Note();
n1.setTitle("n1 title");
n1.setText("n1 text");
n2.setTitle("n2 title");
n2.setText("n2 text");
db.addNote(n1);
db.addNote(n2);
String[]notes = db.listNotes();
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,notes);
ListView lv = (ListView)findViewById(R.id.notes_list);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and the xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/board"
android:scaleType="fitXY"/>
<ImageButton
android:id="#+id/add_note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:src="#drawable/note"
android:background="#android:color/transparent"/>
<ListView
android:id="#+id/notes_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"/>
A semi colon inside the query is missing for your table creation string CREATE_NOTES_TABLE string. Include a semicolon (;) inside the string just after the final ")"; ie. Make it ");";

Categories