I am trying to create password manager app that the user can manage her password in any websites.
The user need to fill 3 fields - Website, Username and Password.
Behind the scenes, the data should be insert to the database in SQLite but I think that the database not open, because I cant see the database folder in path: /data/data/MY_APP/
this is MySQLiteHelper: http://pastebin.com/4ZWJuS5W
package db_pkg;
import java.io.UTFDataFormatException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class MySQLiteHelper
{
public static final String DB_NAME = "mu_dbname";
public static final String TASKS_TABLE = "passwords";
public static final int DB_VER = 1;
public static final String TASK_ID = "_id";
public static final String TASK_WEB = "web";
public static final String TASK_USER = "user";
public static final String TASK_PASSWORD = "password";
// public static final String TASK_LAT = "lat";
// public static final String TASK_LNG = "lng";
private static final String SCRIPT_CREATE_DB = "create table "
+ TASKS_TABLE + "(" + BaseColumns._ID
+ " integer primary key autoincrement, " + TASK_WEB
+ " text not null, " + TASK_USER + " text not null, "
+ TASK_PASSWORD + " text not null" + ");";
private Context context;
private MyDBHelper myDBHelper;
public MySQLiteHelper(Context context)
{
this.context = context;
this.myDBHelper = new MyDBHelper(this.context);
}
public void addTaskItem(addPassword item)
{
SQLiteDatabase database = myDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_WEB, item.getWebsite());
values.put(TASK_USER, item.getUsername());
values.put(TASK_PASSWORD, item.getPassword());
database.insert(TASKS_TABLE, null, values);
database.close();
}
public boolean updateItemById(int taskID, addPassword item)
{
SQLiteDatabase database = myDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_WEB, item.getWebsite());
values.put(TASK_USER, item.getUsername());
values.put(TASK_PASSWORD, item.getPassword());
boolean b = database.update(TASKS_TABLE, values,
TASK_ID + "=" + taskID, null) > 0;
database.close();
return b;
}
public boolean deleteTaskItemById(int taskID)
{
SQLiteDatabase database = myDBHelper.getWritableDatabase();
boolean b = database.delete(TASKS_TABLE, TASK_ID + "=" + taskID, null) > 0;
return b;
}
public Cursor getCursorALL()
{
Cursor cursor;
SQLiteDatabase database = myDBHelper.getReadableDatabase();
cursor = database.query(TASKS_TABLE,
new String[] { TASK_ID,TASK_WEB,TASK_USER,TASK_PASSWORD},
null,null, null, null, null);
return cursor;
}
//testing Debugging
public void printAllCursorDB()
{
Cursor cursor=getCursorALL();
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
StringBuffer st=new StringBuffer();
st.append("ID:"+cursor.getString(0));
st.append(" Text:"+cursor.getString(1));
st.append(" Phone:"+cursor.getString(2));
st.append(" Priority:"+cursor.getString(3));
Log.d("MyTasksDBMngr", st.toString());
cursor.moveToNext();
}
cursor.close();
}
private class MyDBHelper extends SQLiteOpenHelper
{
public MyDBHelper(Context context)
{
super(context, DB_NAME, null, DB_VER);
Log.i("MyDBHelper", "Constructor");
}
#Override
public void onCreate(SQLiteDatabase db)
{
String sqlst = String.format("drop table if exists %s;",
TASKS_TABLE);// משפט למחיקת הטבלה
db.execSQL(sqlst);
db.execSQL(SCRIPT_CREATE_DB);
Log.i("MyDBHelper", "onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
onCreate(db);
}
}
}
this is addPassword:
http://pastebin.com/e17CQ6mF
package db_pkg;
public class addPassword {
String website, username, password;
int id;
public addPassword()
{
}
public addPassword(String website, String username, String password, int id) {
this.website = website;
this.username = username;
this.password = password;
this.id = id;
}
public addPassword(String website, String password, int id) {
this.website = website;
this.id = id;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWebsite() {
return website;
}
public void setWebsite(String web) {
if(web.length() < 2)
{
this.website = web;
}
}
public String getUsername() {
return username;
}
public void setUsername(String user) {
this.username = user;
}
public String getPassword() {
return password;
}
public void setPassword(String pass) {
this.password = pass;
}
}
this is my Activity:
package com.appweb.passwordmanager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import db_pkg.MySQLiteHelper;
import db_pkg.addPassword;
public class newPassword extends AppCompatActivity {
private MySQLiteHelper niv;
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0) {
return false;
} else {
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_password);
final EditText website = (EditText) findViewById(R.id.website);
final EditText username = (EditText) findViewById(R.id.username);
final EditText password = (EditText) findViewById(R.id.password);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isEmpty(password))
{
if(!isEmpty(website))
{
addPassword item = new addPassword(website.getText().toString(),
username.getText().toString(),
password.getText().toString(),
0);
niv.addTaskItem(item);
}
}
}
});
}
}
#Ramzi
SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database.
At First Please read
Android SQLite Database
Android SQLite Database Tutorial
Example
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}
Related
I have been searching for hours but still I can't find any way on how to update a listview using the listview.setOnItemLongClickListener I have tried but I think I am doing it all wrong. Does anyone know how to edit a listview after a longclick listener?
DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final String TEST_TABLE = "TEST_TABLE";
public static final String TEST_NAME = "NAME";
public static final String COLUMN_NAME = TEST_NAME;
public static final String COLUMN_ADDRESS = "ADDRESS";
public static final String COLUMN_ID = "ID";
public static final String TEST_AGE = "age";
public DBHelper(#Nullable Context context) {
super(context, "test.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTableStatement = "CREATE TABLE " + TEST_TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_ADDRESS + " TEXT)";
sqLiteDatabase.execSQL(createTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public boolean addData(TestModel testModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, testModel.getName());
cv.put(COLUMN_ADDRESS, testModel.getAddress());
long insert = db.insert(TEST_TABLE, null, cv);
if (insert == -1) {
return false;
} else {
return true;
}
}
public boolean deleteData(TestModel testModel) {
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM " + TEST_TABLE + " WHERE " + COLUMN_ID + " = " + testModel.getID();
Cursor cursor = db.rawQuery(queryString, null);
if (cursor.moveToFirst()) {
return true;
} else {
return false;
}
}
public void update(TestModel testModel) {
}
public List<TestModel> viewAll() {
List<TestModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + TEST_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
TestModel newTest = new TestModel(id, name, address);
returnList.add(newTest);
} while (cursor.moveToNext());
} else {
}
cursor.close();
db.close();
return returnList;
}
}
TestModel
public class TestModel {
private int ID;
private String name;
private String address;
public TestModel(int ID, String name, String address) {
this.ID = ID;
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "ID:" + ID +
", name:'" + name + '\'' +
", address:'" + address + '\'' +
'}';
}
public TestModel() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
MainActivity
package com.example.crudtest2;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btn_Add, btn_View;
EditText et_name, et_address, et_username;
ListView lv_allList;
ArrayAdapter testArrayAdapter;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_Add = findViewById(R.id.btnAdd);
btn_View = findViewById(R.id.btnView);
et_name = findViewById(R.id.inputName);
et_address = findViewById(R.id.inputAddress);
lv_allList = findViewById(R.id.listviewData);
dbHelper = new DBHelper(MainActivity.this);
showAllData(dbHelper);
btn_Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TestModel testModel;
try {
testModel = new TestModel(-1, et_name.getText().toString(), et_address.getText().toString());
Toast.makeText(MainActivity.this, "Successfully Added", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error adding", Toast.LENGTH_SHORT).show();
testModel = new TestModel(-1, "error", "error");
}
DBHelper dbHelper = new DBHelper(MainActivity.this);
dbHelper.addData(testModel);
showAllData(dbHelper);
}
});
btn_View.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBHelper dbHelper = new DBHelper(MainActivity.this);
showAllData(dbHelper);
//Toast.makeText(MainActivity.this, dbHelper.viewAll().toString(), Toast.LENGTH_SHORT).show();
}
});
lv_allList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TestModel clickedData = (TestModel) adapterView.getItemAtPosition(i);
dbHelper.deleteData(clickedData);
showAllData(dbHelper);
Toast.makeText(MainActivity.this, "Data Deleted Successfully", Toast.LENGTH_SHORT).show();
}
});
lv_allList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
TestModel clickedData = (TestModel) adapterView.getItemAtPosition(i);
dbHelper.updateData(clickedData);
return true;
}
});
}
private void showAllData(DBHelper dbHelper) {
testArrayAdapter = new ArrayAdapter<TestModel>(MainActivity.this, android.R.layout.simple_list_item_1, dbHelper.viewAll());
lv_allList.setAdapter(testArrayAdapter);
}
}
Is there like any way to edit my listview once a longclick listener event has happened? I have tried doing the same thing with delete it's because I don't have really any idea how to edit a listview after a longclick.
I'm following this tutorial (https://www.youtube.com/watch?v=hDSVInZ2JCs&t=3615s&ab_channel=SoftwareandProgrammingwithProfessorSluiter)
Everything works great, until I try this line of code :
lv_productList.setAdapter(productArrayAdapter);
then the app crashes. I've looked online and tried a bunch of stuff but I'm super stuck
Here's the problem area
btn_viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
List<ProductModel> all = dataBaseHelper.getAll();
ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
lv_productList.setAdapter(productArrayAdapter);
Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
}
});
here's my full code
MainActivity.java
package com.example.sqldemo;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//reference to all buttons and controls on the layout
Button btn_add, btn_viewAll;
EditText et_name, et_number;
ListView lv_productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_add = findViewById(R.id.btn_add);
btn_viewAll = findViewById(R.id.btn_viewAll);
et_name = findViewById(R.id.et_name);
et_number = findViewById(R.id.et_number);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductModel productModel;
try {
productModel = new ProductModel(-1, et_name.getText().toString(), Integer.parseInt(et_number.getText().toString()));
Toast.makeText(MainActivity.this, productModel.toString(), Toast.LENGTH_SHORT).show();
}
catch(Exception err) {
Toast.makeText(MainActivity.this, "Error creating product", Toast.LENGTH_SHORT).show();
productModel = new ProductModel(-1, "error", 0);
}
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
boolean success = dataBaseHelper.addOne(productModel);
Toast.makeText(MainActivity.this, "Success! Product has been added to the database :)", Toast.LENGTH_SHORT).show();
}
});
btn_viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
List<ProductModel> all = dataBaseHelper.getAll();
ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
lv_productList.setAdapter(productArrayAdapter);
Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
DataBaseHelper.java
package com.example.sqldemo;
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 DataBaseHelper extends SQLiteOpenHelper {
public static final String PRODUCT_TABLE = "PRODUCT_TABLE";
public static final String COLUMN_PRODUCT_NAME = "PRODUCT_NAME";
public static final String COLUMN_PRODUCT_NUMBER = "PRODUCT_AGE";
public static final String COLUMN_ID = "ID";
public DataBaseHelper(#Nullable Context context) {
super(context, "Products.db", null, 1);
}
//this is called the first item a database is accessed. used to create a new database
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + PRODUCT_TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_PRODUCT_NAME + " TEXT, " + COLUMN_PRODUCT_NUMBER + " INT)";
db.execSQL(createTableStatement);
}
//this is called if the database version number changes. It prevents previous users apps from breaking when the database is updated
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addOne(ProductModel productModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PRODUCT_NAME, productModel.getName());
cv.put(COLUMN_PRODUCT_NUMBER, productModel.getNumber());
//long insert returns positive in data insertion was successful, and negative if it was not
long insert = db.insert(PRODUCT_TABLE, null, cv);
if (insert == -1) {
return false;
}
else {
return true;
}
}
public List<ProductModel> getAll() {
List<ProductModel> returnList = new ArrayList<>();
// get data from the database
String queryString = "SELECT * FROM " + PRODUCT_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
//move the cursor to the first set of data and check if anything was returned
if (cursor.moveToFirst()) {
// loop through the cursor (result set) and create new product objects. Put them into the return list (defined above)
do {
int productID = cursor.getInt(0);
String productName = cursor.getString(1);
int productNumber = cursor.getInt(2);
ProductModel newProduct = new ProductModel(productID, productName, productNumber);
returnList.add(newProduct);
} while (cursor.moveToNext());
}
else {
//if no results from database, don't add anything to the list.
}
cursor.close();
db.close();
return returnList;
}
}
ProductModel.java
package com.example.sqldemo;
//declare a new public class/object with 3 variables
public class ProductModel {
private int id;
private String name;
private int number;
//constructor
public ProductModel(int id, String name, int number) {
this.id = id;
this.name = name;
this.number = number;
}
public ProductModel() {
}
// toString is necessary for printing the contents of a class object
#Override
public String toString() {
return "ProductModel{" +
"id=" + id +
", name='" + name + '\'' +
", number=" + number +
'}';
}
//getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
> Blockquote
You can simply change RecyclerView to ListView.
Or
if you want to use RecyclerView, you have to create a custom Recyclerview Adapter.
Here a Beginner friendly Guide: https://medium.com/#suhanshupatel/recyclerview-in-android-for-beginner-cfbc132a0dec
Thanks for helping me fix my problem!
Issue
The issue is that the data never gets saved into the database, which it did before, but then i updated the database version and now it does not.
Is there an error thrown? Yes there is and its right down below.
E/SQLiteLog: (1) near "0": syntax error
E/SQLiteDatabase: Error inserting 0=20 id=csdfergeg userid=csdfergeg email=erregegergr
android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO Info(0,id,userid,email) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1417)
at com.vikkivuk.mxelevator.Database.addUserInfo(Database.java:50)
at com.vikkivuk.mxelevator.finishScene$1.onClick(finishScene.java:61)
at android.view.View.performClick(View.java:6294)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
My code:
Database Class:
package com.vikkivuk.mxelevator;
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 Database extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " TEXT," + KEY_EMAIL + " TEXT," + Integer.parseInt(KEY_CODE) + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, info.UserId);
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo(){
List<UserInfo> results = new ArrayList<UserInfo>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[] {String.valueOf(info.ID)});
db.close();
}
}
UserInfo:
package com.vikkivuk.mxelevator;
public class UserInfo {
public String ID;
public String UserId;
public String Email;
public String CODE;
public UserInfo(String uid, String mail, String el_code){
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(String userId, String uid, String mail, String el_code){
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
UserInfoAdapter:
package com.vikkivuk.mxelevator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
public class UserInfoAdapter extends ArrayAdapter<UserInfo> {
public UserInfoAdapter(Context context, List<UserInfo> info) {
super(context, 0, info);
}
public View getView(int position, View convertView, ViewGroup parent){
UserInfo info = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.user_info_item_row, parent, false);
}
TextView uid = convertView.findViewById(R.id.textview_userid);
TextView email = convertView.findViewById(R.id.textview_email);
TextView textcode = convertView.findViewById(R.id.codetext);
uid.setText(info.UserId);
email.setText(info.Email);
textcode.setText(info.CODE);
return convertView;
}
}
Finish scene:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.Random;
public class finishScene extends AppCompatActivity {
EditText userId, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish_scene);
userId = findViewById(R.id.userid);
email = findViewById(R.id.email);
CheckBox agreeCheck = findViewById(R.id.agreeCheck1);
Boolean checked = agreeCheck.isChecked();
Button submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userId.length() < 5) {
Toast.makeText(getApplicationContext(), "Your UID is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (email.length() < 6) {
Toast.makeText(getApplicationContext(), "Your EMAIL is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (!agreeCheck.isChecked()) {
Toast.makeText(getApplicationContext(), "Please check the agree box!", Toast.LENGTH_SHORT).show();
return;
} else {
Random rand = new Random();
int int_random1 = rand.nextInt(10000);
int int_random2 = rand.nextInt(10);
int int_random3 = rand.nextInt(10);
int int_random4 = rand.nextInt(15);
int int_random5 = rand.nextInt(25);
int random_code = int_random1 + int_random2 + int_random3 + int_random4 + int_random5;
Database db = new Database(finishScene.this);
UserInfo info = new UserInfo(userId.getText().toString(), email.getText().toString(), String.valueOf(random_code));
db.addUserInfo(info);
db.close();
userId.setText("");
email.setText("");
Toast.makeText(getApplicationContext(), "Data saved! Pending approval...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(userId.getContext(), Success.class);
startActivity(intent);
}
}
});
}
}
ShowData:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShowData extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
List<UserInfo> info = new Database(this).getUserInfo();
UserInfoAdapter adapter = new UserInfoAdapter(this, info);
ListView listView = findViewById(R.id.userInfoList);
listView.setAdapter(adapter);
Button goback = findViewById(R.id.goback1);
goback.setOnClickListener(v -> {
Intent intent = new Intent(goback.getContext(), MainActivity.class);
startActivity(intent);
});
}
}
That's all of my classes. Also, I would like to specify that I don't actually know what database versions are since I started with the android studio 3 days ago.
please try this I implemented some change on the UserInfo class
the Id must be an integer and you add a String
database.java
public class MyBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public MyBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " INTEGER," + KEY_EMAIL + " TEXT," + KEY_CODE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// contentValues.put(KEY_ID, info.UserId); i removed this
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo() {
List<UserInfo> results = new ArrayList<>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[]{String.valueOf(info.ID)});
db.close();
}
}
and UserInfo :
public class UserInfo {
public int ID;
public int UserId;
public String Email;
public int CODE;
public UserInfo(int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(int userId, int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
i hope that's help you
At first the app would just crash when I started it with an emulator, Not sure what I changed to get it to run but now it will run the onCreate method however, when I implement the addButtonClicked method the app just stalls and the Android Monitor displays "Suspending all threads" every few seconds and I'm not sure where to even begin debugging. Any pointers in the right direction would be greatly appreciated as I'm fairly new to Android development.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText testInput;
TextView testText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testInput = (EditText) findViewById(R.id.testInput);
testText = (TextView) findViewById(R.id.testText);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add product to database
public void addButtonClicked(View view){
Products product = new Products((testInput.getText().toString()));
dbHandler.addProduct(product);
printDatabase();
}
// Delete Items
public void deleteButtonClicked(View view){
String inputText = testText.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
testText.setText(dbString);
testInput.setText("");
}
}
Products.java
public class Products {
private int _id;
private String _productname;
public Products(){
}
public Products(String productname) {
this._productname = productname;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public int get_id() {
return _id;
}
public String get_productname() {
return _productname;
}
}
MyDBHandler.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS +"(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLUMN_PRODUCTNAME +" TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete product from database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
//Print of DB as sting
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname"))!= null){
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
for your databaseToString method you are performing a retrieve operation. You should be doing a read operation in a thread other than UI thread. Try fetching in AsyncTask. It should work. Implementation for your databaseToString should be handled by AsyncTask.
Happy Coding..
I am new in Android development, And right now what I am trying to do is to save Message that I type and Username. I got this code from vogella.com, but it was written only for messages. And I have tried to add Username, but I get an error "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdatabaseactivity/com.example.testdatabaseactivity.TestDatabaseActivity}: android.database.sqlite.SQLiteException: no such column: SENDER (code 1): , while compiling: SELECT _id, SENDER, MESSAGE FROM MESSAGES"
And I can't figure out what Is wrong. Need a little help.
MessagesDataSource.java
package com.example.testdatabaseactivity;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class MessagesDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_SENDER, MySQLiteHelper.COLUMN_MESSAGE};
public MessagesDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Message createMessage(String sender, String message) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_MESSAGE, message);
values.put(MySQLiteHelper.COLUMN_SENDER, sender);
long insertId = database.insert(MySQLiteHelper.TABLE_MESSAGES, null,values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,null, null, null);
cursor.moveToFirst();
Message newMessage = cursorToMessage(cursor);
cursor.close();
return newMessage;
}
public List<Message> getAllMessages() {
List<Message> messages = new ArrayList<Message>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Message message = cursorToMessage(cursor);
messages.add(message);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return messages;
}
private Message cursorToMessage(Cursor cursor) {
Message message = new Message();
message.setId(cursor.getLong(0));
message.setMessage(cursor.getString(2));
message.setSender(cursor.getString(1));
return message;
}
}
Message.java
package com.example.testdatabaseactivity;
public class Message {
private long id;
private String message;
private String sender;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return message;
}
}
MySQLiteHelper.java
package com.example.testdatabaseactivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_MESSAGES = "MESSAGES";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_MESSAGE = "MESSAGE";
public static final String COLUMN_SENDER = "SENDER";
private static final String DATABASE_NAME = "message.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_SENDER + "sender not null, "
+ COLUMN_MESSAGE + " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),"Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
onCreate(db);
}
}
TestDatabaseActivity.java
package com.example.testdatabaseactivity;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class TestDatabaseActivity extends ListActivity {
private MessagesDataSource datasource;
public String sender = "Suren";
EditText edittext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittext = (EditText) findViewById(R.id.txt_message);
datasource = new MessagesDataSource(this);
datasource.open();
List<Message> values = datasource.getAllMessages();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(this,android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
String text = edittext.getText().toString();
ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
Message message = null;
if(edittext.length() == 0){
return;
}else{
// save the new message to the database
message = datasource.createMessage(sender, text);
adapter.add(message);
edittext.getText().clear();
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Correct your CREATE Table Query need space between Column Name and Column Type
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_SENDER + " text not null, "
+ COLUMN_MESSAGE + " text not null);";
You Forget to add space over here in your Query COLUMN_SENDER + "sender not null, "
// Database creation sql statement
private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_MESSAGES + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SENDER + " text not null, "
+ COLUMN_MESSAGE + " text not null)";
"sender" is not a type. You need put "text".
And give the appropriate spaces.