Android data is not stored to SQLite database - java

I would like to ask something about Store Android Data to SQLite Database (I am new to SQLite Database). I have been trying to store data to SQLite Database, but when I saw the database with SQLiteStudio the data was empty.
This is my code :
DatabaseHelper.java
package com.example.toolsmanager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "btm.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final String TABLE_1 = "oneroundsingle";
public static final String TABLE1_COLUMN1 = "_ID";
public static final String TABLE1_COLUMN2 = "GAMETYPE";
public static final String TABLE1_COLUMN3 = "PLAYER1";
public static final String TABLE1_COLUMN4 = "PLAYER2";
public static final String TABLE1_COLUMN5 = "SCORE";
public static final String TABLE1_COLUMN6 = "WINNER";
public static final String CREATE_TABLE_ORS = "create table" + TABLE_1 + " ( " +
TABLE1_COLUMN1 + " integer primary key autoincrement, " +
TABLE1_COLUMN2 + " text, " +
TABLE1_COLUMN3 + " text, " +
TABLE1_COLUMN4 + " text, " +
TABLE1_COLUMN5 + " text, " +
TABLE1_COLUMN6 + " text " + ");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_ORS);
db.execSQL(CREATE_TABLE_ORD);
db.execSQL(CREATE_TABLE_RS);
db.execSQL(CREATE_TABLE_RD);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists" + TABLE_1);
db.execSQL("drop table if exists" + TABLE_2);
db.execSQL("drop table if exists" + TABLE_3);
db.execSQL("drop table if exists" + TABLE_4);
onCreate(db);
}
}
OR_SingleCount.java
package com.example.toolsmanager;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class OR_SingleCount extends AppCompatActivity {
int player1_score, player2_score, final_score;
TextView text_player1_name, text_player2_name;
String score, winner;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_or_single_count);
text_player1_name = (TextView)findViewById(R.id.player1_name);
text_player1_name.setText(getIntent().getExtras().getString("player1"));
text_player2_name = (TextView)findViewById(R.id.player2_name);
text_player2_name.setText(getIntent().getExtras().getString("player2"));
}
public void singleCount(View v) {
int id = v.getId();
if (id == R.id.player1_plus) {
player1_score += 1;
TextView text_player1_score = (TextView) findViewById(R.id.player1_score);
text_player1_score.setText(String.valueOf(player1_score));
} else if (id == R.id.player1_minus && player1_score != 0) {
player1_score -= 1;
TextView text_player1_score = (TextView) findViewById(R.id.player1_score);
text_player1_score.setText(String.valueOf(player1_score));
} else if (id == R.id.player2_plus) {
player2_score += 1;
TextView text_player2_score = (TextView) findViewById(R.id.player2_score);
text_player2_score.setText(String.valueOf(player2_score));
} else if (id == R.id.player2_minus && player2_score != 0) {
player2_score -= 1;
TextView text_player2_score = (TextView) findViewById(R.id.player2_score);
text_player2_score.setText(String.valueOf(player2_score));
}
finalScore();
}
public void finalScore(){
if ((player1_score == 21 && player2_score < 20) || (player2_score == 21 && player1_score < 20)) {
final_score = 21;
getWinner();
} else if (player1_score == 30 || player2_score == 30) {
final_score = 30;
getWinner();
} else if (player1_score >= 20 && player2_score >= 20) {
if (player1_score == player2_score + 2) {
final_score = player1_score;
getWinner();
} else if (player2_score == player1_score + 2) {
final_score = player2_score;
getWinner();
}
}
}
public void getWinner() {
if (player1_score == final_score){
winner = text_player1_name.getText().toString();
String print_winner = winner + " is the winner";
Toast.makeText(getApplicationContext(),print_winner, Toast.LENGTH_LONG).show();
} else if(player2_score == final_score) {
winner = text_player2_name.getText().toString();
String print_winner = winner + " is the winner";
Toast.makeText(getApplicationContext(), print_winner, Toast.LENGTH_LONG).show();
}
score = player1_score + " - " + player2_score;
String gametype = "Single";
addORSingleData(gametype,
text_player1_name.getText().toString(),
text_player2_name.getText().toString(),
score,
winner);
AlertDialog repeatdialog= new AlertDialog.Builder(this)
.setTitle("Game Finish")
.setMessage("Do you want to repeat the game?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
player1_score = 0;
player2_score = 0;
recreate();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(OR_SingleCount.this, OneRoundMatch.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}).create();
repeatdialog.show();
}
public void addORSingleData(String gametype, String player1, String player2, String score, String winner){
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TABLE1_COLUMN2, gametype);
contentValues.put(DatabaseHelper.TABLE1_COLUMN3, player1);
contentValues.put(DatabaseHelper.TABLE1_COLUMN4, player2);
contentValues.put(DatabaseHelper.TABLE1_COLUMN5, score);
contentValues.put(DatabaseHelper.TABLE1_COLUMN6, winner);
db.insert(DatabaseHelper.TABLE_1, null, contentValues);
}
}
What's wrong with my code?

I've never used SQLite Studio so I couldn't trouble shoot that issue if I wanted to but you could set up a cursor:
Cursor cursor = db.query(TABLE_NAME,null,null,null,null,null,null);
then call
Toast.makeText(this, "" + cursor.getCount(), Toast.LENGTH_SHORT).show();
to see if you're inserting any data. Also, what are the extra tables in your onCreate method?

Related

How to add from sqlite database into a for loop

So im trying to get 3 of my columns from my database from sqlite to be put into my arraylist then displayed into a list view but at the moment it is only displaying the quantity. Eg: Name: 1 Quantity: 1 Type: 1
But I want it to display all of the other columns instead of just the quantity so the output would actually be: Name: Milk Quantity: 1 Type: Ingredient
Does anyone know how to do this?
InventoryStatus class:
public class InventoryStatus extends AppCompatActivity {
DatabaseHelper myDB;
int currentPosition = 0;
private ArrayList<String> fullList;
private ArrayList<String> displayedList;
ArrayAdapter<String> listAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_status);
listView = findViewById(R.id.listViewStock);
Button btNext = findViewById(R.id.buttonNext);
Button btPrevious = findViewById(R.id.buttonPrevious);
myDB = new DatabaseHelper(this);
Cursor data = myDB.getAllData();
fullList = new ArrayList<>();
displayedList = new ArrayList<>();
for (int i = 0; i < 5; i++)
{
fullList.add("Name: " + i + "Quantity: " + i + "Type: " + i);
}
if (fullList.size() == 0)
{
Toast.makeText(this, "No data found", Toast.LENGTH_SHORT).show();
}
else // fullList isn't empty show first 5 items in ListView
{
setDisplayListPosition();
listView.setAdapter(listAdapter);
}
btNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) // change current position and refresh ListView
{
currentPosition += 5;
if (currentPosition > fullList.size()) currentPosition -= 5;
else
setDisplayListPosition();
}
});
btPrevious.setOnClickListener(new View.OnClickListener() // change current position and refresh ListView
{
public void onClick(View view) {
currentPosition -= 5;
if (currentPosition < 0) currentPosition = 0;
else
setDisplayListPosition();
}
});
}
private void setDisplayListPosition() // helper function which refresh ListView based on `currentPos`
{
displayedList.clear();
for (int i = 0; i < 5 && i + currentPosition < fullList.size(); i++) {
displayedList.add(fullList.get(currentPosition + i)); // ad 5 items from finalList to displayedList
}
listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
displayedList
);
}
}
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Inventory.db";
public static final String TABLE_NAME = "Inventory_table";
public static final String COL1 = "ID";
public static final String COL2 = "Name";
public static final String COL3 = "Quantity";
public static final String COL4 = "Type";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " Name TEXT, Quantity Text, Type Text)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String Name, String Quantity, String Type){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, Name);
contentValues.put(COL3, Quantity);
contentValues.put(COL4, Type);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
// Gets all data
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("select * from " + TABLE_NAME, null);
return data;
}
// Deletes all data
public String deletedata(){
SQLiteDatabase myDB = this.getWritableDatabase();
myDB.delete(TABLE_NAME, null, null);
myDB.close();
return null;
}
}
Change this :
for (int i = 0; i < 5; i++)
{
fullList.add("Name: " + i + "Quantity: " + i + "Type: " + i);
}
to :
if(cursor.moveToFirst())
for(int i=0; i<5 ;i++){
fullList.add("Name: " + cursor.getString(1) + "Quantity: " + cursor.getString(2) + "Type: " + cursor.getString(3));
if(!cursor.moveToNext())
break;
}

Android: SQLite error in adding data

I'm working on a PiggyBank-like application wherein users can make wishlists of their wanted item and helps them save for that item. My app is still in prototype because i'm still learning android.
The problem i'm experiencing right now is every time i add a new data, it always returns false. Here's my code:
DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "price";
private static final String COL4 = "totalsavings";
private static final String COL5 = "duedate";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Returns only the ID that matches the name passed in
* #param name
* #return
*/
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Updates the name field
* #param newName
* #param id
* #param oldName
*/
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
" = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
/**
* Delete from database
* #param id
* #param name
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText, editText2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for inputs
editText = (EditText) findViewById(R.id.editText);
editText2 =(EditText) findViewById(R.id.editText2);
//buttons
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
//call database
mDatabaseHelper = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListDataActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by User on 2/28/2017.
*/
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
EditDataActivity.java
In this activity, the data will be displayed in an EditText (name), the savings goal (price). (I'm still working on the totalsavings).
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private TextView myGoal, mySavings;
private Button btnSave,btnDelete, btnDeposit;
private EditText editable_item, depositInput;
DatabaseHelper mDatabaseHelper;
private String selectedName, selectedPrice;
private int selectedID, selectedTotalSavings;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
myGoal = (TextView) findViewById(R.id.displayGoal);
mySavings = (TextView) findViewById(R.id.displayTotalSavings);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnDeposit = (Button) findViewById(R.id.btnDeposit);
editable_item = (EditText) findViewById(R.id.editable_item);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//now get the price we passed as an extra
selectedPrice = receivedIntent.getStringExtra("price");
//now we get the totalsavings we passed as an extra
selectedTotalSavings = receivedIntent.getIntExtra("totalsavings", -1);
//set the text to show the current selected name
editable_item.setText(selectedName);
//set the text to show the user's saving goal
myGoal.setText(selectedPrice);
//set text to show the user's total savings so far
mySavings.setText(selectedTotalSavings);
//-----------------------------------DIALOG BOX-----------------------------------------
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter Deposit");
builder.setMessage("Enter your deposit!");
depositInput= new EditText(this);
builder.setView(depositInput);
//SET POSITIVE BUTTON
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String depositTxt=depositInput.getText().toString();
selectedTotalSavings = Integer.parseInt(selectedTotalSavings + depositTxt);
mySavings.setText(selectedTotalSavings);
Toast.makeText(getApplicationContext(),depositTxt, Toast.LENGTH_LONG).show();
}
});
//SET NEGATIVE BUTTON
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//CREATE THE DIALOG
final AlertDialog depositPrompt=builder.create();
//--------------------------------------------------------------------------------------
//buttons
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item = editable_item.getText().toString();
if(!item.equals("")){
mDatabaseHelper.updateName(item,selectedID,selectedName);
}else{
toastMessage("You must enter a name");
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
editable_item.setText("");
toastMessage("removed from database");
}
});
btnDeposit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
depositPrompt.show();
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
Here's the Sample Syntax
User enters details for name and price
User clicks add data
User can View Data and the data will be displayed on a ListView
User can edit and view data in the EditDataActivity
I'm not sure what the problem is.
UPDATE
so i found this code on the MainActivity Class. I'm trying to add the data from editText2 but i don't know how.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
Do i have to make a new AddData?
You need to insert the right type of values as mentioned below :
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item); // pass an integer instead of a String as you have mentioned its datatype as INTEGER or parse it using Integer.parseInt()
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
The problem I think is in the CREATE TABLE query.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
There is no space between COL3 and "TEXT" (same for COL4 and "INTEGER"). So just add a space like so.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + " TEXT, " + COL4 +" INTEGER)";
Problem is in your addData() method. COL4 holds INTEGER value.
Try this:
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, Integer.parseInt(item));
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
The return of db.insert() is a long and you're comparing it to an int. Change
if (result == -1) {
return false;
} else {
return true;
}
To
return (int)result == -1;

Suspicious data changes when updating SQLite database [Android]

I am following this AlarmClock tutorial (project .zip also available on GitHub) on how to build my alarm for Android. I fixed some code that was bad, etc, but it still doesn't work as it should.
I've been getting a lot of SQLiteDatabase leaks and I fixed them (I think), but according to my observations data is still updated wrongly every time I delete an alarm or restart the application.
There are some other minor bugs, like the one where new alarms aren't added to database at all, but that is another problem.
So, I believe problem lies somewhere here:
package com.example.vedran.valarm;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import com.example.vedran.valarm.AlarmContract.Alarm;
import java.util.ArrayList;
import java.util.List;
public class AlarmDBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME = "alarmclock.db";
private static AlarmDBHelper database;
private static final String SQL_CREATE_ALARM =
"CREATE TABLE " + Alarm.TABLE_NAME + " (" +
Alarm._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Alarm.COLUMN_NAME_ALARM_NAME + " TEXT," +
Alarm.COLUMN_NAME_ALARM_TIME_HOUR + " INTEGER," +
Alarm.COLUMN_NAME_ALARM_TIME_MINUTE + " INTEGER," +
Alarm.COLUMN_NAME_ALARM_REPEAT_DAYS + " TEXT," +
Alarm.COLUMN_NAME_ALARM_REPEAT_WEEKLY + " BOOLEAN," +
Alarm.COLUMN_NAME_ALARM_TONE + " TEXT," +
Alarm.COLUMN_NAME_ALARM_ENABLED + " BOOLEAN" + " )";
private static final String SQL_DELETE_ALARM =
"DROP TABLE IF EXISTS" + Alarm.TABLE_NAME;
public AlarmDBHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ALARM);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ALARM);
onCreate(db);
}
public static synchronized AlarmDBHelper getInstance(Context context){
if(database == null){
database = new AlarmDBHelper(context.getApplicationContext());
}
return database;
}
/**
* objasnim kasnije
* #param c
* #return
*/
private AlarmModel populateModel(Cursor c){
AlarmModel model = new AlarmModel();
model.id = c.getLong(c.getColumnIndex(Alarm._ID));
model.name = c.getString(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_NAME));
model.timeHour = c.getInt(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_TIME_HOUR));
model.timeMinute = c.getInt(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_TIME_MINUTE));
model.repeatWeekly = c.getInt(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_REPEAT_WEEKLY)) != 0;
model.alarmTone = c.getString(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_TONE)) != "" ? Uri.parse(c.getString(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_TONE))) : null;
model.isEnabled = c.getInt(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_ENABLED)) != 0;
String[] repeatingDays = c.getString(c.getColumnIndex(Alarm.COLUMN_NAME_ALARM_REPEAT_DAYS)).split(",");
for(int i=0;i<repeatingDays.length;i++){
model.setRepeatingDay(i, !repeatingDays[i].equals("false"));
}
return model;
}
private ContentValues populateContent(AlarmModel model){
ContentValues values = new ContentValues();
values.put(Alarm.COLUMN_NAME_ALARM_NAME, model.name);
values.put(Alarm.COLUMN_NAME_ALARM_TIME_HOUR, model.timeHour);
values.put(Alarm.COLUMN_NAME_ALARM_TIME_MINUTE, model.timeMinute);
values.put(Alarm.COLUMN_NAME_ALARM_REPEAT_WEEKLY, model.repeatWeekly);
values.put(Alarm.COLUMN_NAME_ALARM_TONE, model.alarmTone != null ? model.alarmTone.toString() : "");
values.put(Alarm.COLUMN_NAME_ALARM_ENABLED, model.isEnabled);
StringBuilder buildRepeatingDays = new StringBuilder();
for(int i=0; i<7; i++){
buildRepeatingDays.append(model.getRepeatingDay(i));
buildRepeatingDays.append(",");
}
String repeatingDays = buildRepeatingDays.toString();
values.put(Alarm.COLUMN_NAME_ALARM_REPEAT_DAYS, repeatingDays);
return values;
}
public long createAlarm(AlarmModel model){
ContentValues values = populateContent(model);
SQLiteDatabase db = this.getWritableDatabase();
long stat = db.insert(Alarm.TABLE_NAME, null, values);
db.close();
return stat;
}
public long updateAlarm(AlarmModel model){
ContentValues values = populateContent(model);
SQLiteDatabase db = this.getWritableDatabase();
long stat = db.update(Alarm.TABLE_NAME, values, Alarm._ID + " = " + String.valueOf(model.id), null);
db.close();
return stat;
}
public AlarmModel getAlarm(long id){
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM " + Alarm.TABLE_NAME + " WHERE " + Alarm._ID + " = " + String.valueOf(id);
Cursor c = db.rawQuery(select, null);
if(c.moveToNext()){
AlarmModel model = populateModel(c);
c.close();
db.close();
return model;
}
c.close();
db.close();
return null;
}
public List<AlarmModel> getAlarms(){
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM " + Alarm.TABLE_NAME;
Cursor c = db.rawQuery(select, null);
List<AlarmModel> alarmList = new ArrayList<>();
while(c.moveToNext()){
alarmList.add(populateModel(c));
}
c.close();
db.close();
if(!alarmList.isEmpty()){
return alarmList;
}
return null;
}
public int deleteAlarm(long id) {
SQLiteDatabase db = this.getWritableDatabase();
/*int br = db.delete(Alarm.TABLE_NAME, Alarm._ID + " = ?",
new String[]{String.valueOf(id)});*/
int br = db.delete(Alarm.TABLE_NAME, Alarm._ID + " = " + String.valueOf(id), null);
db.close();
return br;
}
}
And here are some methods (entire Classes and Activities are too huge to add them here, but they are available on GitHub) that deal with my database:
Inside AlarmListActivity
public void setAlarmEnabled(long id, boolean isEnabled){
AlarmManagerHelper.cancelAlarms(this);
AlarmModel model = dbHelper.getAlarm(id);
if(model!=null) {
model.isEnabled = isEnabled;
dbHelper.updateAlarm(model);
}
//mAdapter.setAlarms(dbHelper.getAlarms());
//mAdapter.notifyDataSetChanged();
AlarmManagerHelper.setAlarms(this);
}
public void deleteAlarm(long id) {
final long alarmId = id;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please confirm deletion")
.setTitle("Delete alarm?")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Cancel Alarms
AlarmManagerHelper.cancelAlarms(mContext);
//Delete alarm from DB by id
dbHelper.deleteAlarm(alarmId);
//Refresh the list of the alarms in the adaptor
mAdapter.setAlarms(dbHelper.getAlarms());
//Notify the adapter the data has changed
mAdapter.notifyDataSetChanged();
//Set the alarms
AlarmManagerHelper.setAlarms(mContext);
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
mAdapter.setAlarms(dbHelper.getAlarms());
mAdapter.notifyDataSetChanged();
/*if(dbHelper.getAlarms() == null){
throw new NullPointerException("told ya db was empty!");
}*/
}
}

Updating specific column using a spinner widget

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

Content of the result of aggregation query not returned

I am a begineer and I want to allow just one user to sign up as per the demand of my project.
The SIGNUP.java is meant to accomplish it using DbHelper.java but things work fine for
c.getCount()
but not for
Integer.parseInt(c.getString(0))
SIGNUP.java reads:
package com.bishal.android.taskmanager;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SIGNUP extends Activity {
Button register;
private EditText etName;
private EditText etEmail;
//private EditText etUsername;
private EditText etPassword;
private DbHelper dbhelper;
AlertDialogManager alert = new AlertDialogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
dbhelper=new DbHelper(this);
etName=(EditText)findViewById(R.id.edit_name);
etEmail=(EditText)findViewById(R.id.edit_email);
etPassword=(EditText)findViewById(R.id.edit_signup_password);
register=(Button)findViewById(R.id.signup);
final boolean bregister=(dbhelper.NoOfUser()==0)?true:false;
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//String UserNameValue=etUsername.getText().toString();
String NameValue=etName.getText().toString();
String EmailValue=etEmail.getText().toString();
String PasswordValue=etPassword.getText().toString();
//Toast.makeText(SIGNUP.this,dbhelper.ThereIsUser(), Toast.LENGTH_LONG).show();
if (bregister){
ACCOUNT_INFO account=new ACCOUNT_INFO(NameValue,EmailValue,PasswordValue);
if(NameValue.trim().length()>0 && EmailValue.trim().length() > 0 && PasswordValue.trim().length() >0){
if(dbhelper.eMailValidation(EmailValue)){
if(dbhelper.validateregister(EmailValue)){
dbhelper.addAccount(account);
Toast.makeText(SIGNUP.this, "Your account has been sucessfully created.", Toast.LENGTH_LONG).show();
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Username/Email already exists.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this,"Signup failed..", "Email address is not in such form.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Please enter empty fields.", false);
}
}
}
});
}
}
DbHelper.java reads(why 'count' is not returned as count of number of rows in table?):
package com.bishal.android.taskmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
//import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DbHelper extends SQLiteOpenHelper{
private static final String TAG=DbHelper.class.getSimpleName();
public static final String DB_NAME="Store Account.db";
public static final int DB_VERSION=1;
public static final String TABLE="Account_Info";
public static final String COL_ID="Id"; //special for ID
public static final String COL_NAME="Name";
public static final String COL_EMAIL="Email";
//public static final String COL_UNAME="Username";
public static final String COL_PASSWORD="Password";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_ACCOUNT_INFORMATION = "CREATE TABLE " + TABLE + "("
+ COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " String,"
+ COL_EMAIL + " String," + COL_PASSWORD + " String" + ")";
Log.d(TAG, "onCreate sql: "+CREATE_ACCOUNT_INFORMATION);
db.execSQL(CREATE_ACCOUNT_INFORMATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exists " + TABLE);
Log.d(TAG,"onUpdate dropped table "+ TABLE);
onCreate(db);
}
void addAccount(ACCOUNT_INFO account){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(COL_NAME,account.getNAME());
values.put(COL_EMAIL,account.getEMAIL());
//values.put(COL_UNAME, account.getUSERNAME());
values.put(COL_PASSWORD, account.getPASSWORD());
db.insert(TABLE, null, values);
db.close();
}
public boolean validateuser(String email,String password){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email +"'AND "+COL_PASSWORD+"='" + password+"'" , null);
if(c.getCount()>0)
return true;
else
return false;
}
public boolean validateregister(String email){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email+"'" , null);
if(c.getCount()>0)
return false;
else
return true;
}
public boolean eMailValidation(String emailValue) {
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern=Pattern.compile(EMAIL_PATTERN);;
Matcher matcher;
matcher = pattern.matcher(emailValue);
return matcher.matches();
}
public int NoOfUser() {
Cursor c=getReadableDatabase().rawQuery("SELECT count(*) FROM " + TABLE, null);
int count=Integer.parseInt(c.getString(0));
return count;
}
}

Categories