Android why does my checkDB keep giving false? - java

I'm trying to create a button that switches to one of 2 activities based on whether a database exists. I've made a databasecheckhelper but for some reason it keeps giving out false, even though the database exists.
code on clicking the button:
public void open_my_training(View view) {
Intent intent;
boolean databaseExists = checkDatabase.checkDB(this);
if(databaseExists){
intent = new Intent(this, a.class);
}else{
intent = new Intent(this, b.class);
}
startActivity(intent);
}
the helper
public class checkDatabase {
public static boolean checkDB(Context context) {
File dbFile = context.getDatabasePath("database.db");
return dbFile.exists();
}
}
Can anyone tell me what i'm doing wrong?
edit:
since the code seems to be fine i'll add my code for creating the database:
public void save_training(View view) {
CheckBox box1 = (CheckBox) findViewById(R.id.box1);
CheckBox box2 = (CheckBox) findViewById(R.id.box2);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
String spinner1 = spinner1.getSelectedItem().toString();
createDatabase();
addTraining(box1.isChecked(), box2.isChecked(), spinner1);
}
private void createDatabase() {
try {
trainingDB = this.openOrCreateDatabase("database.sqlite", MODE_PRIVATE, null);
trainingDB.execSQL("CREATE TABLE IF NOT EXISTS table1" + "(id integer primary key," +
"box1 boolean, box2 boolean, + "spinner1 VARCHAR);");
}
private void addTraining(boolean box1Checked, boolean box2Checked, String spinner1) {
trainingDB.execSQL("INSERT INTO table1 (box1, box2, spinner1) VALUES ('"+ box1Checked + "', '" +
box2Checked + "', '" + spinner1 + "');");
}

Replace
File dbFile = context.getDatabasePath("database.sqlite");
instead of
File dbFile = context.getDatabasePath("database.db");

Related

SQL Lite Data not being inserted (Android Studio in java)

I want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
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)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!

Refreshing my ListView within my Cursor Adapter?

Long time lurker - first post:
Problem: When I click an imagebutton (basically just checkboxes) they will update my database row correctly and change the image to the proper boolean. However when I click them again - it does not re-update and gives off the same message.
What I think the problem is: I am rather new to Android but I'm pretty sure while my database is updating correctly my bindview variables are not?
My Cursor Adapter BindView:
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
final String id = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_ID));
final String name2 = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_NAME));
final String gift = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_GIFT));
final String specs = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_SPECIFICS));
final String store = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_STORE));
final String url = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_URL));
final String status = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_STATUS));
ImageButton checkBoxImage = (ImageButton) view.findViewById(R.id.ID_ROW_CHECKBOX);
if(status.equals("true"))
{
checkBoxImage.setImageResource(R.drawable.icon_yes);
} else {
checkBoxImage.setImageResource(R.drawable.icon_no);
}
checkBoxImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(status.equals("true"))
{
ContentValues values = new ContentValues();
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "false");
DBHELPER dbhelper = new DBHELPER(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "FALSE UPDATED");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_no);
db.close();
} else {
DBHELPER dbhelper = new DBHELPER(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "true");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_yes);
System.out.println("BEFORE : " + status);
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "TRUE UPDATED");
db.close();
}
}
});
What I have tried: So I click an image and it'll go from "checked" to "unchecked" or visa versa however only allows it once unless I reload the list.
What I've tried: Requery kept coming up but that is now considered outdated and to be avoided. I saw a few posts talking about swapping out the query for a new one but I kept getting a null error so I am unsure if that is the answer and I am just misunderstanding something or what.
Thanks, appreciate you guys.
if statement inside of OnClickListener is not checking with the latest value of status column. You need to read it again inside of OnClickListener. Change code like this:
checkBoxImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHELPER dbhelper = new DBHELPER(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
String[] columns = new String[]{DBHELPER.WISHLIST_COLUMN_NAME, DBHELPER.WISHLIST_COLUMN_GIFT, DBHELPER.WISHLIST_COLUMN_SPECIFICS, DBHELPER.WISHLIST_COLUMN_STORE, DBHELPER.WISHLIST_COLUMN_URL, DBHELPER.WISHLIST_COLUMN_STATUS};
Cursor cursor2 = db.query(DBHELPER.WISHLIST_TABLE_NAME, columns, null, null, null, null, null);
String status2 = cursor2.getString(cursor2.getColumnIndex(DBHELPER.WISHLIST_COLUMN_STATUS));
if("true".equals(status2)) {
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "false");
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "FALSE UPDATED");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_no);
} else {
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "true");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_yes);
System.out.println("BEFORE : " + status2);
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "TRUE UPDATED");
}
db.close();
}
});
The following code should be placed inside of the onClick method:
if(status.equals("true"))
{
checkBoxImage.setImageResource(R.drawable.icon_yes);
} else {
checkBoxImage.setImageResource(R.drawable.icon_no);
}
By the way, your code should be cleaner. The declaration of values must be outside the if statement

Copy and display data from one sqlite table to another at runtime

I am trying to make an android application that allows the user to create a custom workout list from an already existing list of workouts. I decided to create an sqlite database to accomplish this task. In my database handler class "DBHandles.java" I have created and populated "Table_Workouts" with all the available workouts in the application. Also in "DBHandles.java" I have created another empty table "Table_User_List" for the purpose of holding specific entries from the "Table_Workouts" table that the user selects. "Table_User_List" needs to be populated at runtime.
public class DBhandles extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Workouts.db";
public static final String TABLE_WORKOUTS = "Workouts";
public static final String TABLE_USER_LIST = "UserWorkouts";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_LINK = "link";
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_WORKOUTS_TABLE = "CREATE TABLE " +
TABLE_WORKOUTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
String CREATE_USER_TABLE ="CREATE TABLE " +
TABLE_USER_LIST + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
db.execSQL(CREATE_WORKOUTS_TABLE);
db.execSQL(CREATE_USER_TABLE);
db.execSQL("INSERT INTO " + TABLE_WORKOUTS + "(name, description, link) VALUES ('Shoulder Press', 'Shoulder PRess description', 'https://www.youtube.com/watch?v=qEwKCR5JCog')");
public void addWorkout(Workout workout) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, workout.getWorkoutName());
values.put(COLUMN_DESCRIPTION, workout.getDescription());
values.put(COLUMN_LINK, workout.getLink());
db.insert(TABLE_USER_LIST, null, values);
} catch (Exception e){
Log.d(TAG, "Error while trying to add");
}
finally{
db.endTransaction();
}
//db.close();
}
public Workout findWorkout(String Workoutname) {
String query = "SELECT * FROM " + TABLE_WORKOUTS
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
workout.setID(Integer.parseInt(cursor.getString(0)));
workout.setWorkoutName(cursor.getString(1));
workout.setDescription((cursor.getString(2)));
workout.setLink(cursor.getString(3));
cursor.close();
} else {
workout = null;
}
db.close();
return workout;
}
public boolean deleteWorkout(String Workoutname) {
boolean result = false;
String query = " SELECT * FROM " + TABLE_USER_LIST
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
workout.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_WORKOUTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(workout.getID()) });
cursor.close();
result = true;
}
db.close();
return result;
}
public ArrayList getAllWorkoutNames (){
return genericGetSQL(TABLE_WORKOUTS, COLUMN_NAME);
}
public ArrayList genericGetSQL(String whichTable, String whichColumn){
ArrayList<String> wrkArray = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(whichTable, new String[]{whichColumn}, null,null, null, null,null);
String fieldToAdd = null;
if(cursor.moveToFirst()){
while(cursor.isAfterLast()==false){
fieldToAdd = cursor.getString(0);
wrkArray.add(fieldToAdd);
cursor.moveToNext();
}
cursor.close();
}
return wrkArray;
}
As you can see I am returning an Arraylist from the DBHandles.class to display the name column of the "Table_Workouts" table. This ArrayList is accessed in my "DisplayAllWorkouts.java" class. The "DiplayAllWorkouts.java" class generates a tablerow for each entry in the "Table_Workouts" table and displays the name column to the user.
public class DisplayAllWorkouts extends AppCompatActivity implements YourListFrag.OnFragmentInteractionListener {
DBhandles db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayworkoutlist);
yourListFrag = new YourListFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.LinLayDisplayYourList, yourListFrag, "ARG_PARAM1").
commit();
context = this;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText = {"NAME ", " ADD "};
for (String c : headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
db = yourListFrag.getDb();//new DBhandles(this, null, null, 1);
final ArrayList<String> arrNames = db.getAllWorkoutNames();
final ArrayList<String> arrDesc = db.getAllWorkoutDescription();
final ArrayList<String> arrLink = db.getAllWorkoutsLink();
for (int i = 0; i < arrNames.size(); i++) {
TableRow row = new TableRow(this);
final CheckBox AddBox = new CheckBox(this);
AddBox.setText("ADD");
final TextView nametv = new TextView(this);
//final TextView desctv = new TextView(this);
//final TextView linktv = new TextView(this);
nametv.setTextSize(30);
// desctv.setTextSize(30);
nametv.setText(arrNames.get(i));
//desctv.setText(arrDesc.get(i));
//linktv.setText(arrLink.get(i));
text = nametv.getText().toString();
row.addView(nametv);
row.addView(AddBox);
AddBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// if(AddBox.isChecked()){
Workout wrk = (db.findWorkout(text));
db.addWorkout(wrk);
yourListFrag.refresh();
// yourListFrag.refresh();
// yourListFrag.refresh(text);
// }
// else{
// db.deleteWorkout(text);
//yourListFrag.delete(nametv.getText().toString());
// yourListFrag.refresh();
// }
}
});
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DisplayAllWorkouts.this, DisplaySingleWorkout.class);
i.putExtra("itemName", nametv.getText());
i.putStringArrayListExtra("everydesc", arrDesc);
i.putStringArrayListExtra("everyname", arrNames);
i.putStringArrayListExtra("everylink",arrLink);
startActivity(i);
}
});
tableLayout.addView(row);
}
}
#Override
public void onFragmentInteraction(int position) {
}
}
My problem is as follows. I want to be able to click on a table row displayed in the "DisplayAllWorkouts.java" class and have the corresponding row in "Table_Workouts" table be copied to the "Table_User_List" table. Once the row is copied I want the name column of "Table_User_List" displayed in "YourListFrag.java" class and inflated in the "DisplayAllWorkouts.java" class.
public class YourListFrag extends Fragment {
private ArrayAdapter<String> arrayAdapter;
private ListView lstView;
public ArrayList<String> holdNamesFromDB;
final DBhandles db = new DBhandles(getContext(), null, null, 1);
public DBhandles getDb(){
return this.db;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_list, container, false);
lstView = (ListView)rootView.findViewById(R.id.lstView);
holdNamesFromDB = db.getAllUserWorkouts();
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, holdNamesFromDB);
lstView.setAdapter(arrayAdapter);
public void refresh(){//String text){
//arrayAdapter.add(text);
// db.getAllUserWorkouts();
// arrayAdapter.notifyDataSetChanged();
holdNamesFromDB = db.getAllUserWorkouts();
//arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, db.getAllUserWorkouts());
arrayAdapter.notifyDataSetChanged();
// arrayAdapter.notifyDataSetChanged();
//
}
I need the fragment to refresh its view everytime a new entry is added to the "Table_User_List" so the user can see every entry of the name column of "Table_User_List" in real time. I put logs in my program and the the flow seemed to successfully reach all the appropriate method calls without throwing an error or crashing. However, my program does not display the entries from Table_User_List in the "YourListFrag.java" class. I don't know if their is a problem copying the row from one sqlite table to the other, displaying and refershing the name column in the fragment or inflating the fragment into "DisplayAllWorkouts.java" class. I have been struggling with this problem for awhile now and I finally decided to reach out to the community that has always been there for me. I have referenced the following sqlite copy data from one table to another
and i can't tell if this approach actually works in my program because nothing is displayed in the fragment. Thank you for your time and effort. I apologize for the lines of code i commented out and posted. I have been trying everything i could think of.

every time creating database after insert a row in android sql

#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
EditText USER_NAME, USER_PASS, CON_PASS, USER_EMAIL;
String user_name, user_pass, con_pass, user_email;
Button REG;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
USER_NAME = (EditText) findViewById(R.id.reg_user);
USER_PASS = (EditText) findViewById(R.id.reg_pass);
CON_PASS = (EditText) findViewById(R.id.con_pass);
USER_EMAIL = (EditText) findViewById(R.id.reg_email);
REG = (Button) findViewById(R.id.user_reg);
REG.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
user_name = USER_NAME.getText().toString();
user_pass = USER_PASS.getText().toString();
con_pass = CON_PASS.getText().toString();
user_email = USER_EMAIL.getText().toString();
if (!(user_pass.equals(con_pass))) {
Toast.makeText(getBaseContext(), "Password are not matching", Toast.LENGTH_LONG).show();
USER_NAME.setText("");
USER_PASS.setText("");
CON_PASS.setText("");
USER_EMAIL.setText("");
} else {
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, user_name, user_pass, user_email);
Toast.makeText(getBaseContext(), "Registration is suessful", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
}
It is because you are creating table each time you insert a row. To solve this problem you need to change the create table query "CREATE TABLE 'TABLE_NAME' IF NOT EXISTS". The "IF NOT EXISTS" will restrict the system to create the database again if it is created once.
You are calling creating a new Table every time, you create an instance of DatabaseOperations - as your SQL statement 'CREATES'
Modify SQL_CREATE_ENTRIES to something like below
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + + " integer primary key autoincrement, "+
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
Edit
1) I've update query to include auto-increment your primary key
2) In your onUpgrade method add the line
db.execSQL("DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME);
This will delete the table when you change the version of DB.
Next, update the version of by 1, to 3.
Re-run app, it will be rebuild the DB table.

android java get spinner selected string value

I want to display the String number from mySpinner only inside my Toast but I can't find out to do just that thing. Any help is welcome!
if(cursor.moveToFirst())
{
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
while (pCur.moveToNext())
{
String name = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
list.add(name + "\n" + number);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
adapter stuff of no importance
spinnerClickListener();
}
Onclick method for imagebutton to display the selected contact phone number in a toast.
public void spinnerClickListener(){
//spinner item button onclick listener
callBTN = (ImageButton)findViewById(R.id.call);
mySpinner = (Spinner)findViewById(R.id.contacts);
callBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Selected number :" + "\n" + mySpinner.getSelectedItem(), Toast.LENGTH_LONG).show();
}
});
}
thanks in advance!
you should use this
mySpinner.getSelectedItem().toString()
instead of
mySpinner.getSelectedItem()

Categories

Resources