Change Password In SQLite Database in Android - java

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.

Related

Android Studio + Database - Multiple check data to insert data if not exists

I'm having a problem with my code. I don't know how to check multiple columns in the database to insert different data on every not existing data.
For example:
1st input
Name: Raymond Jay Berin
Event: INTRAMURALS
FACILITATOR: CSG
2nd input
Name: Raymond Jay Berin
Event: LOVE SYMPOSIUM
FACILITATOR: DSSC
the thing here is that. Raymond Jay Berin already existed in the database, but I want Raymond Jay Berin will be inserted into a different event...
also, I already tried to create multiple tables but my project crashes when I click the attendance button to add data.
Code for DatabaseHelper.class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.sqlite";
public static final String TABLE_NAME = "attendance";
public static final String COL_1 = "ID";
public static final String COL_2 = "FULLNAME";
public static final String COL_EVENT_2 = "EVENT_NAME";
public static final String COL_EVENT_3 = "FACILITATOR_NAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
//ATTENDANCE
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FULLNAME TEXT NOT NULL, EVENT_NAME TEXT NOT NULL, FACILITATOR_NAME TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//ATTENDANCE
db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME );
//recreate
onCreate(db);
}
//ATTENDANCE
public boolean insertData (String fullname, String event, String facilitator){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,fullname);
contentValues.put(COL_EVENT_2,event);
contentValues.put(COL_EVENT_3,facilitator);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean checkIfRecordExist(String nameOfTable,String columnName,String columnValue) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT "+columnName+" FROM "+nameOfTable+" WHERE "+columnName+"='"+columnValue+"'",null);
if (cursor.moveToFirst()) {
db.close();
Log.d("Record Already Exists", "Table is:" + nameOfTable + " ColumnName:" + columnName);
return true;//record Exists
}
Log.d("New Record ", "Table is:" + nameOfTable + " ColumnName:" + columnName + " Column Value:" + columnValue);
db.close();
} catch (Exception errorException) {
Log.d("Exception occured", "Exception occured " + errorException);
db.close();
}
return false;
} }
Code for the Attendance.java class
public class Attendance extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DatabaseHelper myDb;
EditText fname , eventname, faciname;
Button attendance;
Button view;
Switch lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
myDb = new DatabaseHelper(this);
fname = findViewById(R.id.txtFullname);
eventname = findViewById(R.id.eventname);
faciname = findViewById(R.id.faciname);
attendance = findViewById(R.id.btnatt);
view = findViewById(R.id.btnview);
lock = findViewById(R.id.switchLock);
viewAll();
AddData();
lock.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (lock.isChecked()){
eventname.setEnabled(false);
faciname.setEnabled(false);
}else{
eventname.setEnabled(true);
faciname.setEnabled(true);
}
}
public void viewAll() {
view.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("ID :" + res.getString(0) + "\n");
buffer.append("NAME :" + res.getString(1) + "\n");
buffer.append("EVENT :" + res.getString(2) + "\n");
buffer.append("FACILITATOR :" + res.getString(3) + "\n"+"\n");
}
// Show all data
showMessage("ATTENDANCE LIST", buffer.toString());
}
}
);
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
public void AddData() {
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String valInput = fname.getText().toString();
final String valInput1 = eventname.getText().toString();
final String valInput2 = faciname.getText().toString();
boolean valid = true;
if (TextUtils.isEmpty(valInput)) {
fname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput1)) {
eventname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput2)) {
faciname.setError("This Item must not be empty!");
valid = false;
}
if (valid) {
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString());
if (!isExist) {
boolean isInserted = myDb.insertData(fname.getText().toString(), eventname.getText().toString(), faciname.getText().toString());
if (isInserted) {
Toast.makeText(Attendance.this, "Attendance Success", Toast.LENGTH_LONG).show();
fname.setText(null);
} else if (isInserted == false) {
Toast.makeText(Attendance.this, "Failed to Attendance", Toast.LENGTH_LONG).show();
}
}else if (isExist == true){
Toast.makeText(Attendance.this, "Failed to Attendance "+fname+" Already Existed", Toast.LENGTH_LONG).show();
}
}
}
}); }
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.Logout)
.setMessage(R.string.really_logout)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = new Intent(Attendance.this, MainActivity.class);
startActivity(intent);
Attendance.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}}
change checkIfRecordExist method like this
public boolean checkIfRecordExist(String nameOfTable,String columnName1,String columnValue1,String columnName2,String columnValue2) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+nameOfTable+" WHERE "+columnName1+"='"+columnValue1+"' and "+ columnName2 +"='"+columnValue2+"'",null);
.......................
change below line like this
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString(),DatabaseHelper.COL_2, eventname.getText().toString())

Android Studio can't insert data into sqlitedatabase

I'm doing a small project for my mobile app subject. I need to link it with sqlitedatabase.
I've been the tutorial at the Youtube, I followed the tutorial step by step. I didn't got any error from the code.
I need to insert the value into the db and display it back but the user input didn't inserted into db so I couldn't display the data from the DB.
I hope someone could help me. I've been stuck for 2 days because of this problem with no error display.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "STUDENT.DB";
//create table
public static final String TABLE_STUDENT = "STUDENT_TABLE";
public static final String COL_STD_ID = "STD_ID";
public static final String COL_STD_NAME = "STD_NAME";
public static final String COL_STD_EMAIL = "STD_EMAIL";
public static final String COL_STD_ADDRESS = "STD_ADDRESS";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME, null, 1);
Log.e("DATABASE OPERATION","Database created/opend...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_STUDENT +" (STD_ID INTEGER PRIMARY KEY AUTOINCREMENT,STD_NAME TEXT,STD_EMAIL TEXT, STD_ADDRESS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_STUDENT );
onCreate(db);
}
public boolean insertData(String STD_NAME, String STD_EMAIL, String STD_ADDRESS)
{
SQLiteDatabase db = this.getWritableDatabase();
//get the data from user into db
ContentValues contentValues = new ContentValues();
contentValues.put(COL_STD_NAME,STD_NAME);
contentValues.put(COL_STD_EMAIL,STD_EMAIL);
contentValues.put(COL_STD_ADDRESS,STD_ADDRESS);
//SEE WHETHER THE DATA INSERT INTO DB OR NOT
//IF RETURN -1, DATA NOT SUCCESSFUL INSERTED
long result = db.insert(TABLE_STUDENT,null,contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + TABLE_STUDENT,null);
return result;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etstdName, etstdEmail, etstdAddress;
Button btnInsertData, btnViewData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etstdName = (EditText)findViewById(R.id.etstdName);
etstdEmail = (EditText)findViewById(R.id.etstdEmail);
etstdAddress = (EditText)findViewById(R.id.etstdEmail);
btnViewData = (Button)findViewById(R.id.btnViewData);
btnInsertData = (Button)findViewById(R.id.btnInsertData);
InsertStdData();
}
// I think i get stuck at here but theres not error display at InsertStdData() methid
public void InsertStdData() {
btnInsertData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(etstdName.getText().toString(),
etstdEmail.getText().toString(),
etstdAddress.getText().toString());
if(isInserted = true)
Toast.makeText(MainActivity.this,"Data successfully inserted.",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not successfully inserted.",Toast.LENGTH_LONG).show();
}
});
}
public void viewStdData(View view) {
Cursor result = myDB.getAllData();
if(result.getCount() == 0) {
//showmessage method
showMessage("ERROR", "NO DATA FOUND");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()){
buffer.append("STD_ID : "+result.getString(0)+"\n");
buffer.append("STD_NAME : "+result.getString(1)+"\n");
buffer.append("STD_EMAIL : "+result.getString(2)+"\n");
buffer.append("STD_ADDRESS :"+result.getString(3)+"\n\n");
}
//show all data
showMessage("DATA",buffer.toString());
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
You called InsertStdData() but you didnt call viewStdData(View view) in your MainActivity.

How do I check that login and password entered is valid [closed]

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 can't view logs from my database

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

Regarding Android Database

Hot To Create A Table in database only once and insert data into that table multiple times in android using SQLite DB...??
You should be sub-classing SQLiteOpenHelper and making use of its convenience methods which will remove a lot of the complexity of using SQLite. See Data Storage
Take a look at the NotePadProvider sample.
This is my activity class
public class d extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String name=getIntent().getStringExtra("name");
String email=getIntent().getStringExtra("email");
String phone=getIntent().getStringExtra("phone");
Log.e("d3","came to other activity");
SmartDBHelper d=new SmartDBHelper(getApplicationContext());
d.open();
d.insertTitle(name, phone, email);
Cursor c=d.getAllTitles();
// c.getColumnName(0);
for( int i=0;i<c.getCount();i++){
if(c.moveToNext()){
Log.e("c", ""+ c.getString(0) );
Log.e("d", ""+ c.getString(1) );
Log.e("d4", ""+ c.getString(2) );
}
Log.e("r",""+c.getCount());
finish();
}
}
}
here is my sqllite class
public class SmartDBHelper extends SQLiteOpenHelper {
private SQLiteDatabase dBH;
private static final String DATABASE_NAME = "yo.db";
private static final int DATABASE_VERSION = 2;
private static final String NOTIFY_TABLE_NAME = "user_notify_data";
private static final String HR_TABLE_NAME = "user_hr_data";
private static final String NOTIFY_TABLE_CREATE =
"CREATE TABLE " + NOTIFY_TABLE_NAME + " (counter INTEGER PRIMARY KEY, " +
"userresponse TEXT, " +
"notifytime TEXT);";
private static final String HR_TABLE_CREATE =
"CREATE TABLE " + HR_TABLE_NAME +
" (counter INTEGER PRIMARY KEY, " +
"hr TEXT, " +
"act TEXT, " +
"timestamp TEXT);";
public SmartDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.e("smartdbhelper", "before creation");
db.execSQL(NOTIFY_TABLE_CREATE);
Log.e("smartdbhelper", "middle creation");
db.execSQL(HR_TABLE_CREATE);
Log.e("smartdbhelper", "after creation");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public SmartDBHelper open() throws SQLException
{
dBH = getWritableDatabase();
return this;
}
public long insertTitle(String isbn, String title, String publisher)
{
ContentValues initialValues = new ContentValues();
initialValues.put("hr", isbn);
initialValues.put("act", title);
initialValues.put("timestamp", publisher);
Log.e("insertes","i");
dBH.insert(HR_TABLE_NAME, null, initialValues);
return 11111111;
}
public Cursor getAllTitles()
{
return dBH.query(HR_TABLE_NAME, new String[] {
"hr","act","timestamp"},null,
null,
null,
null,
null);
}
//---closes the database---
public void close()
{
close();
}
}
The above code works and has been tested

Categories

Resources