This is the code for getting the table RECORD from the SQLiteDatebase. In the try block something goes wrong and it always throws the SQLiteException. All I am trying to do here is to convert each row of the table "RECORD" into a string and add it to an ArrayList, subsequently connect the array to the ArrayAdapter, and finally use ListView to display the array.
package com.example.tommy.stop_watch_real;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import java.util.ArrayList;
public class RecordList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_list);
ListView temp = (ListView) findViewById(R.id.recordList);
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
**try {
SQLiteOpenHelper dataBaseHelper = new DataBaseHelper(this);
SQLiteDatabase db = dataBaseHelper.getReadableDatabase();
Cursor cursor = db.query("RECORD", new String[] {"_id, DATE, MINUTES"}, null, null,null,null,null);
while (cursor.moveToFirst()){
String id = Integer.toString(cursor.getInt(0));
String date = cursor.getString(1);
String minutes = Integer.toString(cursor.getInt(2));
String finalValue = id + "|" + date + "|" + minutes;
arrayList.add(finalValue);
}
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList);
temp.setAdapter(adapter);
cursor.close();
db.close();}**
catch (SQLiteException e) {
Toast.makeText(RecordList.this, "Database not available", Toast.LENGTH_LONG).show();
}
}
}
This is the code for my datebaseHelper:
class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Record"; // name of the database
private static final int DB_VERSION = 1; //Version
DataBaseHelper (Context context){
super(context, DB_NAME, null, DB_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE RECORD ("
+ "_id INTEGER PRIMARY KEY AUTOINCERMENT, "
+ "DATE STRING," //careful
+ "MINUTES INTEGER" + ");"
);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//no need to worry about this yet.
}
}
The toast always shows up, meaning something is wrong in the try block. I just started android development a week ago and I don't know what went wrong in my code. It would be great if you could give me some direction.
Thank you in advance.
This part seems wrong to me.
while (cursor.moveToFirst()){
String id = Integer.toString(cursor.getInt(0));
String date = cursor.getString(1);
String minutes = Integer.toString(cursor.getInt(2));
String finalValue = id + "|" + date + "|" + minutes;
arrayList.add(finalValue);
}
I am not sure what you are trying to achieve but the right way to get data from data base is like this:
cursor.moveToFirst()
while (cursor.isAfterLast()){
String id = Integer.toString(cursor.getInt(0));
String date = cursor.getString(1);
String minutes = Integer.toString(cursor.getInt(2));
String finalValue = id + "|" + date + "|" + minutes;
arrayList.add(finalValue);
}
Related
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));
}
}
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!
i try to save current date values when button get clicked....i use DBAdapter for save parameters to sqlite and it was fine when used for 2 fields like example of DBAdapter but when i edited DBAdapter for 6 fields this doesnt work.where is my problem?
DBAdapter.java
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_YEAR = "year";
public static final String KEY_MONTH = "month";
public static final String KEY_DAY = "day";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String KEY_SECOND = "second";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_YEAR, KEY_MONTH, KEY_DAY, KEY_HOUR, KEY_MINUTE, KEY_SECOND};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo12";
public static final String DATABASE_TABLE = "mainToDo12";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_YEAR + " TEXT NOT NULL, "
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
+ KEY_SECOND + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String year, String month,String day, String hour,String minute,String second) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_YEAR, year);
initialValues.put(KEY_MONTH, month);
initialValues.put(KEY_DAY, day);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
initialValues.put(KEY_SECOND, second);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String year, String month,long day, String hour, String minute,long second) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MONTH, month);
newValues.put(KEY_DAY, day);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MINUTE, minute);
newValues.put(KEY_SECOND, second);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity.java
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.view.View;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button plus;
int second,minute,houre,day,mounth,year;
DBAdapter mDb = new DBAdapter(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ViewGroup.LayoutParams superparams =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout table = new LinearLayout(this);
plus = new Button(this);
plus.setText("+");
table.addView(plus);
setContentView(table);
plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Calendar c = Calendar.getInstance();
second = c.get(Calendar.SECOND);
minute = c.get(Calendar.MINUTE);
houre = c.get(Calendar.HOUR);
day = c.get(Calendar.DAY_OF_MONTH);
mounth = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
mDb.open();
mDb.insertRow(Integer.toString(year), Integer.toString (mounth),Integer.toString(day), Integer.toString(houre),Integer.toString(minute), Integer.toString(second));
mDb.close();
mDb.open();
Cursor g=mDb.getRow(2);
DisplayContact(g);
mDb.close();
}
});
}
public void DisplayContact(Cursor c)
{
Toast.makeText(this,"id: "+c.getString(0)+"\n"+
"year: "+c.getString(1)+"\n"+
"month: "+c.getString(2),
Toast.LENGTH_LONG).show();
}
}
You're missing commas , between your column specifications here:
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
After adding the missing commas, either uninstall your app or increment the schema version to get the table recreated.
I feel like this is a really simple fix but I am new the android and sqlite in general. I have a array that takes data from a database and then shows them in a list. However every time I restart the app the list adds the items once again into the list. How can I make it not do this?
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.assignmenttracker.MySQLiteHelper;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
private ListView ListView;
private Button addbutton;
public final static String ID_EXTRA="com.example.assignmenttracker._ID";
public static ArrayList<String> ArrayofName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.addbutton = (Button)this.findViewById(R.id.button1);
this.addbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this, AddAssign.class);
startActivity(intent);
}
});
}
private void populateListView() {
MySQLiteHelper db = new MySQLiteHelper(this);
List<tasklist> contacts = db.getSometasklist();
for (tasklist cn : contacts) {
Log.d("Reading: ", "Reading all contacts..");
String log = "Id: "+cn.getID()+" ,Task: " + cn.getTask() + " ,Date: " + cn.getDate() + " ,Status: " + cn.getStatus();
Log.d("Name: ", log);
}
ListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
ListView.setAdapter(adapter);
ListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(MainActivity.this, ViewAssign.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);}
});
}
#Override
public void onResume() {
super.onResume();
populateListView();
}
}
here is the code of mysqlitehelper
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Contacts Table Columns names
private static final String TABLE_CONTACTS = "tasklist1";
private static final String KEY_ID = "id";
private static final String KEY_TASK = "task";
private static final String KEY_DESC = "desc";
private static final String KEY_MOD = "module";
private static final String KEY_DATE = "date";
private static final String KEY_TYPE = "type";
private static final String KEY_STATUS = "status";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "tasklist1";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TASKLIST_TABLE = "CREATE TABLE tasklist1 ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"task TEXT, "+
"desc TEXT, "+
"module TEXT, "+
"date TEXT, "+
"type TEXT, "+
"status INTEGER )";
db.execSQL(CREATE_TASKLIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older task list table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// create fresh task list table
this.onCreate(db);
}
public void insertTask(tasklist tasklist){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, tasklist.getTask());
values.put(KEY_DESC, tasklist.getDesc());
values.put(KEY_MOD, tasklist.getModule());
values.put(KEY_DATE, tasklist.getDate());
values.put(KEY_TYPE, tasklist.getType());
values.put(KEY_STATUS, tasklist.getStatus());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public List<tasklist> getAlltasklist(int passedid) {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS +
" where id = " + passedid;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDesc(cursor.getString(2));
contact.setModule(cursor.getString(3));
contact.setDate(cursor.getString(4));
contact.setType(cursor.getString(5));
contact.setStatus(cursor.getInt(6));
String name = cursor.getString(1);
String desc =cursor.getString(2);
String module =cursor.getString(3);
String date = cursor.getString(4);
String type = cursor.getString(5);
int status = cursor.getInt(6);
ViewAssign.task= name;
ViewAssign.desc=desc;
ViewAssign.module=module;
ViewAssign.date=date;
ViewAssign.type=type;
ViewAssign.status=status;
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public List<tasklist> getSometasklist() {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDate(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(4);
MainActivity.ArrayofName.add(name);
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public void deleteTask(long row) {
// Deletes a row given its rowId, but I want to be able to pass
// in the name of the KEY_NAME and have it delete that row.
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=" + row, null);
db.close();
}
}
I suspect the culprint is this:
public static ArrayList<String> ArrayofName = new ArrayList<String>();
It is a static variable, meaning that in some circumstances, it will STILL have the objects you added on app first run when you run it second time.
Possible solutions:
remove "static" keyword, or
clear ArrayOfName before populating it, eg. ArrayOfName.clear()
I know I am late but maybe it will help someone else.
You need to split ArrayList into two parts
Place the following code in MainActivity
public static ArrayList<String> ArrayofName;
And place the following in onCreate() OR onResume() method
ArrayofName = new ArrayList<String>();
I am trying to update current credits column of the only row in the database using a drop down spinner which gets values from an arraylist. Very unsure about how to go about doing this operation. Thank you for any help in advance.
My database code:
package com.example.parkangel;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " TEXT NOT NULL, " + KEY_CREDITS + " TEXT
NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
}
My main activity code I will be doing the operation through:
package com.example.parkangel;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class Balance extends Activity{
Button add;
TextView display;
Spinner spinner3;
String[] money = {"Select amount", "£1", "£2", "£5", "£10"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
db.close();
tv.setText(data);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
Your question is fairly compound, getting selected field from spinner, updating database... I'm not going to provide a complete answer, but this should get you started:
This is how you would get the selected field from the spinner, which you can then use to update your database. One word of warning, I believe setOnItemSelectedListener is called when it is initially set, so you may need to ignore the first call.
Spinner spinner;
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2,
long arg3) {
if(! (view instanceof TextView)){
// view is probably a textview, but record type if not.
System.out.println("incorrect view type " + view.getClass().getSimpleName());
return;
}
EditText et = (EditText) view;
String fieldName = et.getText().toString().trim();
//Now we got selected name, send name
//to a function that updates our database.
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I didn't find the problem but I can tell you that your code is VERY INEFFICIENT. You are using String to build your result in the getData method. Each time you try to append the new data (Row) to the old one you are creating a new string to hold the new data. If you are retrieving 1000 row from the database, this means that you are creating 1000 string to build the final one. I recommend using StringBuilder instead as following:
StringBuilder strBuilder= new StringBuilder();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
strBuilder.append( c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n");
}
return str= strBuilder.toString();
Here is an example of how to insert into your DB:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PFNAME , editText1.getText().toString());
values.put(KEY_PSNAME , stringArrayList.get(position));
values.put(KEY_CARD , "12345677");
values.put(KEY_CREDITS , "55");
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
db.close(); // Closing database connection