I am successful in inserting data into the database but when i try to retrieve data and display in textView it gets directed to the MainActivity.
The Regiser_page.java is as follows
public class Register_Page extends Activity {
int from_Where_I_Am_Coming = 0;
private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb ;
Button b1,b2;
TextView name ;
TextView email;
TextView pass;
TextView dob;
TextView gender;
TextView phone;
TextView city;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register__page);
name = (TextView) findViewById(R.id.editText_name);
phone = (TextView) findViewById(R.id.editText_phone);
email = (TextView) findViewById(R.id.editText_email);
pass = (TextView) findViewById(R.id.editText_pass);
dob = (TextView) findViewById(R.id.editText_dob);
gender=(TextView)findViewById(R.id.editText_gender);
city=(TextView)findViewById(R.id.editText_city);
b1=(Button)findViewById(R.id.button_register);
b2=(Button)findViewById(R.id.button_view);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
public void addUser(View view) {
if(mydb.insertContact(name.getText().toString(), email.getText().toString(),
pass.getText().toString(), dob.getText().toString(),
gender.getText().toString(),phone.getText().toString(),city.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
}
}
public void getmydata(View v){
Intent intent =new Intent();
intent.setClass(this ,View_Profile.class);
startActivity(intent);
}
The Activity_register_page.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
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"
tools:context="no.nordicsemi.android.nrftoolbox.Register_Page">
<RelativeLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:id="#+id/register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/editText_name"
android:layout_alignParentTop="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="28dp"
android:layout_weight="0.36"
android:text="Register Here"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#3333ff"
android:textSize="28dp" />
<Button
android:id="#+id/button_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="790dp"
android:onClick="mydata"
android:text="View data" />
<TextView
android:id="#+id/textView_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14sp"
android:layout_marginTop="70sp"
android:autoText="false"
android:text="Name :"
android:textColor="#3368ff"
android:textColorLink="#000000"
android:textSize="20sp" />
<EditText
android:id="#+id/editText_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:layout_marginTop="100sp"
android:ems="10"
android:hint="Enter your name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14sp"
android:layout_marginTop="160sp"
android:text="Email-id :"
android:textColor="#3368ff"
android:textColorLink="#000000"
android:textSize="20sp" />
<EditText
android:id="#+id/editText_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:layout_marginTop="190sp"
android:ems="10"
android:hint="Enter Email-id"
android:inputType="textEmailAddress" />
<TextView
android:id="#+id/textView_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="250dp"
android:hint="Enter Password"
android:text="Password"
android:textColor="#3368ff"
android:textSize="20sp" />
<EditText
android:id="#+id/editText_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="280dp"
android:ems="10"
android:hint="Enter Password"
android:inputType="textPassword" />
<TextView
android:id="#+id/textView_dob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14sp"
android:layout_marginTop="450sp"
android:text="Date of Birth :"
android:textColor="#3368ff"
android:textColorLink="#000000"
android:textSize="20sp" />
<EditText
android:id="#+id/editText_dob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="480dp"
android:ems="10"
android:hint="Date of Birth"
android:inputType="date" />
<TextView
android:id="#+id/textView_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14sp"
android:layout_marginTop="540sp"
android:text="Phone No. :"
android:textColor="#3368ff"
android:textColorLink="#000000"
android:textSize="20sp" />
<EditText
android:id="#+id/editText_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:layout_marginTop="570sp"
android:ems="10"
android:hint="Enter Phone No."
android:inputType="phone" />
<TextView
android:id="#+id/textView_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14sp"
android:layout_marginTop="630sp"
android:text="City :"
android:textColor="#3368ff"
android:textColorLink="#000000"
android:textSize="20sp" />
<EditText
android:id="#+id/editText_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:layout_marginTop="660sp"
android:ems="10"
android:hint="Enter your City"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14sp"
android:layout_marginTop="340sp"
android:text="Gender :"
android:textColor="#3368ff"
android:textColorLink="#000000"
android:textSize="20sp" />
<EditText
android:id="#+id/editText_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="370dp"
android:ems="10"
android:hint="M/F/Others"
android:inputType="textPersonName" />
<Button
android:id="#+id/button_register"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginLeft="110dp"
android:layout_marginTop="720dp"
android:background="#3368ff"
android:onClick="addUser"
android:text="Register"
android:textAlignment="center"
android:textColor="#ffffff" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
The View_Profile.java is as follows:
public class View_Profile extends AppCompatActivity {
TextView name, email, pass, phone, gender, city, dob;
int id_To_Update=0;
private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view__profile);
name = (TextView) findViewById(R.id.textView_name);
phone = (TextView) findViewById(R.id.textView_phone);
email = (TextView) findViewById(R.id.textView_email);
pass = (TextView) findViewById(R.id.textView_pass);
gender = (TextView) findViewById(R.id.textView_gender);
dob = (TextView) findViewById(R.id.textView_dob);
city = (TextView) findViewById(R.id.textView_city);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
Cursor rs = mydb.getData(1);
id_To_Update = 1;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_NAME));
String phon = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_EMAIL));
String cit = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_CITY));
String gend = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_GENDER));
String pas = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_PASS));
String dobb = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_DOB));
if (!rs.isClosed()) {
rs.close();
}
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);
pass.setText((CharSequence)pas);
pass.setFocusable(false);
pass.setClickable(false);
dob.setText((CharSequence)dobb);
dob.setFocusable(false);
dob.setClickable(false);
gender.setText((CharSequence)gend);
gender.setFocusable(false);
gender.setClickable(false);
phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);
city.setText((CharSequence)cit);
city.setFocusable(false);
city.setClickable(false);
}
}
The myDbAdapter.java is as follows:
public class myDbAdapter extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_PASS = "password";
public static final String CONTACTS_COLUMN_DOB = "date-of-birth";
public static final String CONTACTS_COLUMN_GENDER = "gender";
public static final String CONTACTS_COLUMN_PHONE="phone";
public static final String CONTACTS_COLUMN_CITY="city";
private HashMap hp;
public myDbAdapter(Context context) {
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,email text,pass text, dob text,gender text,phone text,city text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String email, String pass, String dob,String gender,String phone,String city) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("email", email);
contentValues.put("password", pass);
contentValues.put("date-of-birth", dob);
contentValues.put("gender", gender);
contentValues.put("phone",phone);
contentValues.put("city",city);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name, String email, String pass, String dob,String gender,String phone,String city) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("email", email);
contentValues.put("password", pass);
contentValues.put("date-of-birth", dob);
contentValues.put("gender", gender);
contentValues.put("phone",phone);
contentValues.put("city",city);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
What is the error that is directing View_Profile to MainActivity and results in failure of the display of the result??
My log file shows this error :
near "-": syntax error
Error inserting phone=5895346896 email=man#gmail.com name=my name gender=male password=47ufvjtio city=bangalore date-of-birth=30-02-95
android.database.sqlite.SQLiteException: near "-": syntax error (code 1): , while compiling: INSERT INTO contacts(phone,email,name,gender,password,city,date-of-birth) VALUES (?,?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
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:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at no.nordicsemi.android.nrftoolbox.myDbAdapter.insertContact(myDbAdapter.java:60)
at no.nordicsemi.android.nrftoolbox.Register_Page.addUser(Register_Page.java:194)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4020)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5276)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Is there any error in the insertContact code?? or why is this not working?
Let's make it clear :
*** You are creating table with column "dob"
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,email text,pass text, dob text,gender text,phone text,city text)"
);
}
*** Now look into
public boolean insertContact (String name, String email, String pass, String dob,String gender,String phone,String city) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("email", email);
contentValues.put("password", pass);
//contentValues.put("date-of-birth", dob);
// it should be "dob" instead of "date-of-birth"
contentValues.put("dob", dob);
// like this
contentValues.put("gender", gender);
contentValues.put("phone",phone);
contentValues.put("city",city);
db.insert("contacts", null, contentValues);
return true;
}
** also make change here
// public static final String CONTACTS_COLUMN_DOB = "date-of-birth";
// as
public static final String CONTACTS_COLUMN_DOB = "dob";
It's all about mismatching column name of date of birth
When you add new activity you have to register it in manifest file.You should have to register you new activity in your project manifest file.
<activity
android:name=".Register_Page"/>
<activity
android:name=".View_Profile"/>
Add this two line of code in manifest file of your project. you have to add them after your MainActivity's tag ends in your manifest file.
Related
I am trying to create an Android app with a login and register functionality. Whenever I run the app, the login page renders, and when I click on the create account button, it takes me to the register page as it should. After I fill in the blanks and I click on the register button, the app crashes. I used the debugger, and went through the same process, and I noticed an error message saying "java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable com.google.android.material.textfield.TextInputEditText.getText()' on a null object reference". What could be the root of this problem?
Here is my code:
activity_registration.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".Registration">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutFirstName"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="60dp"
android:hint="#string/first_name"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextFirstName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/first_name"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutLastName"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:hint="#string/last_name"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutFirstName">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/last_name"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutEmail"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:hint="#string/email"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutLastName">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextEmail"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/email"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutNewUsername"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:hint="#string/new_username"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutEmail">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextNewUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/username"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutNewPassword"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="#string/new_password"
android:inputType="textPassword"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutNewUsername">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextNewPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/password"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayoutConfirmPassword"
android:layout_width="238dp"
android:layout_height="48dp"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="#string/confirm_password"
android:inputType="textPassword"
android:textAlignment="viewStart"
android:textColorHint="#757575"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutNewPassword">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textInputEditTextConfirmPassword"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/confirm_password"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/newRegistration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="#string/register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayoutConfirmPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>
Registration.java
package com.zybooks.event_tracking;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
public class Registration extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = Registration.this;
// Field variables
TextInputLayout textInputLayoutFirstName, textInputLayoutLastName, textInputLayoutEmail, textInputLayoutUsername, textInputLayoutPassword, textInputLayoutConfirmPassword;
TextInputEditText textInputEditTextFirstName, textInputEditTextLastName, textInputEditTextEmail, textInputEditTextUsername, textInputEditTextPassword, textInputEditTextConfirmPassword;
Button register;
InputValidation inputValidation;
Database database;
UserModel user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUI();
setupListeners();
initObjects();
}
// initialize views
private void setupUI() {
textInputLayoutFirstName = (TextInputLayout) findViewById(R.id.textInputLayoutFirstName);
textInputLayoutLastName = (TextInputLayout) findViewById(R.id.textInputLayoutLastName);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutUsername = (TextInputLayout) findViewById(R.id.textInputLayoutUsername);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutConfirmPassword = (TextInputLayout) findViewById(R.id.textInputLayoutConfirmPassword);
register = findViewById(R.id.newRegistration);
}
// initialize listeners
private void setupListeners() {
register.setOnClickListener(this);
}
// initialize objects to be used
private void initObjects() {
inputValidation = new InputValidation(activity);
database = new Database(activity);
user = new UserModel();
}
// listen the click the view
#Override
public void onClick(View v) {
if (v.getId() == R.id.newRegistration) {
postDataToSQLite();
}
}
// validate the input text fields and post data to SQLite
private void postDataToSQLite() {
if (!inputValidation.isInputEditTextFilled(textInputEditTextFirstName, textInputLayoutFirstName, getString(R.string.error_message_name))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextLastName, textInputLayoutLastName, getString(R.string.error_message_name))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextUsername, textInputLayoutUsername, getString(R.string.error_message_username))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, getString(R.string.error_message_password))) {
return;
}
if (!inputValidation.isInputEditTextMatches(textInputEditTextPassword, textInputEditTextConfirmPassword,
textInputLayoutConfirmPassword, getString(R.string.error_password_match))) {
return;
}
if (!database.checkUser(textInputEditTextEmail.getText().toString().trim())) {
user.setFirstName(textInputEditTextFirstName.getText().toString().trim());
user.setLastName(textInputEditTextLastName.getText().toString().trim());
user.setEmail(textInputEditTextEmail.getText().toString().trim());
user.setUsername(textInputEditTextUsername.getText().toString().trim());
user.setPassword(textInputEditTextPassword.getText().toString().trim());
database.addUser(user);
Intent g = new Intent(Registration.this, Grid.class);
startActivity(g);
emptyInputEditText();
//we close this activity
this.finish();
} else {
// Toast to show success message that record is wrong
Toast t = Toast.makeText(this, "Wrong email or password!", Toast.LENGTH_SHORT);
t.show();
}
}
// empty all input edit text
private void emptyInputEditText() {
textInputEditTextFirstName.setText(null);
textInputEditTextLastName.setText(null);
textInputEditTextEmail.setText(null);
textInputEditTextUsername.setText(null);
textInputEditTextPassword.setText(null);
textInputEditTextConfirmPassword.setText(null);
}
}
Database.java
package com.zybooks.event_tracking;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "EventManager.db";
// User table name
private static final String TABLE_USER = "user";
// User table columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_FIRST_NAME = "user_first_name";
private static final String COLUMN_USER_LAST_NAME = "user_last_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_USERNAME = "user_username";
private static final String COLUMN_USER_PASSWORD = "user_password";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_FIRST_NAME + " TEXT,"
+ COLUMN_USER_LAST_NAME + " TEXT," + COLUMN_USER_EMAIL + " TEXT, " + COLUMN_USER_USERNAME + " TEXT,"
+ COLUMN_USER_PASSWORD + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
// Constructor
public Database (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop User Table if exist
db.execSQL((DROP_USER_TABLE));
// Create tables again
onCreate(db);
}
// Create user record
public void addUser (UserModel user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_FIRST_NAME, user.getFirstName());
values.put(COLUMN_USER_LAST_NAME, user.getLastName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_USERNAME, user.getUsername());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// Inserting Row
db.insert(TABLE_USER, null, values);
db.close();
}
// Fetch all user and return the list of user records
public List<UserModel> getAllUser() {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID,
COLUMN_USER_FIRST_NAME,
COLUMN_USER_LAST_NAME,
COLUMN_USER_EMAIL,
COLUMN_USER_USERNAME,
COLUMN_USER_PASSWORD
};
// sorting orders
String sortOrder =
COLUMN_USER_FIRST_NAME + " ASC";
List<UserModel> userList = new ArrayList<UserModel>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_first_name,user_last_name,user_email,user_username,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(TABLE_USER, // Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
UserModel user = new UserModel();
user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_ID))));
user.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_FIRST_NAME)));
user.setLastName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_LAST_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_EMAIL)));
user.setUsername(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_USERNAME)));
user.setPassword(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_PASSWORD)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
// Update user record
public void updateUser (UserModel user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_USERNAME, user.getUsername());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
// Delete user record
public void deleteUser(UserModel user) {
SQLiteDatabase db = this.getWritableDatabase();
// delete user record by id
db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
// Check if user exist or not
public boolean checkUser(String username) {
//array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_USERNAME + " = ?";
// selection argument
String[] selectionArgs = {username};
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public boolean checkUser(String username, String password) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_USERNAME + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {username, password};
// query user table with conditions
Cursor cursor = db.query(TABLE_USER, //Table to query
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
}
Adding this set of code to my Registration.java file solved my problem.
textInputEditTextFirstName = (TextInputEditText) findViewById(R.id.textInputEditTextFirstName);
textInputEditTextLastName = (TextInputEditText) findViewById(R.id.textInputEditTextLastName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextUsername = (TextInputEditText) findViewById(R.id.textInputEditTextNewUsername);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextNewPassword);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
I know its simple and I am just new to SQLite and Android Studio, but I am trying to create a database table inventory each item having an ID, item name, and quantity. Then view that database table in RecyclerView. Right now I am getting the error message:
E/SQLiteDatabase: Error inserting item=Apples _id=1 quantity=5
android.database.sqlite.SQLiteException: table inventory has no column named quantity
(code 1 SQLITE_ERROR): , while compiling: INSERT INTO inventory(item,_id,quantity) VALUES
(?,?,?)
Here is my current code:
IventoryDB.java
private static final class InventoryTable {
private static final String TABLE = "inventory";
private static final String COL_ID = "_id";
private static final String COL_ITEM = "item";
private static final String COL_QTY = "quantity";
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + InventoryTable.TABLE + " (" +
InventoryTable.COL_ID + " integer primary key autoincrement, " +
InventoryTable.COL_ITEM + " text, " +
InventoryTable.COL_QTY + "text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("drop table if exists " + InventoryDB.InventoryTable.TABLE);
onCreate(db);
}
public void addItem(int id, String item, String qty) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InventoryDB.InventoryTable.COL_ID, id);
values.put(InventoryDB.InventoryTable.COL_ITEM, item);
values.put(InventoryDB.InventoryTable.COL_QTY, qty);
db.insert(InventoryDB.InventoryTable.TABLE, null, values);
}
Inventory.java
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
private InventoryDB DB;
private int id;
public void addItem(View view) {
createNewAddItemDialog();
}
public void createNewAddItemDialog(){
dialogBuilder = new AlertDialog.Builder(this);
final View addItemPopupView = getLayoutInflater().inflate(R.layout.popup_additem, null);
addItemName = (EditText) addItemPopupView.findViewById(R.id.additempopup_itemname);
addItemQuantity = (EditText)addItemPopupView.findViewById(R.id.additempopup_itemquantity);
addItemBtn = (Button) addItemPopupView.findViewById(R.id.additempopup_add);
cancelAddBtn = (Button) addItemPopupView.findViewById(R.id.additempopup_cancel);
dialogBuilder.setView(addItemPopupView);
dialog = dialogBuilder.create();
dialog.show();
addItemBtn.setOnClickListener(v -> {
String itemName = addItemName.getText().toString();
String itemQuantity = addItemQuantity.getText().toString();
if (itemName.equals("") || itemQuantity.equals("")) {
//addError.setText("Please ensure both fields are filled out!");
} else {
Boolean itemExists = DB.checkItemExists(itemName);
if (itemExists){
//addError.setText("Item already exists!");
} else {
DB.addItem(id, itemName, itemQuantity);
dialog.dismiss();
id += 1;
}
}
});
cancelAddBtn.setOnClickListener(v -> dialog.dismiss());
}
popup_additem.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Item"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.25" />
<EditText
android:id="#+id/additempopup_itemname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Item Name"
android:inputType="text"
android:minHeight="48dp"
android:text=""
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.361" />
<EditText
android:id="#+id/additempopup_itemquantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Item Quantity"
android:inputType="number"
android:minHeight="48dp"
android:text=""
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/additempopup_itemname"
app:layout_constraintVertical_bias="0.066" />
<Button
android:id="#+id/additempopup_add"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="Add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.8"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/additempopup_itemquantity"
app:layout_constraintVertical_bias="0.105" />
<Button
android:id="#+id/additempopup_cancel"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="Cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/additempopup_add"
app:layout_constraintHorizontal_bias="0.8"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/additempopup_itemquantity"
app:layout_constraintVertical_bias="0.105" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is a long shot, but I think that you're missing a blank space in the last sentence of the method onCreate(SQLiteDatabase db) ... it seems that you're creating a column named: quantitytext instead of quantity text ...
I want my application to be able to display average rating when the user click onto the get average button but how can I do it? I have already created the database and the database is working but I have issues with the main activity.
manifest:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp">
<ImageView
android:layout_width="150dp"
android:layout_height="50dp"
android:scaleType="fitXY"
android:src="#drawable/logo_jpg" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="Product:"
android:id="#+id/textView"
android:textStyle="bold"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:ems="10"/>
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:id="#+id/averagelistView"
android:layout_alignParentLeft="true"
>
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonaverage"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:onClick="Average"
android:text="Get Average"/>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="Get Average:"
android:onClick="average"
android:id="#+id/textView2"
android:textStyle="bold"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:ems="10"/>
</TableRow>
</TableLayout>
</ScrollView>
</LinearLayout>
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.averagerating2ndpage);
lvInfo = (ListView) findViewById(R.id.averagelistView);
txtProduct = (EditText) findViewById(R.id.editText);
txtAvg = (EditText) findViewById(R.id.editText2);
db = new Database_rbar(this);
dbAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, ArrayofName);
lvInfo.setAdapter(dbAdapter);
lvInfo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentId = results.get(position).getId();
txtProduct.setText(results.get(position).getProduct());
}
});
DisplayAll();
btnAvg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtAvg = db.getAverage();
}
});
}
public void DisplayAll() {
results = db.getAllResults();
ArrayofName.clear();
for (Result rs : results) {
ArrayofName.add(rs.getId() + ".\t" + rs.getProduct());
}
dbAdapter.notifyDataSetChanged();
txtProduct.setText("");
}
}
Database:
public class Database_rbar extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = Environment.getExternalStorageDirectory().toString() + "/result.db";
private static final String TABLE_RESULT = "Result";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_RATING = "rating";
private static final String KEY_PHONE = "phone";
private static final String KEY_PRODUCT = "product";
private static final String KEY_EMAIL = "email";
public Database_rbar(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//creating Tables
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_RESULTS_TABLE = "CREATE TABLE " + TABLE_RESULT + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME +
" TEXT,"+ KEY_PHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_PRODUCT + " TEXT," + KEY_RATING + " REAL" + ")";
db.execSQL(CREATE_RESULTS_TABLE);
}
//upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RESULT);
//create tables again
onCreate(db);
}
public int getAverage(String product){
String countquery = "SELECT AVG(rating) * FROM" + TABLE_RESULT + "WHERE" + KEY_PRODUCT + "='" + product + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countquery, null);
cursor.close();
return cursor.getCount();
}
public List<Result> getAllResults() {
List<Result> resultList = new ArrayList<Result>();
String selectQuery = "SELECT * FROM " + TABLE_RESULT;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Result result = new Result();
result.setId(Integer.parseInt(cursor.getString(0)));
result.setName(cursor.getString(1));
result.setPhone(cursor.getString(2));
result.setEmail(cursor.getString(3));
result.setProduct(cursor.getString(4));
result.setRating(Float.parseFloat(cursor.getString(5)));
resultList.add(result);
} while (cursor.moveToNext());
}
return resultList;
}
}
From your code txtAvg is an EditText variable but in onClick() method you assign to an integer value from db.getAverage().
The appropriate way would be to convert the integer to String then set it to txtAvg using setText() method:
txtAvg.setText(String.valueOf(db.getAverage()));
Your getAverage() method in Database_rbar has a String parameter, but when you call it in MainActivity it has no arguments:
txtAvg = db.getAverage();
It should (from what I can infer from your code) look more like:
txtAvg = db.getAverage("product_key_here");
There may be other errors, but this is the one referred to by your stack trace.
Edit: Ramadan Juma has correctly identified another issue. In addition, I expect your countquery String will create a problem as well, as it has an incorrect number of spaces.
Edit 2: You also call cursor.close() before you call cursor.getCount(). I expect this will also throw an error.
Please anyone tell me how to connect MainActivity class with adapterClass, I am not able to connect to my sqllite database. Any help would be greatly appreciated.
Below is my main activity class
public class LoginActivity extends Activity {
EditText nameText,phoneText;
Button registeredButton,newUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
newUser =(Button)findViewById(R.id.new_user);
newUser.setOnClickListener(new View.OnClickListener()
#Override
public void onClick(View v) {
nameText=(EditText)findViewById(R.id.user_text);
phoneText=(EditText)findViewById(R.id.pass_text);
String name= nameText.getText().toString();
String phone=phoneText.getText().toString();
AdapterClass ad1=new AdapterClass(getApplicationContext(),DatabaseDetail.REGISTER);
ad1.Open();
Cursor cursor=ad1.query("SELECT * FROM CUS_REGISTER WHERE CUS_NAME=? AND CUS_PHONE=?",new String[] { name, phone });
Cursor cursor = ad1.fetchRecords(new String[]{}, null);
startManagingCursor(cursor);
cursor.moveToFirst();
if(cursor.getCount() > 0)
{
Toast.makeText(getApplicationContext(), "Sucess", 5000).show();
}else{
}
}
});
}
}
And this my adapter class code
public Cursor query(String args, String[] pColumnValues) {
// TODO Auto-generated method stub
return database.query(DATABASE_TABLE, pColumnValues, args, null, args, args, args);
}
MainActivity Class
package com.example.sqlitedbtestproject;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.app.Activity;
public class MainActivity extends Activity {
AryaDatabaseAdapter help;
EditText name, address, infoFetcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText1);
address = (EditText) findViewById(R.id.editText2);
infoFetcher = (EditText) findViewById(R.id.editText3);
help = new AryaDatabaseAdapter(this);
}
public void addUser(View view)
{
if(help.insertData(name.getText().toString(), address.getText().toString())>0)
{
MessagePopper.message(this, "Successfully Inserted");
}
else
{
MessagePopper.message(this, "Un successfull Attempt");
}
}
public void viewDetail(View view)
{
MessagePopper.message(this, help.getAllData());
}
public void viewUserDetail(View view)
{
MessagePopper.message(this, help.getSpecificData(infoFetcher.getText().toString()));
}
public void updateUserDetail(View view)
{
MessagePopper.message(this, "Updated number of rows are "+help.updateRow(name.getText().toString(),infoFetcher.getText().toString()));
}
public void deleteUserDetail(View view)
{
MessagePopper.message(this, "Deleted number of rows are "+help.deleteRow(infoFetcher.getText().toString()));
}
}
Database Adapter class
package com.example.sqlitedbtestproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AryaDatabaseAdapter
{
Context context;
DBHelper helpDB;
AryaDatabaseAdapter(Context ctx)
{
helpDB = new DBHelper(ctx);
}
public Long insertData(String name, String address)
{ System.out.println("Reached inside insert data ");
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.NAME, name);
contentValues.put(DBHelper.ADDRESS, address);
SQLiteDatabase db = helpDB.getWritableDatabase();
Long l = db.insert(DBHelper.TABLE_NAME, null, contentValues);
System.out.println("Reached inside insert data "+l+" "+name+" "+address);
return l;
}
public String getAllData()
{ System.out.println("Reached inside get data ");
SQLiteDatabase db = helpDB.getWritableDatabase();
String columns[] = {DBHelper.UID,DBHelper.NAME, DBHelper.ADDRESS};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , null,null,null,null,null);
StringBuffer buff=new StringBuffer();
while(cursor.moveToNext())
{
buff.append(cursor.getInt(cursor.getColumnIndex(DBHelper.UID))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.NAME))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS))+" \n ");
}
return buff.toString();
}
public String getSpecificData(String name)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
String columns[] = {DBHelper.UID, DBHelper.ADDRESS};
System.out.println("Name is "+name);
String []selectionArgs = {name};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , DBHelper.NAME+" =? ",selectionArgs,null,null,null);
StringBuffer buff=new StringBuffer();
while(cursor.moveToNext())
{
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.UID));
String address = cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS));
buff.append(id+" "+address+" \n ");
}
return buff.toString();
}
public int updateRow(String oldname , String newName)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.NAME, newName);
String whereArgs[] = {oldname};
return db.update(DBHelper.TABLE_NAME, contentValues, DBHelper.NAME + " =? ", whereArgs);
}
public int deleteRow(String name)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
String whereArgs[] = {name};
return db.delete(DBHelper.TABLE_NAME, DBHelper.NAME + " =? ", whereArgs);
}
static class DBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "aryadatabase";
private final static String TABLE_NAME = "ARYATABLE";
private final static int DATABASE_VERSION = 1;
private final static String UID = "_id";
private final static String NAME = "Name";
private final static String ADDRESS = "Address";
private final static String CREATE = "CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+ADDRESS+" VARCHAR(255));";
private final static String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
Context context ;
public DBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
MessagePopper.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
//CREATE TABLE ARYATABLE (_id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(255));
try
{
db.execSQL(CREATE);
MessagePopper.message(context, "OnCreate Called");
}
catch (SQLException e)
{
MessagePopper.message(context, e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try
{
db.execSQL(DROP_TABLE);
MessagePopper.message(context, "OnUpgarde Called");
onCreate(db);
}
catch (SQLException e)
{
MessagePopper.message(context, e.getMessage());
}
}
}
}
Message or Toast popper example
package com.example.sqlitedbtestproject;
import android.content.Context;
import android.widget.Toast;
public class MessagePopper {
public static void message(Context ctx, String Message)
{
Toast.makeText(ctx, Message, Toast.LENGTH_SHORT).show();
}
}
Layout File
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Name :"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="19dp"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_alignRight="#+id/editText2"
android:layout_below="#+id/editText2"
android:layout_marginTop="18dp"
android:onClick="addUser"
android:text="Add User" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="14dp"
android:onClick="viewDetail"
android:text="View Details" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button2"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:ems="10"
android:hint="Name of person for details" />
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText3"
android:layout_alignRight="#+id/editText3"
android:layout_below="#+id/editText3"
android:onClick="viewUserDetail"
android:text="View User Address" />
<Button
android:id="#+id/button4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button3"
android:layout_alignParentBottom="true"
android:layout_marginBottom="17dp"
android:onClick="updateUserDetail"
android:text="Update" />
<Button
android:id="#+id/button5"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button4"
android:layout_centerHorizontal="true"
android:onClick="deleteUserDetail"
android:text="Delete" />
</RelativeLayout>
View this sample code i have developed and verify against your code. You should upload logcat for precise solution here. :)
I wanted to do a view output using table layout.
My idea goes like this.
I have a main page, known as activity_main.xml
when you click on the cancel button, it will go to a summary page,
know as data.xml.
In data.xml, I have a date edittext, whereby ,when I enter a date,eg 12/2/2013,
and after I click the button search, it will show me the record of it.
However, I'm not sure how to do it.
If I didn't enter any date and click "search", it will show all the records.
Right now,I am able to show all the records, without searching the data.
Below is my code.
Can someone kindly help me out with the search by date?
I hope that I've explained myself clear enough.
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_PRICE = "fuelprice";
public static final String KEY_FUEL = "fuelpump";
public static final String KEY_COST = "tcost";
public static final String KEY_ODM = "odometer";
public static final String KEY_CON = "fcon";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "fuelLog";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
try{
db.execSQL(DATABASE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}//onCreate
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}//onUpgrade
}//DatabaseHelper
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//open
//---closes the database---
public void close()
{
DBHelper.close();
}//close
//---insert a log into the database---
public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_PRICE, fuelprice);
initialValues.put(KEY_FUEL, fuelpump);
initialValues.put(KEY_COST, tcost);
initialValues.put(KEY_ODM, odometer);
initialValues.put(KEY_CON, fcon);
return db.insert(DATABASE_TABLE, null, initialValues);
}//insertLog
// --retrieves all the data
public Cursor getAllLog()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE, KEY_PRICE, KEY_FUEL,KEY_ODM,KEY_CON}, null, null, null, null, null);
}
}
summary.java
public class summary extends Activity{
TableLayout tablelayout_Log = null;
Button searchButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
tablelayout_Log = (TableLayout) findViewById(R.id.tableLayout_Log);
tablelayout_Log.setStretchAllColumns(true);
tablelayout_Log.setShrinkAllColumns(true);
//View
searchButton = (Button) findViewById(R.id.searchBtn);
searchButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
}
});
}//oncreate
public void refreshTable()
{
tablelayout_Log.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Fuel Log");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span = 5;
rowTitle.addView(title, params);
tablelayout_Log.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try
{
dbAdaptor.open();
cursor = dbAdaptor.getAllLog();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String date = cursor.getString(1);
String price = cursor.getString(2);
String pump = cursor.getString(3);
String odometer = cursor.getString(4);
String fcon = cursor.getString(5);
TextView viewId = new TextView(getApplicationContext());
viewId.setText("" + id);
TextView viewDate = new TextView(getApplicationContext());
viewDate.setText(date);
TextView viewPrice = new TextView(getApplicationContext());
viewPrice.setText(price);
TextView viewPump = new TextView(getApplicationContext());
viewPump.setText(pump);
TextView viewOdometer = new TextView(getApplicationContext());
viewOdometer.setText(odometer);
TextView viewCon = new TextView(getApplicationContext());
viewCon.setText(fcon);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(viewId);
row.addView(viewDate);
row.addView(viewPrice);
row.addView(viewPump);
row.addView(viewOdometer);
row.addView(viewCon);
tablelayout_Log.addView(row);
}
while(cursor.moveToNext());
}
catch(Exception e){
Log.d("Fuel Log", e.getMessage());
}
finally
{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}//refreshTable
}//main
MainActivity.java
public class MainActivity extends Activity {
TableLayout tablelayout_Contacts = null;
Button insertButton = null;
EditText nameEdit = null;
EditText contactEdit = null;
Button viewButton = null;
Button deleteButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tablelayout_Contacts = (TableLayout) findViewById(R.id.tableLayout_Contacts);
tablelayout_Contacts.setStretchAllColumns(true);
tablelayout_Contacts.setShrinkAllColumns(true);
nameEdit = (EditText) findViewById(R.id.editText_Name);
contactEdit = (EditText) findViewById(R.id.editText_Number);
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
dbAdaptor.open();
String name = nameEdit.getText().toString();
String number = contactEdit.getText().toString();
dbAdaptor.insertContact(name, number);
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
finally{
if(dbAdaptor != null)
dbAdaptor.close();
}
}
});
//View records
viewButton = (Button) findViewById(R.id.button2);
viewButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
//delete records
deleteButton = (Button) findViewById(R.id.button3);
deleteButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
refreshTable();
String name = nameEdit.getText().toString();
if(!name.equals(""))
{
dbAdaptor.deleteContact(name);
}
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
}//oncreate
//refresh table
public void refreshTable()
{
tablelayout_Contacts.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Contacts");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span =3;
rowTitle.addView(title,params);
tablelayout_Contacts.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try{
dbAdaptor.open();
cursor = dbAdaptor.getAllContacts();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String name = cursor.getString(1);
String contact = cursor.getString(2);
TextView idView = new TextView(getApplicationContext());
idView.setText("" + id);
TextView nameView = new TextView(getApplicationContext());
nameView.setText(name);
TextView contactView = new TextView(getApplicationContext());
nameView.setText(contact);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(idView);
row.addView(nameView);
row.addView(contactView);
tablelayout_Contacts.addView(row);
}
while (cursor.moveToNext());
}
catch (Exception e)
{
Log.d("Contact Manager", e.getMessage());
}
finally{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/date"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpricetxtview"
android:text="#string/fuelprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpumptxtview"
android:text="#string/fuelpump"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelpump"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/totalcosttxtview"
android:text="#string/totalcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/tcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/odometertxtview"
android:text="#string/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/fcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveBTN"
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/updateBTN"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/cancelBTN"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</LinearLayout>
</LinearLayout>
data.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/datepast"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fc"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/highpricetxtview"
android:text="#string/highprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/highprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/searchBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search" />
<Button
android:id="#+id/deleteBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
<Button
android:id="#+id/backBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/tableLayout_Log"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
The error you are getting is a nullpointer that means that some object that is at line 205 in MainActivity or it is used at that line is null. Check that first and then try to run again.
The immediate problem is here:
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
Not all throwables have a message and a null can be returned. A null cannot be logged. It causes the "println needs a message" exception in the stacktrace.
So first, change that to e.g.
catch (Exception e)
{
Log.e("Fuel Log", "", e);
}
This will log the exception with error level, empty message and with full stacktrace.
Then you can see what causes that exception in the first place.
Hello date type is not supported in Sqlite Database.you have assign date as text so it will take string so you need to keep string in proper order so that it can work as date search.
You can store date in form of 2013-12-23 (20131223) then you can get your query by passing date
by the way you can try like below
public ArrayList<String> getEventsForNotification(String dateSearch)
{
ArrayList<String> arrayList=new ArrayList<String>();
String sql="SELECT "+KEY_EVENT_NAME+" FROM "+ TABLE_EVENT +" WHERE SUBSTR("+KEY_EVENT_DATE+",6) like '"+dateSearch+"'";
Cursor cursor=sqLiteDatabase.rawQuery(sql, null);
if(cursor.moveToFirst())
{
do
{
arrayList.add(cursor.getString(0));
}while(cursor.moveToNext());
cursor.close();
cursor=null;
}
return arrayList;
}
modify according to your need.