Implementing SQLite into Android App - java

I am new to Android and I am making a simple Log in/Register app. At the moment my problem is that the SQLite database create is not executing meaning that it wont make my table. I have made:
Register.java
public class Register extends Activity implements View.OnClickListener {
EditText insertUsername, insertName, insertPassword, insertFinal;
Button create;
LoginDBAdapter loginHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_register);
insertUsername = (EditText) findViewById(R.id.insertUsername);
insertName = (EditText) findViewById(R.id.insertName);
insertPassword = (EditText) findViewById(R.id.insertPassword);
insertFinal = (EditText) findViewById(R.id.insertFinal);
}
#Override
protected void onDestroy(){
super.onDestroy();
close();
}
private void close() {
loginHandler.close();
}
private void open() {
loginHandler = new LoginDBAdapter(this);
loginHandler.open();
}
public void onClick(View v) {
String username = insertUsername.getText().toString();
String name = insertName.getText().toString();
String password = insertPassword.getText().toString();
String confirm = insertFinal.getText().toString();
//Validation for the fields
// check if any of the fields are vaccant
if (username.equals("") || password.equals("") || confirm.equals("")) {
Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirm)) {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
} else {
// Save the Data in Database
loginHandler.register(username, name, password);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
finish();
}
}
}
LoginAdapter.
public class LoginDBAdapter {
private SQLiteDatabase db;
private DataBaseHelper myHelp;
// Labels table name
public static final String TABLE_NAME = "Users";
private static final String DATABASE_NAME = "login.db";
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_Username = "Username";
public static final String KEY_name = "Name";
public static final String KEY_password = "Password";
// property help us to keep data
public int User_id;
public String Username;
public String Name;
public String Password;
public static final String DATABASE_CREATE = "create table "+ TABLE_NAME+
"(" + KEY_ID + " integer primary key autoincrement ,"
+ KEY_Username + "Username text not null, "
+ KEY_name + "Name text not null, "
+ KEY_password +"Password text not null);";
private final Context context;
public LoginDBAdapter(Context data) {
this.context = data;
myHelp = new DataBaseHelper(context);
}
public LoginDBAdapter open(){
db = myHelp.getWritableDatabase();
return this;
}
public void close(){
myHelp.close();
}
public long register(String username, String name, String password){
ContentValues newUser = new ContentValues();
newUser.put(KEY_Username, username);
newUser.put(KEY_name, name);
newUser.put(KEY_password, password);
//Inserting put information into a new row into Users table
return db.insert(TABLE_NAME, null, newUser);
}
public String authLogin(String username) {
Cursor cursor = db.query("Users", null, " Username= ?", new String[]{username}, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "Username does not exist";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("Password"));
cursor.close();
return password;
}
private static class DataBaseHelper extends SQLiteOpenHelper {
private static final int version = 1;
public DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, version);
}
//This is called if no database exists and DataBaseHelper will create a new one
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table "+ TABLE_NAME+
"(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ KEY_Username + "Username text not null, "
+ KEY_name + "Name text not null, "
+ KEY_password +"Password text not null)");
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase create_db, int oldVersion, int newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
//Destroy all data
create_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(create_db);
}
}
}
What have I done wrong? I had the project at one point pass the username, name and password passed to register but could not insert into table Users because it doesnt exist. I ran it through Android Device Monitor
No table: Users

There is a problem with your SQL statement.
+ KEY_Username + "Username text not null, "
This will render as
"UsernameUsername text not null, "
So you should probably change it to:
+ KEY_Username + " text not null, "
The same mistake is in other lines as well.

I think you are never calling this method
private void open() {
loginHandler = new LoginDBAdapter(this);
loginHandler.open();
}
from the Register class.
I suggest to change the onCreate method as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_register);
insertUsername = (EditText) findViewById(R.id.insertUsername);
insertName = (EditText) findViewById(R.id.insertName);
insertPassword = (EditText) findViewById(R.id.insertPassword);
insertFinal = (EditText) findViewById(R.id.insertFinal);
open();
}

use this code.it will help you out to create a table in sqlite as well as you can store the Registeration details too
Register.java
public class Register extends Activity implements View.OnClickListener {
EditText insertUsername, insertName, insertPassword, insertFinal;
Button create;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_register);
insertUsername = (EditText) findViewById(R.id.insertUsername);
insertName = (EditText) findViewById(R.id.insertName);
insertPassword = (EditText) findViewById(R.id.insertPassword);
insertFinal = (EditText) findViewById(R.id.insertFinal);
}
public void onClick(View v) {
String username = insertUsername.getText().toString();
String name = insertName.getText().toString();
String password = insertPassword.getText().toString();
String confirm = insertFinal.getText().toString();
//Validation for the fields
// check if any of the fields are vaccant
if (username.equals("") || password.equals("") || confirm.equals("")) {
Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirm)) {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
} else {
// Save the Data in Database
Intent intent1=new Intent(Register.this,LoginDBAdapter.class);
Bundle userdata=new Bundle();
userdata.putString("username",username);
userdata.putString("name",name);
userdata.putString("password",password);
userdata.putString("confirm",confirm );
intent1.putExtras(userdata);
startActivity(intent1);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
}
LoginDBAdapter.java
public class LoginDBAdapter extends Activity {
TextView text;
SQLiteDatabase mydb;
String username,name,password;
private static String DBNAME = "login.db"; // THIS IS THE SQLITE DATABASE FILE NAME.
private static String TABLE = "Users";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Bundle userdetails=getIntent().getExtras();
username= userdetails.getString("username");
name=userdetails.getString("name");
password=userdetails.getString("password");
text=(TextView)findViewById(R.id.txthead);
createTable();
insertIntoTable(username,name,password);
}
public void createTable(){
try
{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, Username TEXT,Name TEXT, Password TEXT);");
mydb.close();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
}
}
#SuppressLint("DefaultLocale")
public void onsearchclick(View view)
{
// Toast.makeText(getApplicationContext(), "subval of"+ subval+""+subval1+"",Toast.LENGTH_SHORT).show();
showTableValues();
}
public void insertIntoTable(String username,String name,String password){
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("INSERT INTO " + TABLE + "(Username,Name,Password) VALUES('"+username+"','"+name+"','"+password+"')");
mydb.close();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), ""+e.toString()+"", Toast.LENGTH_LONG).show();
//System.out.println(""+e.toString()+"");
}
}
The showTableValues will show the last entered username and password and name of the person
public void showTableValues()
{
try
{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor cursor=mydb.rawQuery("SELECT * FROM Users", null);
int x = cursor.getCount(); //this will return number of records in current cursor
Toast.makeText(getApplicationContext(), ""+x+"",Toast.LENGTH_SHORT).show();
if ( x == 0 )
{
//No rows are inserted in table
}
else
{
try
{
cursor.moveToFirst();
do {
String username=cursor.getString(cursor.getColumnIndex("Username")).toString();
String name=cursor.getString(cursor.getColumnIndex("Name")).toString();
String password=cursor.getString(cursor.getColumnIndex("Password")).toString();
String tempString="User Name: "+username.toString();
String tempString1="Name: "+""+name.toString();
String tempString2="Password: "+""+password.toString();
TextView text=(TextView)findViewById(R.id.txthead);
text.setText(tempString);
text.append(tempString1);
text.append(tempString2);
} while (cursor.moveToNext());
}
finally
{
cursor.close();
mydb.close();
}
// }
}
}
catch( Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
fragment_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/insertFinal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/final1"
android:layout_alignBottom="#+id/final1"
android:layout_alignParentRight="true"
android:ems="10"
android:hint="Confirm Password" >
</EditText>
<EditText
android:id="#+id/insertUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="Enter user name" />
<TextView
android:id="#+id/txtusername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/insertUsername"
android:layout_alignBottom="#+id/insertUsername"
android:layout_alignParentLeft="true"
android:text="User Name:" />
<Button
android:id="#+id/Register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="125dp"
android:padding="30dp"
android:text="Register"
android:onClick="onClick"/>
<TextView
android:id="#+id/final1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Register"
android:layout_alignParentLeft="true"
android:layout_marginBottom="78dp"
android:text="Confirm password" />
<TextView
android:id="#+id/Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/insertFinal"
android:layout_alignParentLeft="true"
android:layout_marginBottom="17dp"
android:text="Password" />
<EditText
android:id="#+id/insertPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Password"
android:layout_alignBottom="#+id/Password"
android:layout_alignParentRight="true"
android:ems="10"
android:hint="enter password" />
<EditText
android:id="#+id/insertName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/insertPassword"
android:layout_alignParentRight="true"
android:ems="10"
android:hint="Enter Name:" />
<TextView
android:id="#+id/txtname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/txtusername"
android:layout_alignTop="#+id/insertName"
android:text="Name:" />
</RelativeLayout>
activity_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show"
android:onClick="onsearchclick" ></Button>
<TextView
android:id="#+id/txthead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/show" />
</RelativeLayout>
in Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.login"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Register"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.login.LoginDBAdapter" />
</application>
</manifest>

Related

App stops working when clicked on Button coded to save, refresh and search

I need help fixing a problem with my 3 buttons that don't work properly and I'm not sure how to fix it. The "Save" button is to keep my database save, the "Refresh" button is to clear, and the "Search" button is to find an existing database. My TextView shows the existing database after registered. These are my goals to accomplish.
Here are my code files:
XML File:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_verticsl_margin"
android:paddingBottom="#dimen/activity_verticsl_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dip"
android:gravity="center"
android:text="Registration"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtid"
android:hint="ID"
android:inputType="number"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtfirstname"
android:hint="#string/first_name"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtlastname"
android:hint="#string/last_name"
android:layout_marginTop="5dip"
/>
<EditText
android:id="#+id/txtmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="#string/e_mail" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtuser"
android:hint="#string/username"
android:layout_marginTop="5dip"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtpw"
android:hint="#string/password"
android:layout_marginTop="5dip"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsave"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
<Button
android:id="#+id/btnclear"
android:layout_width="212dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight=".30"
android:text="refresh"
android:textColor="#fff"
android:textSize="15dip"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="search"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsearch"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"/>
</TableLayout>
Java File StudentRegistration.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StudentRegistration {
public static final String KEY_ROWID ="_id";
public static final String KEY_FNAME = "fname";
public static final String KEY_LNAME = "lname";
public static final String KEY_EMAIL = "email";
public static final String KEY_USER ="user";
public static final String KEY_PASS ="pass";
private static final String DATABASE_NAME = "StudentDB";
private static final String DATABASE_TABLE = "StudentTbl";
private static final int DATABASE_VERSION = 1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME,
null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_FNAME + " TEXT NOT NULL, " +
KEY_LNAME + " TEXT NOT NULL, " +
KEY_EMAIL + " TEXT NOT NULL, " +
KEY_USER + " TEXT NOT NULL, " +
KEY_PASS + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
onCreate(db);
}
}
public StudentRegistration(Context c) {
ourContext = c;
}
public StudentRegistration open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long savedata(String fname, String lname, String email, String user, String pass) {
ContentValues cv = new ContentValues();
cv.put(KEY_FNAME, fname);
cv.put(KEY_LNAME, lname);
cv.put(KEY_EMAIL, email);
cv.put(KEY_USER, user);
cv.put(KEY_PASS, pass);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData(){
String[] refresh = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, refresh, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iFName = c.getColumnIndex(KEY_FNAME);
int iLName = c.getColumnIndex(KEY_LNAME);
int iEmail = c.getColumnIndex(KEY_EMAIL);
int iUser = c.getColumnIndex(KEY_USER);
int iPass = c.getColumnIndex(KEY_PASS);
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow)
+ " " + c.getString(iFName)
+ " " + c.getString(iLName)
+ " " + c.getString(iEmail)
+ " " + c.getString(iUser)
+ " " + c.getString(iPass)
+ "\n\n";
}
return result;
}
public String getFName(long l){
String[] getfname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getfname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String fname = c.getString(1);
return fname;
}
return null;
}
public String getLName(long l){
String[] getlname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getlname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String lname = c.getString(2);
return lname;
}
return null;
}
public String getEmail(long l){
String[] getemail = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getemail, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String email = c.getString(3);
return email;
}
return null;
}
public String getUser(long l){
String[] getuser = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getuser, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String user = c.getString(4);
return user;
}
return null;
}
public String getPass(long l){
String[] getpass = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getpass, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String pass = c.getString(5);
return pass;
}
return null;
}
}
and the java file MainActivity:
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 android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText FirstName, LastName, Email, UserName, Password, ID;
Button Save, Clear, Search;
TextView TxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstName = (EditText)findViewById(R.id.txtfirstname);
LastName = (EditText)findViewById(R.id.txtlastname);
Email = (EditText)findViewById(R.id.txtmail);
UserName = (EditText)findViewById(R.id.txtuser);
Password = (EditText)findViewById(R.id.txtpw);
TxtData =(TextView)findViewById(R.id.textView);
Save =(Button)findViewById(R.id.btnsave);
Clear=(Button)findViewById(R.id.btnclear);
Search=(Button)findViewById(R.id.btnsearch);
Search.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String search = ID.getText().toString();
Long l= Long.parseLong(search);
StudentRegistration mysearch = new
StudentRegistration(MainActivity.this);
mysearch.open();
String returnedFname = mysearch.getFName(l);
String returnedLname = mysearch.getLName(l);
String returnedEmail = mysearch.getEmail(l);
String returnedUser = mysearch.getUser(l);
String returnedPass = mysearch.getPass(l);
mysearch.close();
FirstName.setText(returnedFname);
LastName.setText(returnedLname);
Email.setText(returnedEmail);
UserName.setText(returnedUser);
Password.setText(returnedPass);
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname = FirstName.getText().toString();
String lname = LastName.getText().toString();
String email = Email.getText().toString();
String user = UserName.getText().toString();
String pass = Password.getText().toString();
StudentRegistration save = new StudentRegistration(MainActivity.this);
save.open();
save.savedata(fname, lname, email, user, pass);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
Clear.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
StudentRegistration refresh = new StudentRegistration(MainActivity.this);
refresh.open();
String data = refresh.getData();
refresh.close();
TxtData.setText(data);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
}
}
My Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.classifiedinformation">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
How can I accomplish my goals?
First of all some hints about what went wrong would have been nice.
You need to initialize ID like you did with the other EditText's.
Add ID = findViewById(R.id.txtid); to your onCreate(Bundle savedInstanceState) method.
The first thing I got when clicking on 'Save' was the following:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.citiesapps.myapplication.MainActivity$2.onClick(MainActivity.java:76)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
As the stacktrace states you are trying to invoke a method on a null-object in this case 'ID'.
After analyzing your code, i saw your are executing setText on an editText that is not initialized in your java class.
Probable editText code is:
ID.setText(""); Here ID is not initialized with xml file.
Use ID = findViewById(R.id.txtid); for initializing the ID field
Check all editText initialization. Then use that editText.
Thanks :)

I have a retention window, but the data is not saved. How to store the value of boolean in the database?

Hello everybody. I'm trying to make an application that works with the database. I have a retention window, but the data is not saved. How to save the value boolean from check-box into the database?
How to resole this problem?
This is code of Database
public class DataBase extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "DataOfSchedule.db";
public static final String TABLE_NAME = "DataOfSchedule_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "AGE";
public static final String COL_4 = "SEX_MALE";
public static final String COL_7 = "SEX_FEMALE";
public static final String COL_5 = "WEIGHT";
public static final String COL_6 = "HEIGHT";
public static final String COL_8 = "TRAUMA";
public DataBase(Context context){
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY," +
" NAME TEXT," +
" AGE INTEGER NOT NULL DEFAULT 0 , " +
"SEX_MALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\") ," +
"SEX_FEMALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"TRAUMA NOT NULL TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"WEIGHT INTEGER NOT NULL DEFAULT 0," +
"HEIGHT INTEGER NOT NULL DEFAULT 0)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
}
public boolean insertData(String name, Integer age, String sex_male, String sex_female, Integer weight, Integer height, String trauma){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,age);
contentValues.put(COL_4,sex_male);
contentValues.put(COL_5,weight);
contentValues.put(COL_6,height);
contentValues.put(COL_7,sex_female);
contentValues.put(COL_8,trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
//To Check Whether Data is Inserted in DataBase
if(result==-1){
return false;
}else{
return true;
}
}
public Cursor getALLData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
return res;
}
}
It is code of Activity which inserts data
public class InsertData extends AppCompatActivity {
DataBase myDb;
EditText txtName, txtAge , txtWeight, txtHeight;
CheckBox boxSex_male,boxSex_female,boxTrauma;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_data);
myDb = new DataBase(this);
txtName = (EditText) findViewById(R.id.name);
txtAge = (EditText) findViewById(R.id.age);
boxSex_male = (CheckBox) findViewById(R.id.sex_m);
boxTrauma = (CheckBox) findViewById(R.id.trauma);
boxSex_female = (CheckBox) findViewById(R.id.sex_f);
txtWeight = (EditText) findViewById(R.id.weight);
txtHeight = (EditText) findViewById(R.id.height);
btnClick = (Button) findViewById(R.id.InsertBtn);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ClickMe();
}
});
if(boxTrauma.isChecked()){
boxTrauma.setChecked(true);
}else {
boxTrauma.setChecked(false);
}
if(boxSex_female.isChecked()){
boxSex_female.setChecked(true);
}else {
boxSex_female.setChecked(false);
}
if(boxSex_male.isChecked()){
boxSex_male.setChecked(true);
}else {
boxSex_male.setChecked(false);
}
}
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
String sex_male = boxSex_male.getText().toString();
String trauma = boxTrauma.getText().toString();
String sex_female = boxSex_female.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData(name,age_int,sex_male,sex_female,weight_int,height_int,trauma);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}
}
It is my HTML
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/insert_heading"
android:layout_gravity="center"
android:textSize="16dp"
android:textColor="#021aee"/>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_name"/>
<EditText
android:id="#+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_age"
android:numeric="integer"/>
<EditText
android:id="#+id/weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_weight"
android:numeric="integer"/>
<EditText
android:id="#+id/height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_height"
android:numeric="integer"/>
<TextView
android:padding="10dp"
android:text="#string/insert_sex"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/sex_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/male"/>
<CheckBox
android:id="#+id/sex_f"
android:text="#string/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:padding="10dp"
android:text="#string/insert_trauma"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/trauma"
android:text="#string/insert_trauma_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/InsertBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#string/insert_button"
android:textColor="#f2fde4"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
Lets break this problem down into a couple of Posts. First we can deal with the SQLite part of the code then you can post a new question about inserting values--there is just to much code to cover and make this understandable.
Change your code in your DataBase class (BTW: Not a good name!)
Give the variable names for the columns an understandable name. Who can remember what COL_6 is? Also consider that these probably do not need to be public.
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_AGE = "AGE";
public static final String COL_GENDER = "GENDER";
public static final String COL_WEIGHT = "WEIGHT";
public static final String COL_HEIGHT = "HEIGHT";
public static final String COL_TRAUMA = "TRAUMA";
You might not want to check if the table already exists, but I added the check anyway. I also made ID an AUTOINCREMENT column.
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT," +
COL_AGE + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER + " INTEGER NOT NULL DEFAULT 0, " +
COL_TRAUMA + " INTEGER NOT NULL DEFAULT 0, " +
COL_WEIGHT + " INTEGER NOT NULL DEFAULT 0, " +
COL_HEIGHT + " INTEGER NOT NULL DEFAULT 0);");
}
Change the insertData method to accommodate the changes to the static final variables for the columns and the type changes of the parameters:
public boolean insertData(String name, Integer age, Integer sex_male, Integer weight, Integer height, Integer trauma){
boolean success = false;
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_AGE, age);
contentValues.put(COL_GENDER, sex_male);
contentValues.put(COL_WEIGHT, weight);
contentValues.put(COL_HEIGHT, height);
contentValues.put(COL_TRAUMA, trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
if(result != -1) success = true;
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
return success;
}
Also note, no need to get a Writeable database in your getALLData() method:
public Cursor getALLData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME, null);
return res;
}
Now post a new question on how the populate the database from your Activity and we can go from there...

Android Studio Sqlite database login error

I am making an application to expend my knowledge and I am having this problem where I have a username to login with when i click on login button to login to application it gives error. I have tried couple of things but none worked so far. Here is the error code I believe there is something wrong with the database query or onclick method any help will be appreciated thank you.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bulkbuys.bulkbuysapp, PID: 23940
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.bulkbuys.bulkbuysapp.Menu launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1844)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1531)
at android.app.Activity.startActivityForResult(Activity.java:4403)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:4362)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at android.app.Activity.startActivity(Activity.java:4686)
at android.app.Activity.startActivity(Activity.java:4654)
at com.bulkbuys.bulkbuysapp.MainActivity$1.onClick(MainActivity.java:52)
at android.view.View.performClick(View.java:6261)
at android.widget.TextView.performClick(TextView.java:11180)
at android.view.View$PerformClick.run(View.java:23748)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
MainActivity.java
package com.bulkbuys.bulkbuysapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editTextUsername;
Button buttonLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUsername = (EditText) findViewById(R.id.editText_Username);
buttonLogin = (Button) findViewById(R.id.Button_Login);
//create preferences - used to store currently logged in user
}
public void login(View view) {
String username = editTextUsername.getText().toString(); //get Username from editText box
DBHandler dbHandler = new DBHandler(this, null, null, 7);
Admin a = dbHandler.findAdmin(username);
Log.i("Login: ","Trying to login with " + username);
if (username.equals("rick"))
{
Intent intent = new Intent(this, Menu.class);
startActivity(intent);
}
else
{
if (a == null) //if T is null no match came back, therefore incorrect username or password.
{
Toast.makeText(this, "Login failed - Username Wrong", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show();
}
}
}
public void clear(View view) {
editTextUsername.setText("");
}
}
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
tools:context=".MainActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="828dp"
android:layout_height="match_parent"
android:weightSum="1"
android:orientation="vertical"
android:baselineAligned="false"
android:divider="#262626">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="200dp"
android:layout_marginTop="250dp"
android:orientation="vertical">
<EditText
android:id="#+id/editText_Username"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="0dp"
android:hint="Username" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="400dp"
android:layout_weight="0.01"
android:orientation="vertical">
<Button
android:id="#+id/Button_Login"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/roundbutton"
android:onClick="login"
android:text="Login"
android:textColor="#ffffff"
android:textSize="20sp"
android:textStyle="normal|bold" />
<Button
android:id="#+id/button2"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:background="#drawable/roundbutton"
android:onClick="clear"
android:text="clear"
android:textColor="#ffffff"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
DBHandler
package com.bulkbuys.bulkbuysapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper implements BaseColumns {
private static final int DATABASE_VERSION = 19;
private static final String DATABASE_NAME = "GradeDB.db";
//Declare Tables in Database
private static final String TABLE_CUSTOMERS = "customers";
private static final String Admin = "admin";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_COMPANYNAME = "Company Name";
public static final String COLUMN_ADRESS = "Adress";
public static final String COLUMN_EMAIL = "Email";
public static final String COLUMN_ABN = "Abn";
public static final String COLUMN_MOBILENO = "Mobile Number";
public static final String COLUMN_COMPANYNO = "Company Number";
public static final String COLUMN_USERNAME = "User Name";
public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ADMIN_TABLE = "CREATE TABLE " + Admin + "(" +
COLUMN_USERNAME + " TEXT) ";
db.execSQL(CREATE_ADMIN_TABLE);
String CREATE_CUSTOMERS_TABLE = "CREATE TABLE " + TABLE_CUSTOMERS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_COMPANYNAME + " TEXT, " +
COLUMN_ADRESS + " TEXT, " +
COLUMN_EMAIL + " TEXT, " +
COLUMN_ABN + " TEXT. " +
COLUMN_MOBILENO + " TEXT, " +
COLUMN_COMPANYNO + " TEXT) ";
db.execSQL(CREATE_CUSTOMERS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DBHandler.Admin);
db.execSQL("DROP TABLE IF EXISTS " + DBHandler.TABLE_CUSTOMERS);
onCreate(db);
}
//search for product
public Admin findAdmin(String username) {
String query = "SELECT * FROM " + Admin + " WHERE username = '" +
username + "'";
SQLiteDatabase db = this.getWritableDatabase();
//run query with cursor
Cursor cursor = db.rawQuery(query, null);
Admin a = new Admin();
//move to first existing object
if (cursor.moveToFirst()) {
do { //****** This IF loop may be pointless need to mess with...
if (username.equals(cursor.getString(3))) { //If a username matches one in the DB add info into Teacher object
a.setUsername(cursor.getString(0));
}
} while (cursor.moveToNext());
cursor.close();
}
else //no match found return a null object
{
a = null;
db.close();
}
return a;
}
public void addCustomers(Customers customers) {
ContentValues values = new ContentValues(); // simpler way of inserting into DB
//ID isn't added as the ID will automatically be assigned
values.put(COLUMN_ID, customers.getId());
values.put(COLUMN_COMPANYNAME, customers.getCompanyname());
values.put(COLUMN_ADRESS, customers.getAdress());
values.put(COLUMN_EMAIL, customers.getEmail());
values.put(COLUMN_ABN, customers.getAbn());
values.put(COLUMN_MOBILENO, customers.getMobileno());
values.put(COLUMN_COMPANYNO, customers.getCompanyno());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_CUSTOMERS, null, values);
db.close();
}
public ArrayList<Customers> listCustomers() {
String query = "SELECT * FROM " + TABLE_CUSTOMERS + " ORDER BY " + COLUMN_ID;
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Customers> list = new ArrayList<>(); //Array to store customer
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do { //run loop through all results and store each customer into arraylist
Customers p = new Customers();
p.setId(Integer.parseInt(cursor.getString(0)));
p.setCompanyname(cursor.getString(1));
p.setAdress(cursor.getString(2));
p.setEmail(cursor.getString(3));
p.setAbn(cursor.getString(4));
p.setMobileno(cursor.getString(5));
p.setCompanyno(cursor.getString(6));
list.add(p);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
public boolean deleteCustomert(int id) {
boolean success = false;
//create query
String query = "SELECT * FROM " + TABLE_CUSTOMERS + " WHERE " + COLUMN_ID + " = '" + id + "'";
SQLiteDatabase db = this.getWritableDatabase();
//run query
Cursor cursor = db.rawQuery(query, null);
Customers Customers = new Customers(); //temp
//move to first object
if (cursor.moveToFirst()) //if exists delete object
{
cursor.moveToFirst();
Customers.setId(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_CUSTOMERS, COLUMN_ID + " = ?", new String[]{String.valueOf(Customers.getId())});
success = true;
cursor.close();
}
db.close();
return success;
}
public Customers findCustomers(String id) {
String query = "SELECT * FROM " + TABLE_CUSTOMERS + " WHERE " + COLUMN_ID + " = '" +
id + "'";
SQLiteDatabase db = this.getWritableDatabase();
//run query with cursor
Cursor cursor = db.rawQuery(query, null);
Customers p = new Customers();
return p;
}
}
Android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bulkbuys.bulkbuysapp">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CustomerListPage"></activity>
<activity android:name=".Menu"></activity>
</application>
</manifest>
I have got this extra class, i have tried something with it but it didn't work
package com.bulkbuys.bulkbuysapp;
import java.io.Serializable;
public class Admin implements Serializable {
private String username;
public Admin() {
}
public Admin(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString() {
return " / Username: " + username;
}
}
Menu.class
package com.bulkbuys.bulkbuysapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Menu extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
Button buttonclick = (Button)findViewById(R.id.button_customer);
buttonclick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use Intent
Intent intent1= new Intent(Menu.this,CustomerListPage.class);
startActivity(intent1);
}
});
}
}
ActivityNotFoundException
This exception is thrown when a call to startActivity(Intent) or one
of its variants fails because an Activity can not be found to execute
the given Intent.
FYI
Intent intent = new Intent(this, Menu.class);
startActivity(intent);
Make sure, Menu Activity is present or not.
Rectify Statement. Use , instead of .
Don't
String CREATE_CUSTOMERS_TABLE = "CREATE TABLE " + TABLE_CUSTOMERS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_COMPANYNAME + " TEXT , " +
COLUMN_ADRESS + " TEXT , " +
COLUMN_EMAIL + " TEXT , " +
COLUMN_ABN + " TEXT. " +
COLUMN_MOBILENO + " TEXT, " +
COLUMN_COMPANYNO + " TEXT) ";
Do
String CREATE_CUSTOMERS_TABLE = "CREATE TABLE " + TABLE_CUSTOMERS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY , " +
COLUMN_COMPANYNAME + " TEXT , " +
COLUMN_ADRESS + " TEXT , " +
COLUMN_EMAIL + " TEXT , " +
COLUMN_ABN + " TEXT , " +
COLUMN_MOBILENO + " TEXT , " +
COLUMN_COMPANYNO + " TEXT) ";
EDIT
MainActivity$1.onClick(MainActivity.java:52)
public void clear(View view) {
// editTextUsername.setText(""); comment setText method
}

Updating a certain value and saving it in offline database

I'm developing a tiny app that has a value in a textview set to 150,000 by default. Each month I reset the value back to the default. Every time I spend some of that amount, I open my app and enter the amount I spent and the details of what it was spent on.
What I did was create an offline database to store all the times I spent some of that amount, along with it's id and details. Each time I press the "spend" button, the total amount is reduced by the amount I have entered in the EditText.
I haven't implemented how I'll update the total amount yet, I believe I have to use something called sharedpreference number.
This is the main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button spendMoney = (Button)this.findViewById(R.id.spendMoney);
Button test = (Button)this.findViewById(R.id.test);
TextView totalTxt = (TextView) this.findViewById(R.id.totalTxt);
final EditText spendAmount = (EditText)this.findViewById(R.id.spendAmount);
// int totalAmount = Integer.parseInt(totalTxt.getText().toString());
final Paid_DB db = new Paid_DB(this);
spendMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.addPayment(new Payment(0, (Integer.parseInt(spendAmount.getText().toString())), "Test Details"));
}
});
//totalAmount = totalAmount - Integer.parseInt(spendAmount.getText().toString());
// totalTxt.setText(totalAmount);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(null, DetailsActivity.class);
startActivity(i);
}
});
XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.paid.MainActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="13dp"
android:layout_marginStart="13dp"
android:layout_marginTop="53dp"
android:fontFamily="sans-serif"
android:text="Total:"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<EditText
android:id="#+id/spendAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="72dp"
tools:layout_editor_absoluteY="143dp"
android:layout_marginBottom="38dp"
android:layout_above="#+id/spendMoney"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/spendMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spend Money"
tools:layout_editor_absoluteX="115dp"
tools:layout_editor_absoluteY="215dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/totalTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView3"
android:layout_alignBottom="#+id/textView3"
android:layout_alignEnd="#+id/spendMoney"
android:layout_alignRight="#+id/spendMoney"
android:fontFamily="sans-serif"
android:text="150,000"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<Button
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
tools:layout_editor_absoluteX="134dp"
tools:layout_editor_absoluteY="358dp"
android:layout_marginBottom="90dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/spendMoney"
android:layout_alignStart="#+id/spendMoney" />
This is the object I enter into the offline database, containing the id, the amount spent, and details of the payment:
public class Payment {
private int id;
private int amount;
private String details;
public Payment(){}
public Payment(int id, int amount, String details) {
this.id = id;
this.amount = amount;
this.details = details;
}
public Payment(int id, int amount) {
this.id = id;
this.amount = amount;
}
public Payment(int amount, String details) {
this.amount = amount;
this.details = details;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
} }
This is the offline database:
ublic class Paid_DB extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Payments_DB";
// Contacts table name
private static final String PAYMENT_TABLE = "PaymentTable";
// Contacts Table Columns names
private static final String PAY_ID = "id";
private static final String PAY_AMOUNT = "amount";
private static final String PAY_DETAILS = "details";
Paid_DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + PAYMENT_TABLE + "("
+ PAY_ID + " INTEGER PRIMARY KEY," + PAY_AMOUNT + " INTEGER,"
+ PAY_DETAILS + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + PAYMENT_TABLE);
onCreate(db);
}
public void addPayment(Payment payment){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PAY_AMOUNT, payment.getAmount());
values.put(PAY_DETAILS, payment.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(PAYMENT_TABLE, null, values);
db.close();
}
void addListItem(ArrayList<String> listItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < listItem.size(); i++) {
Log.e("vlaue inserting==", "" + listItem.get(i));
values.put(PAY_AMOUNT, listItem.get(i));
db.insert(PAYMENT_TABLE, null, values);
}
db.close(); // Closing database connection
}
Cursor getListItem() {
String selectQuery = "SELECT * FROM " + PAYMENT_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}}
And finally, this is the details activity, it contains a list view that stores and displays all the payments that have been made:
public class DetailsActivity extends AppCompatActivity {
ArrayList<String> detailsListArrayList;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
lv = (ListView) findViewById(R.id.listView);
detailsListArrayList = new ArrayList<>();
detailsListArrayList.add("Item1");
detailsListArrayList.add("Item2");
detailsListArrayList.add("Item3");
detailsListArrayList.add("Item4");
detailsListArrayList.add("Item5");
Paid_DB db = new Paid_DB(this);
db.addListItem(detailsListArrayList);
Cursor cursor = db.getListItem();
Log.e("count", " " + cursor.getCount());
if (cursor != null) {
cursor.moveToNext();
do {
Log.e("value==", "" + cursor.getString(1));
} while (cursor.moveToNext());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
detailsListArrayList );
lv.setAdapter(arrayAdapter);
}
}
XML file:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.paid.DetailsActivity">
<ListView
android:id="#+id/listView"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
Every time I click on the "test" button, the app crashes. And every time I try to add a new entry using the "spend" button, the app also crashes. What did I do wrong?
What I can tell from here (without the error log) is:
1) your app crashes when pressing the test-button because you are starting an activity there without passing a contextobject. Try this:
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
startActivity(i);
}
2) The spend button tries to add a new payment entry to your database. But in your database schema , you declare the PAY_ID as a primary key. Later in your addPayment() you are just passing the PAY_AMOUNT and PAY_DETAILS, so you are missing the PAY_ID which seems to lead to a crash.
EDIT: something like this should return all the payments as an ArrayList (may Contain bugs, just wrote it in this editor).
public ArrayList<Payment> getAllPayments() {
ArrayList<Payment> result = new ArrayList<>();
Cursor c = db.query("PAYMENTS",new String[]{"PAY_ID","PAY_AMOUNT","PAY_DETAIL"},null,null,null,null,null); ;
c.moveToFirst();
while(! c.isAfterLast())
{
int s1=c.getInt(0);
int s2=c.getInt(1);
String s3=c.getString(2);
results.add(new Payment(s1,s2,s3));
c.moveToNext();
}
return results;
}
To update your ListView, you should have a closer look a this link, that explains how to work with ListViews and a custom ListView adapter Custom Adapter for List View

How to refresh ListView on data delete automaticaly

I want list view automatically update after deletion. I use adapter.notifyDataSetChanged() but it doesn't work for me
Here is my code
DatabaseHelper
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";
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)";
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);
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;
}
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;
}
/**
* Delete from database
*/
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);
}
}
EditData
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private Button btnDelete;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
ActionBar actionBar=getSupportActionBar();
actionBar.hide();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.4),(int)(height*.2));
btnDelete = (Button) findViewById(R.id.btnDelete);
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");
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
toastMessage("removed from database");
adapter.notifyDataSetChanged();
}
});
}
/**
* customizable toast
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListData
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
static ArrayAdapter adapter;
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();
}
public 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
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");
}
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
EditText editField;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
editField = (EditText) findViewById(R.id.editText);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editField.getText().toString().length() == 0) {
Toast.makeText(MainActivity.this, "Please Enter!", Toast.LENGTH_SHORT).show();
return;
}
String editText = editField.getText().toString();
AddData(editText);
}
});
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");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
And Layout are
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.tabian.saveanddisplaysql.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Enter any Thing"
android:layout_marginBottom="47dp"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="197dp"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:text="Add" />
<Button
android:id="#+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/btnAdd"
android:text="View Data" />
</LinearLayout>
</RelativeLayout>
edit_data_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<Button
android:id="#+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="DELETE" />
</RelativeLayout>
list_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
After deletion instead of adapter.notifyDataSetChanged(); you can use the following code. It works fine for me:
adapter.remove(selectedName);

Categories