I wanted to play with a ContentProvider example but I ran into an issue I can't seem to solve.
This example consists of an Activity:
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity
{
final String LOG_TAG = "myLogs";
final Uri CONTACT_URI = Uri.parse("content://zulfigarov.com.trainingprj.MyContactsProvider/contacts");
final String CONTACT_NAME = "name";
final String CONTACT_EMAIL = "email";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor cursor = getContentResolver().query(CONTACT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {"name", "email"};
int[] to = {android.R.id.text1, android.R.id.text2};
SimpleCursorAdapter adapter
= new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to, 0);
ListView lvContact = (ListView)findViewById(R.id.lvContacts);
lvContact.setAdapter(adapter);
}
public void onClickInsert(View view)
{
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, "name 4");
cv.put(CONTACT_EMAIL, "email 4");
Uri newUri = getContentResolver().insert(CONTACT_URI, cv);
Log.d(LOG_TAG, "insert, result Uri: " + newUri.toString());
}
public void onClickUpdate(View view)
{
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, "name 5");
cv.put(CONTACT_EMAIL, "email 5");
Uri uri = ContentUris.withAppendedId(CONTACT_URI, 2);
int cnt = getContentResolver().update(uri, cv, null, null);
Log.d(LOG_TAG, "update, count = " + cnt);
}
public void onClickDelete(View view)
{
Uri uri = ContentUris.withAppendedId(CONTACT_URI, 3);
int cnt = getContentResolver().delete(uri, null, null);
Log.d(LOG_TAG, "delete, count = " + cnt);
}
public void onClickError(View view)
{
Uri uri = Uri.parse("content://zulfigarov.com.trainingprj.MyContentProvider/phones");
try
{
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
}
catch (Exception ex)
{
Log.d(LOG_TAG, "Error: " + ex.getClass() + ", " + ex.getMessage());
}
}
}
and a ContentProvider:
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class MyContactsProvider extends ContentProvider
{
final String LOG_TAG = "myLogs";
static final String DB_NAME = "mydb";
static final int DB_VERSION = 1;
static final String CONTACT_TABLE = "contacts";
static final String CONTACT_ID = "_id";
static final String CONTACT_NAME = "name";
static final String CONTACT_EMAIL = "email";
static final String DB_CREATE = "CREATE TABLE " + CONTACT_TABLE + "("
+ CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CONTACT_NAME + " TEXT, "
+ CONTACT_EMAIL + " TEXT" + ");";
static final String AUTHORITY = "zulfigarov.com.trainingprj.MyContactsProvider";
static final String CONTACT_PATH = "contacts";
public static final Uri CONTACT_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + CONTACT_PATH);
static final String CONTACT_CONTENT_TYPE = "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + CONTACT_PATH;
static final String CONTACT_CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd." + AUTHORITY + "." + CONTACT_PATH;
static final int URI_CONTACTS = 1;
static final int URI_CONTACTS_ID = 2;
private static final UriMatcher uriMatcher;
static
{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, CONTACT_PATH, URI_CONTACTS);
uriMatcher.addURI(AUTHORITY, CONTACT_PATH + "/#", URI_CONTACTS_ID);
}
DBHelper dbHelper;
SQLiteDatabase db;
#Override
public boolean onCreate()
{
Log.d(LOG_TAG, "onCreate provider");
dbHelper = new DBHelper(getContext());
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
Log.d(LOG_TAG,"query, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
Log.d(LOG_TAG, "URI_CONTACTS");
if(TextUtils.isEmpty(sortOrder))
{
sortOrder = CONTACT_NAME + " ASC";
}
break;
case URI_CONTACTS_ID:
String id = uri.getLastPathSegment();
Log.d(LOG_TAG, "URI_CONTACTS_ID");
if (TextUtils.isEmpty(selection))
selection = CONTACT_ID + " = " + id;
else
selection = selection + " AND " + CONTACT_ID + " = " + id;
break;
default:
throw new IllegalArgumentException("Wrong URI: " + uri);
}
db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(CONTACT_TABLE, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),CONTACT_CONTENT_URI);
return cursor;
}
#Override
public String getType(Uri uri)
{
Log.d(LOG_TAG, "getTYpe, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
return CONTACT_CONTENT_TYPE;
case URI_CONTACTS_ID:
return CONTACT_CONTENT_ITEM_TYPE;
}
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values)
{
Log.d(LOG_TAG,"insert, " + uri.toString());
if(uriMatcher.match(uri) != URI_CONTACTS)
throw new IllegalArgumentException("Wrong URI: " + uri);
db = dbHelper.getWritableDatabase();
long rowID = db.insert(CONTACT_TABLE, null, values);
Uri resultUri = ContentUris.withAppendedId(CONTACT_CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(resultUri, null);
return resultUri;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs)
{
Log.d(LOG_TAG,"delete, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
Log.d(LOG_TAG,"URI_CONTACTS");
break;
case URI_CONTACTS_ID:
String id = uri.getLastPathSegment();
Log.d(LOG_TAG,"URI_CONTACTS_ID, " + id);
if(TextUtils.isEmpty(selection))
{
selection = CONTACT_ID + " = " + id;
}
else
{
selection = selection + " AND " + CONTACT_ID + " = " + id;
}
break;
default:
throw new IllegalArgumentException("Wrong URI: " + uri);
}
db = dbHelper.getWritableDatabase();
int cnt = db.delete(CONTACT_TABLE, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return cnt;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
{
Log.d(LOG_TAG,"update, " + uri.toString());
switch (uriMatcher.match(uri))
{
case URI_CONTACTS:
Log.d(LOG_TAG,"URI_CONTACTS");
break;
case URI_CONTACTS_ID:
String id = uri.getLastPathSegment();
Log.d(LOG_TAG, "URI_CONTACTS_ID");
if(TextUtils.isEmpty(selection))
{
selection = CONTACT_ID;
}
else
{
selection = selection + " AND " + CONTACT_ID + " = " + id;
}
break;
default:
throw new IllegalArgumentException("Wrong URI: " + uri);
}
db = dbHelper.getWritableDatabase();
int cnt = db.update(CONTACT_TABLE, values, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri,null);
return cnt;
}
private class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE);
ContentValues cv = new ContentValues();
for (int i = 1; i <= 3; i++)
{
cv.put(CONTACT_NAME, "name " + i);
cv.put(CONTACT_EMAIL, "email " + i);
db.insert(CONTACT_TABLE, null, cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
}
The touble is that when I click on the buttons (firing onClickInsert, onClickUpdate etc. methods in MainActivity) it updates the data in database but doesn't update the ListView on an activity. Looks like
getContext().getContentResolver().notifyChange(resultUri, null);
is not working properly. So I can't find where i'm wrong.
Use CursorLoaders to load the data and populate the ListView.
http://developer.android.com/reference/android/content/CursorLoader.html
Then use getContext().getContentResolver().notifyChange(resultUri, null); when you insert, update or delete!
Without CursorLoaders you will have to use ContentObservers
So, although DB is updated in background and you are using notifyChange() but no one is listening to that!
You should be calling adapter.notifyDataSetChanged() (after the onClickInsert) in order to make your ListView notice about the change.
Related
Hello I am new to android studios. I am working on an airline reservation project. One of the requirements of the project is to generate a receipt that is stored on an external file every time a customer makes a payment. I have tried looking around trying to figure out how one might accomplish this with no success. In the app I am using SQLite as a database where every user is assigned a balance once they create an account.
Here is my DBHelper class:
package com.example.shashank.fffffffffffffffffffffffffff;
import android.annotation.SuppressLint;
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 static final String USERS = "users";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String BALANCE = "balance";
public static final String BOOKING = "booking";
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, " + EMAIL + " TEXT UNIQUE, " + BALANCE + " REAL, " + BOOKING + " INTEGER)");
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, 2000);
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);
ContentValues insertValues3 = new ContentValues();
insertValues3.put(COLUMN_DESTINATION, "Cape Town");
insertValues3.put(COLUMN_PRICE, 500);
insertValues3.put(COLUMN_DEPARTURE_TIME, "1200");
insertValues3.put(COLUMN_ARRIVAL_TIME, "1400");
insertValues3.put(COLUMN_DURATION, "2");
insertValues3.put(COLUMN_AVAILABLE_SEATS, 0);
MyDB.insert(FLIGHTS, null, insertValues3);
}
#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, String email, Double balance){
SQLiteDatabase MyDB = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(USERNAME, username);
contentValues.put(PASSWORD, password);
contentValues.put(EMAIL, email);
contentValues.put(BALANCE, balance);
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;
}
#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 closing db)
return rv;
}
#SuppressLint("Range")
public UsersModel getPasswordByName(String name){
UsersModel rv;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cr = db.query(USERS, null, USERNAME+"=?", new String[]{name}, null, null, null);
if (cr.moveToFirst()) {
rv = new UsersModel(
cr.getString(cr.getColumnIndex(USERNAME)),
cr.getString(cr.getColumnIndex(PASSWORD)),
cr.getString(cr.getColumnIndex(EMAIL)),
cr.getDouble(cr.getColumnIndex(BALANCE)),
cr.getInt(cr.getColumnIndex(BOOKING))
);
} else rv = new UsersModel();
cr.close();
return rv;
}
public int setBookingByUserName(int bookingAmount, String userName) {
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public double makingPayment(double balance, String userName){
ContentValues cv = new ContentValues();
cv.put(BALANCE,balance);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public int setAvailableSeatsAfterPayment(int seats, int flightID){
ContentValues cv = new ContentValues();
cv.put(COLUMN_AVAILABLE_SEATS,seats);
return this.getWritableDatabase().update(FLIGHTS,cv,COLUMN_ID+"=?",new String[]{String.valueOf(flightID)});
}
public int cancelBooking(int bookingAmount, String userName){
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{String.valueOf(userName)});
}
}
The making payment method is used to update the database with a new balance when a customer books for a flight.
Here is the booking activity:
package com.example.shashank.fffffffffffffffffffffffffff;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class BookingActivity extends AppCompatActivity {
TextView textView;
TextView departure, arrival, duration, price, seats;
DBHelper dbHelper; //<<<<< ADDED
Button book, accountBtn;
FlightsModel flightsModel; //<<<<< ADDED
UsersModel userModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
dbHelper = new DBHelper(this); //<<<<< ADDED
textView = findViewById(R.id.textView);
departure = findViewById(R.id.departure);
arrival = findViewById(R.id.arrival);
duration = findViewById(R.id.duration);
price = findViewById(R.id.price);
seats = findViewById(R.id.seats);
book = findViewById(R.id.button2);
accountBtn = findViewById(R.id.accountBtn);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Intent nameIntent = getIntent();
String name = nameIntent.getStringExtra("userName");
flightsModel = dbHelper.getFlightById(intValue + 1);
intValue = intValue + 1;
textView.setText(flightsModel.getDestination());
departure.setText(flightsModel.getDeparture_time());
arrival.setText(flightsModel.getArrival_time());
duration.setText(flightsModel.getDuration());
price.setText("R" + Double.toString(flightsModel.getPrice()));
seats.setText(Integer.toString(flightsModel.getAvailable_space()));
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int intValue, seats;
Intent mIntent = getIntent();
intValue = mIntent.getIntExtra("intVariableName", 0);
intValue = intValue + 1;
dbHelper = new DBHelper(BookingActivity.this);
flightsModel = dbHelper.getFlightById(intValue);
double price;
price = flightsModel.getPrice();
userModel = dbHelper.getPasswordByName(name);
double balance;
balance = userModel.getBalance();
String name = nameIntent.getStringExtra("userName");
seats = flightsModel.getAvailable_space();
if(seats == 0){
Toast.makeText(BookingActivity.this, "Booking unsuccessful, no available seats", Toast.LENGTH_SHORT).show();
}else{
if(price <= balance){
dbHelper.setBookingByUserName(intValue, name);
Toast.makeText(BookingActivity.this, "Payment successful, booking has been made", Toast.LENGTH_SHORT).show();
double newBalance;
newBalance = balance - price;
dbHelper.makingPayment(newBalance, name);
seats = seats - 1;
dbHelper.setAvailableSeatsAfterPayment(seats, intValue);
}else{
Toast.makeText(BookingActivity.this, "Payment unsuccessful, not enough funds", Toast.LENGTH_SHORT).show();
}
}
}
});
accountBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BookingActivity.this, AccountActivity.class);
intent.putExtra("userName", name);
startActivity(intent);
}
});
}
}
So once a customer makes his booking a receipt file needs to be generated, say for instance with the flight details, time, date and the price of the flight. Any help will be appreciated thank you.
The following is an example that saves a file in the App's Files directory in a sub directory of receipts. The filename being composed of values e.g.
Fred-Cape Town-1200-1400
Stored at /data/user/0/the_package_name/files/receipts/Fred-Cape Town-1200-1400
The file itself, in the example containing :-
Fred
Cape Town
1200
1400
Some supportive methods added to DBHelper :-
public UsersModel getUsersModelByName(String userName) {
UsersModel rv = new UsersModel();
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(USERS,null,USERNAME+"=?", new String[]{userName},null,null,null);
if (csr.moveToFirst()) {
rv = new UsersModel(
csr.getString(csr.getColumnIndex(USERNAME)),
csr.getString(csr.getColumnIndex(PASSWORD)),
csr.getString(csr.getColumnIndex(EMAIL)),
csr.getDouble(csr.getColumnIndex(BALANCE)),
csr.getInt(csr.getColumnIndex(BOOKING))
);
}
csr.close();
return rv;
}
public boolean makeBooking(String userName, int bookingId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingId);
return db.update(USERS,cv,USERNAME + "=?", new String[]{userName}) > 0;
}
Now the makeBookReceiptFile method, also placed in the DBHelper class:-
public String makeBookReceiptFile(String userName, Context context) {
String rcpts_directory = "receipts";
String rv = "";
SQLiteDatabase db = this.getWritableDatabase();
UsersModel currentUser = getUsersModelByName(userName);
FlightsModel currentFlightsModel = new FlightsModel();
if (currentUser.booking > 0) {
currentFlightsModel = getFlightById(currentUser.booking);
if (currentFlightsModel.id < 1) {
rv = "INVALID - unable to extract booking for id " + currentUser.booking;
}
} else {
rv = "INVALID - unable to extract user who's name is " + userName;
}
if (rv.length() > 0) return rv;
String rcpt_filename =
currentUser.username + "-" +
currentFlightsModel.destination + "-" +
currentFlightsModel.departure + "-" +
currentFlightsModel.arrival
;
File rcpt = new File(context.getFilesDir().getPath() + File.separatorChar + rcpts_directory + File.separatorChar + rcpt_filename);
rcpt.getParentFile().mkdirs();
try {
FileWriter fw = new FileWriter(rcpt);
fw.write(userName +
"\n" + currentFlightsModel.destination+
"\n" + currentFlightsModel.departure +
"\n" + currentFlightsModel.arrival
);
fw.flush();
fw.close();
rv = rcpt.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
rv = "IOERROR - " + e.getMessage();
}
return rv;
}
First it retrieves the UsersModel according to the UserName, the it retrieves the FlightsModel according to the booking id.
If either was not obtained then it returns a String starting with INVALID
It then obtains the Files directory via the Context.
Generates the path for the file.
Makes any missing directories.
Write data to the file, flushes and closes the file returning the path or if there was an io error the error message.
The above was tested using :-
db = new DBHelper(this);
db.insertData("Fred","password","fed#email",0.00);
UsersModel fred = db.getUsersModelByName("Fred");
db.makeBooking(fred.username,1);
Log.d("RESULTINFO",db.makeBookReceiptFile("Fred",this));
Resulting in (via Device Explorer) :-
If you have issues with the location of the file then you will have to read https://developer.android.com/training/data-storage/
My problems : What I suppose to do?
1. Below is my error in logcat
2. Why my data doesn't enter in my SQLite database when I open it in SQLite browser?
3. Almost all the method I make a research and use, but all of them cannot use it.
My connection SQLite database : Database.java
package com.example.projectvote;
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 static androidx.constraintlayout.widget.Constraints.TAG;
public class Database extends SQLiteOpenHelper {
private static final String TAG = "Database";
public static final String DbName = "SignUp.db";
public static final String TbName = "SignUp";
public static final String Col1 = "Num";
public static final String Col2 = "ID";
public static final String Col3 = "Password";
public static final String TbName1 = "candidate";
public static final String Col4 = "Nom";
public static final String Col5 = "Candidates";
public Database(Context context) {
super(context, DbName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE SignUp (Num INT PRIMARY KEY AUTOINCREMENT, ID TEXT, Password TEXT)");
sqLiteDatabase.execSQL("CREATE TABLE candidate (Nom INT PRIMARY KEY AUTOINCREMENT, Candidates TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TbName);
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TbName1);
onCreate(sqLiteDatabase);
}
public long addUser(String ID, String password)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("ID", ID);
cv.put("password", password);
long res = db.insert("SignUp", null, cv);
db.close();
return res;
}
public boolean checkUser(String ID, String password)
{
String[] columns = { Col2 };
SQLiteDatabase db = getReadableDatabase();
String selection = Col2 + "=?" + "and" + Col3 + "=?";
String[] selectionArgs = { ID, password };
Cursor c = db.query(TbName, columns, selection, selectionArgs, null, null, null);
int count = c.getCount();
c.close();
db.close();
if (count > 0)
return true;
else
return false;
}
public Cursor readData(SQLiteDatabase db) {
String[] cols = { Col5 };
Cursor c = db.query(TbName1, cols, null, null, null, null, null);
return c;
}
public boolean addCandidate(String Candidates)
{
SQLiteDatabase db = this. getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(Col5, Candidates);
Log.d(TAG, "addCandidate : Adding " + Candidates + " to " + TbName1);
long res = db.insert(TbName1, null, cv);
if(res == -1)
{
return false;
}
else
{
return true;
}
}
public Cursor getItemID(String Candidates)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + Col4 + " FROM " + TbName1 + " WHERE " + Col5 + " = " + Candidates + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
public void updateCandidate(String newCandidate, int ID, String oldCandidate)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TbName1 + " SET " + Col5 + "= '" + newCandidate + "' WHERE " + Col5 + "= '" + oldCandidate + "'";
Log.d(TAG, "updateCandidate: query: " + query);
Log.d(TAG, "updateCandidate: Setting Candidate to " + newCandidate);
db.execSQL(query);
}
public void deleteCandidate(int ID, String Candidate)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TbName1 + " WHERE " + Col5 + "= '" + Candidate + "'";
Log.d(TAG, "deleteCandidate: query: " + query);
Log.d(TAG, "deleteCandidate: Deleting: " + Candidate + " from database ");
db.execSQL(query);
}
public Cursor getListContent1() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TbName1;
Cursor data = db.rawQuery(query, null);
return data;
}
}
My login java : Login.java
package com.example.projectvote;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity
{
EditText ID, password;
Database db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new Database(this);
ID = findViewById(R.id.etID);
password = findViewById(R.id.etPassword);
}
public void OnLog(View view)
{
String Id = ID.getText().toString().trim();
String Password = password.getText().toString().trim();
Boolean res = db.checkUser(Id, Password);
if (res == true)
{
startActivity(new Intent(getApplicationContext(), Home.class));
}
else if ((ID.equals("Admin") && Password.equals("Admin2019")))
{
startActivity(new Intent(getApplicationContext(), Admin.class));
}
else
{
Toast.makeText(Login.this, "Sorry, Login Error", Toast.LENGTH_SHORT).show();
}
}
public void OnReg(View view) {
startActivity(new Intent(getApplicationContext(), SignUp.class));
}
}
Update your queries in your onCreate() of Database.java like following
sqLiteDatabase.execSQL("CREATE TABLE SignUp (Num INTEGER PRIMARY KEY AUTOINCREMENT, ID TEXT, Password TEXT)");
sqLiteDatabase.execSQL("CREATE TABLE candidate (Num INTEGER PRIMARY KEY AUTOINCREMENT, Candidates TEXT)");
I am working on databases for my project and I have columns for primary key (rowid), number (contact number) and name. I am adding two different entries with same number in my database and i need to extract both of them from the database. Code for extracting is
public Cursor SelectList(String number) throws SQLException {
String query = "SELECT FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim()+"'";
Cursor mcursor = db.rawQuery(query, null);
if(mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
But it is showing SQLite exception at this line
Cursor mcursor = db.rawQuery(query, null);
Code for DatabaseHandler
package com.example.gul.databasealvie;
/**
* Created by gul on 6/6/15.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_NUMBER = "number";
static final String KEY_ID="listid";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB20";
static final String DATABASE_TABLE = "contacts5";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE= "create table contacts5(_id integer primary key , "
+ "name text not null, number text not null, listid text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public boolean DeleteList(String number){
db.execSQL("DELETE FROM "+DATABASE_TABLE+" WHERE "+KEY_NUMBER+"="+number);
return true;
}
public void DropTable(){
db.execSQL("Delete From " + DATABASE_TABLE);
}
public Cursor SelectList(String number) throws SQLException {
String query = "SELECT FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim()+"'";
Cursor mcursor = db.rawQuery(query,null);
if (mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(TableData contact, String id )
{
long myid=Long.parseLong(id);
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, contact.getName());
initialValues.put(KEY_NUMBER,contact.getPhoneNumber());
initialValues.put(KEY_ID, id);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean DeletContact(String number)throws SQLException{
return db.delete(DATABASE_TABLE, KEY_NUMBER + "=" + number, null) > 0;
}
public long insertContact(Anonymous contact, String id )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, contact.getName());
initialValues.put(KEY_NUMBER, contact.getPhoneNumber());
initialValues.put(KEY_ID, id);
// Log.d("Contact", contact.getName() + contact.getPhoneNumber());
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteContact(String number)
{
return db.delete(DATABASE_TABLE, KEY_NUMBER + " = ?",
new String[] { number }) > 0;
}
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_NUMBER}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_NUMBER}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean iskey(long rowid)throws SQLException
{
Cursor mCursor=db.query(true,DATABASE_TABLE, new String[]{KEY_ROWID,KEY_NAME,KEY_NUMBER },KEY_ROWID+"="+rowid,null,null
,null,null,null);
if(mCursor!=null && mCursor.moveToFirst()){
return true;
}
else
return false;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String email)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_NUMBER, email);
return db.update(
DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
Code for testing purposes
package com.example.gul.databasealvie;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
DBAdapter db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBAdapter(this);
AddContact();
PrintingList();
GetContacts();
GetContact();
//UpdateContact();
DeleteContact();
}
public void AddContact() {
Anonymous a= new Anonymous(34,"Wei-Meng Lee", "12345");
Anonymous b= new Anonymous(2,"Wejhkjh Lee", "12234");
//---add a contact---
db.open();
if (db.insertContact(a,"22") >= 0){
Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
}
if (db.insertContact(b,"21") >= 0) {
Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
}
if (db.insertContact(b,"21") >= 0) {
Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
}
db.close();
}
public void PrintingList(){
db.open();
Cursor mCursor=db.SelectList("12234");
if(mCursor.moveToFirst()){
do {
displaylist(mCursor);
}while(mCursor.moveToNext());
}
db.close();
}
public void GetContacts() {
//--get all contacts---
db.open();
// db.DeleteList("12345");
// if(db.DeletContact("12234")) {
// Log.i("Deleted contact", "");
//}
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
db.close();
}
public void GetContact() {
//---get a contact---
db.open();
Cursor c = db.getContact(2);
if (c.moveToFirst())
DisplayContact(c);
else
Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show();
db.close();
}
public void UpdateContact() {
//---update a contact---
db.open();
if (db.updateContact(1, "Wei-Meng Lee", "weimenglee#gmail.com"))
Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
db.close();
}
public void DeleteContact() {
db.open();
//if (db.deleteContact(1))
// Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
//else
// Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show();
db.close();
}
public void DisplayContact(Cursor c)
{
Log.i(
"contacts", "id: " + c.getString(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Number: " + c.getString(2)
);
db.open();
if((db.iskey(2))){
Log.i("Yay ", "it's working");
}
db.close();
}
public void displaylist(Cursor c){
Log.i(
"List","listid:"+c.getString(0)+ "\n"+
"NAMElist: " + c.getString(1)+ "\n" +
"list: "+c.getString(2)
);
}
}
Code For Anonymous.java
package com.example.gul.databasealvie;
/**
* Created by gul on 6/6/15.
*/
/**
* Created by Noor Zia on 5/26/2015.
*/
public class Anonymous {
public long id;
public String name;
public String number;
public Anonymous(){
name="Unknown";
}
public Anonymous(String no){
name="Unknown";
number = no;
}
public Anonymous(long id, String name, String number){
name=name;
this.number=number;
this.name=name;
this.id=id;
}
public long getID(){
return this.id;
}
// setting id
// getting name
public String getName(){
return this.name;
}
// setting name
// getting phone number
public String getPhoneNumber(){
return this.number;
}
// setting phone number
}
dbHelper = new DBHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from centuaryTbl where email='"+email+"'",null);
if (cursor.moveToFirst())
{
do
{
String s1 = cursor.getString(cursor.getColumnIndex("s1"));
String s2 = cursor.getString(cursor.getColumnIndex("s2"));
String s3 = cursor.getString(cursor.getColumnIndex("s3"));
}while (cursor.moveToNext());
}
You need to specify the columns to retrieve. For instance:
String query = "SELECT name, number FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim() + "'";
More information about Select clause
Or you can fetch all columns using '*'
Your query will be
String query = "SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim()+"'";
public String select_data(String email)
{
db=this.getReadableDatabase();
String query="select email,password from "+Table_name;
Cursor cursor=db.rawQuery(query,null);
String a,b;
b="not found";
if (cursor.moveToFirst()) {
do {
a=cursor.getString(0);
if(a.equals(email))
{
b=cursor.getString(1);
break;
}
} while(cursor.moveToNext());
}
return b;
}
I have two classes:
Database class:
package com.qstra.soamazingtodoapp;
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_TASK = "task";
public static final String KEY_DATE = "date";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_TASK,
KEY_DATE, KEY_HOUR, KEY_MINUTE };
// 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;
public static final int COL_HOUR = 3;
public static final int COL_MINUTE = 4;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
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_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT" + KEY_HOUR + " TEXT"
+ KEY_MINUTE + " 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 task, String date, String hour, String minute) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
// 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 task, String date, String hour, String minute) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TASK, task);
newValues.put(KEY_DATE, date);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_MINUTE, minute);
// 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 class:
package com.qstra.soamazingtodoapp;
import com.qstratwo.soamazingtodoapp.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
Time today = new Time(Time.getCurrentTimezone());
DBAdapter myDb;
EditText etTasks;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
String string_hour_x, string_minute_x="None";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTasks = (EditText) findViewById(R.id.editText1);
openDB();
listViewItemClick();
listViewItemLongClick();
populateListView();
// setNotification();
}
#Override
protected Dialog onCreateDialog(int idD){
if (idD== DIALOG_ID){
return new TimePickerDialog(MainActivity.this, kTimePickerListener, hour_x,minute_x, false);
}
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x=hourOfDay;
minute_x=minute;
string_hour_x = Integer.toString(hour_x);
string_minute_x = Integer.toString(minute_x);
Toast.makeText(MainActivity.this, hour_x+" : "+ minute_x,Toast.LENGTH_LONG).show();
}
};
public void setNotification(View v) {
showDialog(DIALOG_ID);
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_AddTask (View v) {
today.setToNow();
String timestamp = today.format("%Y-%m-%d %H:%m:%s");
if(!TextUtils.isEmpty(etTasks.getText().toString())) {
myDb.insertRow(etTasks.getText().toString(),timestamp,string_hour_x, string_minute_x);
}
populateListView();
}
private void populateListView() {
Cursor cursor = myDb.getAllRows();
String[] fromFieldNames=new String[] {
DBAdapter.KEY_ROWID, DBAdapter.KEY_TASK };
int[] toViewIDs = new int[] {
R.id.textViewItemNumber, R.id.textViewItemTasks};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setAdapter(myCursorAdapter);
}
private void updateTask(long id){
Cursor cursor = myDb.getRow(id);
if (cursor.moveToFirst()){
String task = etTasks.getText().toString(); // POBIERANIE Z TEXTFIELD
today.setToNow();
String date = today.format("%Y-%m-%d %H:%m");
// String string_minute_x= Integer.toString(minute_x);
// String string_houte_x=Integer.toString(hour_x);
myDb.updateRow(id, task, date, string_hour_x, string_minute_x );
}
cursor.close();
}public void onClick_DeleteTasks(View v) {
myDb.deleteAll();
populateListView();
}
public void onClick_AppClose(View v) {
moveTaskToBack(true);
MainActivity.this.finish();
}
public void listViewItemLongClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
myDb.deleteRow(id);
populateListView();
return false;
}
});
}
private void listViewItemClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
updateTask(id);
populateListView();
displayToast(id);
}
});
}
private void displayToast(long id){
Cursor cursor = myDb.getRow(id);
if(cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String task = cursor.getString(DBAdapter.COL_TASK);
String date = cursor.getString(DBAdapter.COL_DATE);
String message = "ID: " + idDB + "\n" + "Task: " + task + "\n" + "Date: " + date;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
}
(getting id and text from texfield to database works fine but..)
I'm trying to get hour and minutes values from TimePickerDialog and insert in to database but it seems not working.
Screen shot from log cat:
Why can't it see column named 'hour'?
Add commas in your statement to create database
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT," + KEY_HOUR + " TEXT,"
+ KEY_MINUTE + " TEXT" + ")";
I want to know how to check for duplicated fields in my database by updating it.
If the day and hour are the same in another row it must give an error.
DBHelper:
package me.wouter.schoolwork;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Schedule {
public static final String KEY_ROWID = "_id"; //Row Id
public static final String KEY_HOUR = "schedule_hour";
public static final String KEY_DAY = "schedule_day";
public static final String KEY_LOCATION = "schedule_location";
public static final String KEY_SUBJECT = "schedule_subject";
public static final String KEY_START = "schedule_start";
public static final String KEY_END = "schedule_end";
private static final String DATABASE_NAME = "PlanYourDay";
private static final String DATABASE_TABLE = "schedule";
private static final int DATABASE_VERSION = 1;
private dBHelper classHelper;
private final Context classContext;
private SQLiteDatabase classDatabase;
public Cursor c;
private static class dBHelper extends SQLiteOpenHelper {
public dBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_HOUR + " TEXT NOT NULL, " +
KEY_DAY + " TEXT NOT NULL, " +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_SUBJECT + " TEXT NOT NULL, " +
KEY_START + " TEXT NOT NULL, " +
KEY_END + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Schedule(Context c){
classContext = c;
}
public Schedule open() throws SQLException{
classHelper = new dBHelper(classContext);
classDatabase = classHelper.getWritableDatabase();
return this;
}
public Schedule close(){
classHelper.close();
return this;
}
public long createEntry(String subject, String day, String hour,
String location, String start, String end) {
ContentValues cv = new ContentValues();
cv.put(KEY_SUBJECT, subject);
cv.put(KEY_DAY, day);
cv.put(KEY_HOUR, hour);
cv.put(KEY_LOCATION, location);
cv.put(KEY_START, start);
cv.put(KEY_END, end);
return classDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_SUBJECT, KEY_HOUR, KEY_DAY, KEY_LOCATION, KEY_START, KEY_END};
c = classDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
final int iSubject = c.getColumnIndex(KEY_SUBJECT);
int iHour = c.getColumnIndex(KEY_HOUR);
int iDay = c.getColumnIndex(KEY_DAY);
int iLocation = c.getColumnIndex(KEY_LOCATION);
int iStart = c.getColumnIndex(KEY_START);
int iEnd = c.getColumnIndex(KEY_END);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iSubject) + " " + c.getString(iHour) + " "
+ c.getString(iDay) + " " + c.getString(iLocation) + " " + c.getString(iStart) + " "
+ c.getString(iEnd) + "\n";
}
return result;
}
}
DB Inserter:
package me.wouter.schoolwork;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ScheduleTest extends Activity implements OnClickListener {
// object variables
Button bLoadSql, bSaveSql;
TextView viewSubject, viewDay, viewHour, viewLocation, viewStart, viewEnd;
EditText editSubject, editDay, editHour, editLocation, editStart, editEnd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sql);
allTheVariables();
bLoadSql.setOnClickListener(this);
bSaveSql.setOnClickListener(this);
}
private void allTheVariables() {
// defines variables in xml file
// buttons
bLoadSql = (Button) findViewById(R.id.bLoadSql);
bSaveSql = (Button) findViewById(R.id.bSaveSql);
// textviews
viewSubject = (TextView) findViewById(R.id.viewSubject);
viewDay = (TextView) findViewById(R.id.viewDay);
viewHour = (TextView) findViewById(R.id.viewHour);
viewLocation = (TextView) findViewById(R.id.viewLocation);
viewStart = (TextView) findViewById(R.id.viewStart);
viewEnd = (TextView) findViewById(R.id.viewEnd);
// edittext
editSubject = (EditText) findViewById(R.id.editSubject);
editDay = (EditText) findViewById(R.id.editDay);
editHour = (EditText) findViewById(R.id.editHour);
editLocation = (EditText) findViewById(R.id.editLocation);
editStart = (EditText) findViewById(R.id.editStart);
editEnd = (EditText) findViewById(R.id.editEnd);
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bLoadSql:
Intent i = new Intent("me.wouter.schoolwork.SCHEDULEVIEW");
startActivity(i);
break;
case R.id.bSaveSql:
boolean didItWork = true;
try{
String subject = editSubject.getText().toString();
String day = editDay.getText().toString();
String hour = editHour.getText().toString();
String location = editLocation.getText().toString();
String start = editStart.getText().toString();
String end = editEnd.getText().toString();
Schedule entry = new Schedule(this);
entry.open();
entry.createEntry(subject, day, hour, location, start, end);
entry.close();
}catch (Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Failed");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(didItWork){
Dialog d = new Dialog(this);
d.setTitle("Inserted");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
}
}
}
And Viewer/Loader:
package me.wouter.schoolwork;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ScheduleView extends Activity {
TextView subject;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
subject = (TextView) findViewById(R.id.subject);
Schedule info = new Schedule(this);
info.open();
String data = info.getData();
subject.setText(data);
info.close();
}
}
Thanks in advance!
It seems to me that what you need is a multi-column uniqueness constraint on your DB schema, with a suitable conflict clause:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_HOUR + " TEXT NOT NULL, " +
KEY_DAY + " TEXT NOT NULL, " +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_SUBJECT + " TEXT NOT NULL, " +
KEY_START + " TEXT NOT NULL, " +
KEY_END + " TEXT NOT NULL, " +
"UNIQUE (" + KEY_DAY + ", " + KEY_HOUR + ") ON CONFLICT ROLLBACK);"
);
This will generate a constraint violation error if the day/hour combination is not unique, without you having to write an explicit check.