I am new to Android. I am running SQLite Filter ListView. I added an EditText, priceEditTxt, in the dialog box and another column "Price " in the database. When I search or click the save button, the application stops. I don't know how to solve it.
The Display() function has two EditText and one save button. When I click the save button, the application, unfortunately, stops working.
The getPlanet() function is used to show a search list when I click on the searchview. I don't have much understanding about it.
MainActivity.java:
private void displayDialog()
{
Dialog d=new Dialog(this);
d.setTitle("SQLite Database");
d.setContentView(R.layout.dialog_layout);
nameEditText= (EditText) d.findViewById(R.id.nameEditTxt);
**////////////////////Price edit text which I add/////////////**
priceEditText= (EditText) d.findViewById(R.id.priceEditTxt);
saveBtn= (Button) d.findViewById(R.id.saveBtn);
retrieveBtn= (Button) d.findViewById(R.id.retrieveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
save(nameEditText.getText().toString(),priceEditText.getText().toString());
}
});
retrieveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getPlanets(null);
}
});
d.show();
}
** //save button took one argument "name" only, i add "price" later//**
private void save(String name,String price)
{
DBAdapter db=new DBAdapter(this);
db.openDB();
if(db.add(name,price))
{
nameEditText.setText("");
priceEditText.setText("");
}else {
Toast.makeText(this,"Unable To Save",Toast.LENGTH_SHORT).show();
}
db.closeDB();
this.getPlanets(null);
}
private void getPlanets(String searchTerm)
{
planets.clear();
DBAdapter db=new DBAdapter(this);
db.openDB();
Planet p=null;
Cursor c=db.retrieve(searchTerm);
while (c.moveToNext())
{
int id=c.getInt(0);
String name=c.getString(1);
p=new Planet();
p.setId(id);
p.setName(name);
planets.add(p);
}
db.closeDB();
lv.setAdapter(adapter);
}
DBAdapter.java contains the add and retrieve functions, which I call from MainActivity.
DBAdapter.java:
public class DBAdapter {
Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context c) {
this.c = c;
helper=new DBHelper(c);
}
//OPEN DB
public void openDB()
{
try
{
db=helper.getWritableDatabase();
}catch (SQLException e)
{
e.printStackTrace();
}
}
//CLOSE
public void closeDB()
{
try
{
helper.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
//INSERT DATA
public boolean add(String name,String price)
{
try
{
ContentValues cv=new ContentValues();
cv.put(Constants.NAME, name);
cv.put(Constants.PRICE, price);
//Log.d(Constants.PRICE,"here we gooooooooooooooooooooooooooooooooooooooooooooooooooo");
db.insert(Constants.TB_NAME, Constants.ROW_ID, cv);
return true;
}catch (SQLException e)
{
e.printStackTrace();
}
return false;
}
//RETRIEVE DATA AND FILTER
public Cursor retrieve(String searchTerm)
{
String[] columns={Constants.ROW_ID,Constants.NAME};
Cursor c=null;
if(searchTerm != null && searchTerm.length()>0)
{
String sql="SELECT * FROM "+Constants.TB_NAME+" WHERE "+Constants.NAME+" LIKE '%"+searchTerm+"%'";
c=db.rawQuery(sql,null);
return c;
}
c=db.query(Constants.TB_NAME,columns,null,null,null,null,null);
return c;
}
}
Constants.java contains the creatable and droptable query. I don't know if create table query is right or not.
Constants.java:
public class Constants {
//COLUMNS
static final String ROW_ID="id";
static final String NAME="name";
static final String PRICE="price";
//DB
static final String DB_NAME="ii_DB";
static final String TB_NAME="ii_TB";
static final int DB_VERSION=2;
//CREATE TB
static final String CREATE_TB="CREATE TABLE ii_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL,price TEXT NOT NULL);";
//DROP TB
static final String DROP_TB="DROP TABLE IF EXISTS "+TB_NAME;
}
You are creating different instances of DBAdapter for each operation and opening a new connection to the database on these operations. Also, you are closing these connections each time you are done with the operation.
Trying to get a new connection to your database is expensive, as stated here: Persisting database connection. The database is probably not open or not ready when you do a new operation to your database.
Knowing these simple things, we probably would assume that dbAdapter.openDB() may throw an exception when the database is not yet ready. Thus, leaving the variable db still be equal to null. I assume that your error is NullPointerException and because of this, you cant do operations to your database.
TL;DR
Create a single instance of DBAdapter. Call openDB once. And call closeDB on destroy.
More or Other Sources
Kevin Galligan's Answer for Best Practices
Related
I'm setting SQLite to my app signup page and I want to use my mobile number instead of email for signing up. My app shows no error but the toast ("Registered Successfully") never appears and activity mainWindow never starts.
My Database file is below
public class DatabaseHelp extends SQLiteOpenHelper {
public DatabaseHelp( Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table user(First_NAME text ,Last_NAME text,mobile number primary key ,password text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists user");
}
//inserting in database
public boolean insert(String First_NAME,String Last_NAME,String mobile,String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("Fisrt Name",First_NAME);
contentValues.put("Last Name",Last_NAME);
contentValues.put("Mobile Number",mobile);
contentValues.put("Password",password);
long ins=db.insert("user",null,contentValues);
if(ins==-1) {return false;}
else{ return true;}
}
// if number exists
public Boolean chkemail(String mobile){
SQLiteDatabase db= this.getWritableDatabase();
Cursor cursor=db.rawQuery("Select * from user where mobile=?",new String[]{mobile});
if(cursor.getCount()>0) return false;
else return true;
}
}
My Signup page java file is below
public class signup extends AppCompatActivity {
DatabaseHelp db;
EditText e1,e2,e3,e4,e5;
Button b1;
public void onClick(View view){
Intent i1 = new Intent(this, forgotpass2.class);
startActivity(i1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
db=new DatabaseHelp(this);
e1=(EditText)findViewById(R.id.editText5);
e2=(EditText)findViewById(R.id.editText6);
e3=(EditText)findViewById(R.id.editText);
e4=(EditText)findViewById(R.id.editText7);
e5=(EditText)findViewById(R.id.editText8);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
String s3=e3.getText().toString();
String s4=e4.getText().toString();
String s5=e5.getText().toString();
if(s1.equals("")||s2.equals("")||s3.equals("")||s4.equals("")||s5.equals("")) {
Toast.makeText(getApplicationContext(), "Fields are empty", Toast.LENGTH_SHORT).show();
} else {
if(s4.equals(s5)){
Boolean chkemail=db.chkemail(s3);
if(chkemail == true) {
Boolean insert = db.insert(s1,s2,s3,s4);
if(insert == true) {
Toast.makeText(getApplicationContext(),"Registered Successfully",Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(),"Mobile Number already exits",Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(getApplicationContext(),"Passwords do not match",Toast.LENGTH_SHORT).show();
}
}
});
}
}
What should I do to make the code work properly?
There are several things in your code which need to be pointed out. First, about the insert function, the column names have spaces and I think you should get rid of those spaces for SQLite column names. Modify your insert function like the following.
public boolean insert(String First_NAME,String Last_NAME,String mobile,String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("first_name",First_NAME);
contentValues.put("last_name",Last_NAME);
contentValues.put("mobile",mobile);
contentValues.put("password",password);
long ins=db.insert("user",null,contentValues);
if(ins==-1) return false;
else return true;
}
Now, once you are done with this, I think your chkemail function now works correctly. Because, previously the field mobile was not found in the database table as the column name was different (i.e. the column name in your code was Mobile Number, which I have changed in the insert function to match with the query).
public boolean chkemail(String mobile){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from user where mobile=?",new String[]{mobile});
if(cursor.getCount()>0) return false;
else return true;
}
Please note that I have changed the return type of the chkemail function from Boolean to boolean.
And finally, in the signup activity, you need to modify the part mentioned below as well.
// Changed from Boolean to boolean
boolean insert = db.insert(s1,s2,s3,s4);
if(insert == true) {
Toast.makeText(getApplicationContext(),"Registered Successfully",Toast.LENGTH_SHORT).show();
// Start the new activity here
Intent newIntent = new Intent(this, mainWindow.class);
startActivity(newIntent);
}
Hope that helps!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to create a login funcitonality in android studio in which I verify entered password and login exist in database and go together(based on information in the login database) This should happen when the user clicks "button check login"
If the info is accurate it should take the user to a welcome screen.
I am struggling with how to check the information according to the database. Please help!
Please look at following :
DataBaseHelper.java
package com.example.login;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
// 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 _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
LoginDataBaseAdapter.java
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method to openthe Database
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
// Method to close the Database
public void close()
{
db.close();
}
// method returns an Instance of the Database
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
// method to insert a record in Table
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each column.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show();
}
// method to delete a Record of UserName
public int deleteEntry(String UserName)
{
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
// method to get the password of userName
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
return "NOT EXIST";
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
return password;
}
// Method to Update an Existing Record
public void updateEntry(String userName,String password)
{
// create object of ContentValues
ContentValues updatedValues = new ContentValues();
// Assign values for each Column.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}
SignUpActivity.java
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword;
Button btnCreateAccount;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password Does Not Matches", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
}
Please follow pseduo code:
final String email = emailEditText.getText().toString();
if (!isValidEmail(email)) {
emailEditText.setError("Invalid Email");
}
final String pass = passEditText.getText().toString();
if (!isValidPassword(pass)) {
passEditText.setError("Invalid Password");
}
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
private boolean isValidPassword(String pass) {
if (pass != null && pass.length() > 6) {
return true;
}
return false;
}
I am trying to implement an activity, that has 3 spinners (drop down lists) each of which are populated by a different table from an sqlite database. I managed to create one spinner that is populated correctly, but i am having trouble creating the other two and populating them correctly.
this is my main activity so far:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener {
private DBManager data;
private SQLiteDatabase db;
private final String DB_NAME = "hanakolfein.s3db";
private Spinner spinner;
List<String> list;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Spinner sp1, sp2, sp3;
sp1 = (Spinner) findViewById(R.id.spinner1);
sp2 = (Spinner) findViewById(R.id.spinner2);
sp3 = (Spinner) findViewById(R.id.spinner3);
sp1.setOnItemSelectedListener(null);
sp2.setOnItemSelectedListener(null);
sp3.setOnItemSelectedListener(null); */
data = new DBManager(this, DB_NAME);
db = data.openDataBase();
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
loadSpinner();
}
private void loadSpinner() {
Set<String> set = data.getAllData();
List<String> list = new ArrayList<String>(set);
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setWillNotDraw(false);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
and this is my database manager:
public class DBManager extends SQLiteOpenHelper {
//Path to the device folder with databases
public static String DB_PATH;
//Database file name
public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;
public final static int DB_VERSION = 6;
public SQLiteDatabase getDb() {
return database;
}
public DBManager(Context context, String databaseName) {
super(context, databaseName, null, DB_VERSION);
this.context = context;
//full path to the databases
String packageName = context.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
DB_NAME = databaseName;
openDataBase();
}
//This piece of code will create a database if it’s not yet created
public void createDataBase() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e(this.getClass().toString(), "Copying error");
throw new Error("Error copying database!");
}
} else {
Log.i(this.getClass().toString(), "Database already exists");
}
}
//Performing a database existence check
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
String path = DB_PATH + DB_NAME;
checkDb = SQLiteDatabase.openDatabase(path, null,SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
Log.e(this.getClass().toString(), "Error while checking db");
}
//Android doesn’t like resource leaks, everything should
// be closed
if (checkDb != null) {
checkDb.close();
}
return checkDb != null;
}
//Method for copying the database
private void copyDataBase() throws IOException {
//Open a stream for reading from our ready-made database
//The stream source is located in the assets
InputStream externalDbStream = context.getAssets().open(DB_NAME);
//Path to the created empty database on your Android device
String outFileName = DB_PATH + DB_NAME;
//Now create a stream for writing the database byte by byte
OutputStream localDbStream = new FileOutputStream(outFileName);
//Copying the database
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
//Don’t forget to close the streams
localDbStream.close();
externalDbStream.close();
}
public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
createDataBase();
database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
}
return database;
}
#Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
public Set<String> getAllData() {
Set<String> set = new HashSet<String>();
String selectQuery = "select * from cuisine";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return set;
}
#Override
public void onCreate(SQLiteDatabase db) {}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
Alright, first of all you should not query your database from the main Thread.
I recommend using a Loader as described here. You can have as many Loaders as you like, in your case 1 for each Spinner (just make sure to give them different IDs).
You need to clear that arraylist which you pass to arrayadapter. Because when you use first spinner, you are calling gatAllData & storing that data in arraylist, passing it to arrayadapter. Next time for second spinner you are doing same procedure but it is concatenating to previous entries of arraylist. So before calling to getAllData you need to clear your arraylist. It'll solve your problem.
I'm using SQLite Database for insert , create or update data in my application.I want to change the password in my SQLite database.I'm having problem for change the password in my app. When I run the demo and enter the whatever field is there and hit the Button for change the data in database it goes to else condition. Nothing to show any error or exceptions in log cat. Is there any way to do that? Here is my code.
This is my DBHelper class
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(DataBase_Adapter.DATABASE_CREATE_LOGIN);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to "+_newVersion + ", which will destroy all old data");
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
onCreate(_db);
}
}
This DataBaseAdapter Class Code
public static final String TABLE_NAME_LOGIN="LOGIN";
//Colum,n Names
public static final String KEY_LOGIN_ID="ID";
public static final String KEY_USERNAME="USERNAME";
public static final String KEY_EMAIL_ID="EMAILID";
public static final String KEY_PASSWORD="PASSWORD";
//Table Create Statement
public static final String DATABASE_CREATE_LOGIN = "CREATE TABLE "+TABLE_NAME_LOGIN+" ("+KEY_LOGIN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_USERNAME+" TEXT, "+KEY_EMAIL_ID+" TEXT, "+KEY_PASSWORD+" TEXT)";
//Insert Data in Database Login
public void insertEntry(String userName,String userEmail,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_USERNAME , userName);
newValues.put(KEY_EMAIL_ID , userEmail);
newValues.put(KEY_PASSWORD , password);
// Insert the row into your table
db.insert(TABLE_NAME_LOGIN, null, newValues);
}
//Update Query
public boolean change(String strEmailId , String strNewPin1 )
{
Cursor cur=db.rawQuery("UPDATE "+TABLE_NAME_LOGIN +" SET " + KEY_PASSWORD+ " = '"+strNewPin1+"' WHERE "+ KEY_EMAIL_ID +"=?", new String[]{strEmailId});
if (cur != null)
{
if(cur.getCount() > 0)
{
return true;
}
}
return false;
}
This is my Change Pin Activity
public class Change_Pin_Activity7 extends Activity
{
EditText editText_EmailId , editText_changePin1 , editText_changePin2;
Button buttonChangePin;
TextView textView_PasswordMatch;
String strEmailId , strNewPin1 , strNewPin2;
boolean storedNewData;
DataBase_Adapter dbAdapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.change_pin_activity7);
dbAdapter=new DataBase_Adapter(this);
dbAdapter=dbAdapter.open();
editText_EmailId=(EditText)findViewById(R.id.EditText_EmailId);
editText_changePin1=(EditText)findViewById(R.id.EditText_Pin1);
editText_changePin2=(EditText)findViewById(R.id.EditText_Pin2);
textView_PasswordMatch=(TextView)findViewById(R.id.TextView_PinProblem);
buttonChangePin=(Button)findViewById(R.id.button_ChangePin);
buttonChangePin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
strEmailId = editText_EmailId.getText().toString().trim();
strNewPin1 = editText_changePin1.getText().toString().trim();
strNewPin2 = editText_changePin2.getText().toString().trim();
storedNewData=dbAdapter.change(strEmailId , strNewPin1);
if (strNewPin1.equals(storedNewData))
{
textView_PasswordMatch.setText("Password Match !!!");
Toast.makeText(Change_Pin_Activity7.this,
"Pin Change Successfully", Toast.LENGTH_LONG).show();
}
// check if any of the fields are vaccant
if(strEmailId.equals("")||strNewPin1.equals("")||strNewPin2.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!strNewPin1.equals(strNewPin2))
{
Toast.makeText(getApplicationContext(), "Pin does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
Toast.makeText(getApplicationContext(),"Not Working ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
dbAdapter.close();
}
}
When is if (strNewPin1.equals(storedNewData)) ever going to succeed, if strNewPin1 is a String, and storedNewData is a boolean.
So I am trying to create an application that allows users to put strings into a SQLite database and view the logs in another activity. But when I open the next activity, the application has a forced close and crashes. Here's my code from the activity where the users put the information into a database
Button ViewLogs = (Button)findViewById(R.id.button1);
ViewLogs.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent view = new Intent(StartBitching.this, ViewLogs.class);
startActivity(view);
// TODO Auto-generated method stub
}
}
);
Button MostWanted = (Button)findViewById(R.id.button2);
MostWanted.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent most = new Intent(StartBitching.this, MostWanted.class);
startActivity(most);
}
});
Button Add = (Button)findViewById(R.id.button3);
Add.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtName = (EditText)findViewById(R.id.editText1);
EditText txtDate = (EditText)findViewById(R.id.editText2);
EditText txtSummary = (EditText)findViewById(R.id.editText3);
DatabaseConnector dc = new DatabaseConnector(null);
try
{
String Name = txtName.getText().toString();
String Date = txtDate.getText().toString();
String Summary = txtSummary.getText().toString();
dc.insertLog(Name, Date, Summary);
txtName.setText("");
txtDate.setText("");
txtSummary.setText("");
}
catch(Exception ex)
{
txtName.setText(ex.getMessage().toString());
}
Here is my database connector activity
public class DatabaseConnector{
private static final String DATABASE_NAME = "Blacklist";
private SQLiteDatabase database; // database object
private DatabaseOpenHelper databaseOpenHelper; // database helper
// public constructor for DatabaseConnector
{
Context context = null;
// create a new DatabaseOpenHelper
databaseOpenHelper =
new DatabaseOpenHelper(context, DATABASE_NAME, null, 1);
} // end DatabaseConnector constructor
public DatabaseConnector(ViewLogs viewLogs) {
// TODO Auto-generated constructor stub
}
// open the database connection
public void open() throws SQLException
{
// create or open a database for reading/writing
database = databaseOpenHelper.getWritableDatabase();
} // end method open
// close the database connection
public void close()
{
if (database != null)
database.close(); // close the database connection
} // end method close
// inserts a new dog in the database
public void insertLog(String Name,
String Date, String Summary)
{
try
{
ContentValues newLog = new ContentValues();
newLog.put("Name", Name);
newLog.put("Date", Date);
newLog.put("Summary", Summary);
open(); // open the database
database.insert("logs", null, newLog);
close(); // close the database
}
catch (Exception e){}
} // end method insertDog
public void updateDog(long id, String Name, String Date, String Summary)
{
ContentValues editContact = new ContentValues();
editContact.put("Name", Name);
editContact.put("Date", Date);
editContact.put("Summary", Summary);
open(); // open the database
database.update("logs", editContact, "_id=" + id, null);
close(); // close the database
} // end method updateContact
// return a Cursor with all contact information in the database
public Cursor getAllLogs()
{
return database.query("logs", new String[] {"_id", "Name", "Date", "Summary"},
null, null, null, null, "Name");
} // end method getAllContacts
// get a Cursor containing all information about the contact specified
// by the given id
public Cursor getOneContact(long id)
{
return database.query(
"contacts", null, "_id=" + id, null, null, null, null);
} // end method getOnContact
// delete the contact specified by the given String name
public void deleteLog(long id)
{
open(); // open the database
database.delete("logs", "_id=" + id, null);
close(); // close the database
} // end method deleteContact
private class DatabaseOpenHelper extends SQLiteOpenHelper
{
// public constructor
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version)
{
super(context, name, factory, version);
} // end DatabaseOpenHelper constructor
// creates the contacts table when the database is created
#Override
public void onCreate(SQLiteDatabase db)
{
// query to create a new table named dog
String createQuery = "CREATE TABLE logs" +
"(_id integer primary key autoincrement," +
"Name TEXT," +
"Date TEXT," +
"Summary TEXT);";
db.execSQL(createQuery); // execute the query
} // end method onCreate
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
} // end method onUpgrade
} // end class DatabaseOpenHelper
}
And here is the code from the application that's supposed to allow the user to view all logs in the database
public class ViewLogs extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_logs);
DatabaseConnector dc = new DatabaseConnector(this);
dc.open();
Cursor c = dc.getAllLogs();
String[] logs = new String[0];
if (c !=null)
{
do{
String Name = c.getString(c.getColumnIndex("Name"));
String Date = c.getString(c.getColumnIndex("Date"));
String Summary = c.getString(c.getColumnIndex("Summary"));
TableLayout rl1 =(TableLayout)findViewById(R.id.rel);
for( String log: logs)
{
TextView lbl = (TextView)findViewById(R.id.texter);
lbl.setText(log);
rl1.addView(lbl);
}
}while (c.moveToNext());
}
super.onResume();
}
}
I know this is a lot of code and it might be very hard to read but I am new to programming and If I could get any help at all I would really appreciate it
You should look at using a content provider and cursor loaders, it's a bit of work but it's probably the best way to be able to share data due to a couple of reasons, see
for my opinion on content providers see Android: What is better, using a SQLiteCursorLoader or implementing a ContentProvider?
These links might also help How to use Loaders in Android and Content Providers part 1
Hope this helps