I can't view logs from my database - java

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

Related

Android application crashes when I click save button or search

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

create new table for every item of in another table on Android

I want to create a new table in the database for every label input by the user and the table will have two columns quiz and note but I keep getting an error. I also want to know if there are other ways to achieve this.
These are my codes:
package com.example.mybank;
public class SomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.select);
choose = (Button) findViewById(R.id.register);
save = (Button) findViewById(R.id.save);
inputcos = (EditText) findViewById(R.id.inputcos);
select = (Spinner) findViewById(R.id.spinner);
choose.setOnClickListener(this);
save.setOnClickListener(this);
select.setOnItemSelectedListener(this);
loadSpinnerData();
}
private void loadSpinnerData() {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
select.setAdapter(dataAdapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Boolean testing = true;
switch (v.getId()) {
case R.id.register:
save.setVisibility(View.VISIBLE);
inputcos.setVisibility(View.VISIBLE);
break;
case R.id.save:
try {
label = inputcos.getText().toString();
if (label.trim().length() > 0) {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// inserting new label into database
db.insertLabel(label);
// making input filed text to blank
inputcos.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputcos.getWindowToken(), 0);
// loading spinner with newly added data
loadSpinnerData();
} else {
Toast.makeText(getApplicationContext(), "Please enter course",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
testing = false;
if (testing) {
if (testing) {
Dialog dd = new Dialog(this);
String error = e.toString();
dd.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
dd.setContentView(tv);
dd.show();
}
}
} finally {
if (testing) {
Dialog dd = new Dialog(this);
TextView tv = new TextView(this);
if (label.trim().length() > 0) {
dd.setTitle("Success");
tv.setText("course sucessfully added");
} else {
dd.setTitle("warning");
tv.setText("no course input");
}
dd.setContentView(tv);
dd.show();
}
}
break;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//creating database table for each label of the list view
if (label.trim().length() > 0) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.createnewtable(label);
}
Intent i = new Intent(this, choices.class);
startActivity(i);
// Showing selected spinner item
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Database class:
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "spinnerExample";
// Labels table name
private static final String TABLE_LABELS = "labels";
static final String TABLE_SPINNER = "course";
// Labels Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_NOTE="note";
private static final String KEY_QUIZES="quiz";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT NOT NULL)";
db.execSQL(CREATE_CATEGORIES_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_LABELS);
// Create tables again
onCreate(db);
}
// creating tables for labels
public void createnewtable(String course){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "CREATE TABLE " + course + " (" + KEY_QUIZES
+ " text not null, " + KEY_NOTE + " text not null " + ");";
Log.i("createDB=", sql);
db.execSQL("DROP TABLE IF EXISTS TABLE_SPINNER");
db.execSQL(sql);
}
/**
* Inserting new labels into labels table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
int i = (int) db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
//Now create new table for this category
if (i > 0) {
createnewtable(label);}
}
public long insertquiz(String quiz){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUIZES, quiz);
// Inserting Row
return db.insert(TABLE_SPINNER,null, values);
}
public long insertnote(String note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note);
// Inserting Row
return db.insert(TABLE_SPINNER,null, values);
}
/**
* Getting all labels
* returns list of labels
* */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;}
public List<String> getAllquestions(){
List<String> quiz = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM TABLE_SPINNER WHERE category =" + KEY_QUIZES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
quiz.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return quiz;
}
}
Here's a list of the errors I see.
TABLE_SPINNER is only every dropped and inserted into. Never created in onCreate.
You're dropping that tablet with every call to createnewtable, but it was never created it.
You're using TABLE_SPINNER as the correct table name in the insert statements, but it's in a string literal within the DROP and SELECT statements, so you'll very likely get a Table not found error. You need to always use your variable.
Once the above are addressed, the insert quiz and insert note must be combined. You defined those columns as not null, so if you insert one key into the content values, the other value will be null, and throw an error.
Beware of SQL injection - "SELECT * FROM " + TABLE_LABELS;
That can just be replaced by db.query(TABLE_LABELS, null, null,...
Ovrerall, you should not make tables based on arbitrary string values. How do you query them later? You'd have to know the name of the table to do that.
And there's no benefit of dividing any data of the same exact schema into individual tables. You instead should add a column for String course within a table, not create a table only for String course, then you filter using WHERE course = ?

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;
}

incompatible operand types r.integer and int

I am trying to compare the integer type list and position in the spinner. The integer list contains the list of IDs from a database and the spinner contains the list of names with respect to the IDs. The IDs and names are stored in a database, after comparing the ID from the list and the position from the spinner, two edit text boxes are set to the values corresponding to the specific ID other than name.
The ID is set to auto increment.
Here is the MainActivity:
public class LoginActivity extends AppCompatActivity {
Button b;
EditText ed1, ed2, ed3;
Spinner sp;
String url = "https://web.facebook.com/";
String urltest = "http://www.google.com/";
WebView wb;
database db;
String details[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
b = (Button) findViewById(R.id.button1);
ed1 = (EditText) findViewById(R.id.editText1);
ed2 = (EditText) findViewById(R.id.editText2);
ed3 = (EditText) findViewById(R.id.editText3);
wb = (WebView) findViewById(R.id.webView1);
sp = (Spinner) findViewById(R.id.spinner1);
db = new database(LoginActivity.this);
// wb.loadUrl(url);
List<String> l = db.userlist();
final List<Integer> idlist = db.IDList();
ArrayAdapter<String> sa = new ArrayAdapter<String>(LoginActivity.this, android.R.layout.simple_spinner_item, l);
sp.setAdapter(sa);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
user u = new user();
String name = ed1.getText().toString();
String uname = ed2.getText().toString();
String pass = ed3.getText().toString();
if (name.length() > 0 && uname.length() > 0 && pass.length() > 0) {
u.setName(name);
u.setUname(uname);
u.setPass(pass);
db.insert(u);
ed1.setText("");
ed2.setText("");
ed3.setText("");
} else {
Toast.makeText(LoginActivity.this, "Please enter the Name, User Name and password",
Toast.LENGTH_SHORT).show();
}
Toast.makeText(LoginActivity.this, "The user name details has been saved.", Toast.LENGTH_LONG).show();
}
});
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
if (idlist.get(position) == position) {
details = db.details(position);
ed2.setText(details[0]);
ed3.setText(details[1]);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
I have created two other java files as database.java which creates database and returns:
public class database extends SQLiteOpenHelper {
public static String dbname = "Personal";
public static int version = 1;
public static String tblname = "Data";
public static String id = "ID";
public static String name = "Name";
public static String uname = "Username";
public static String pass = "Password";
public database(Context context) {
super(context, dbname, null, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql1 = "create table " + tblname + " (" + id + " integer primary key autoincrement, " + name + " text, "
+ uname + " text, " + pass + " text)";
db.execSQL(sql1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
void insert(user u) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(name, u.getName());
values.put(uname, u.getUname());
values.put(pass, u.getPass());
db.insert(tblname, id, values);
}
public List<String> userlist() {
List<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(tblname, new String[] { name }, null, null, null, null, null);
while (cursor.moveToNext()) {
String data = cursor.getString(0);
list.add(data);
// Log.e("1", data);
}
return list;
}
public List<integer> IDList() {
List<integer> idlist = new ArrayList<integer>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(tblname, new String[] { id }, null, null, null, null, null);
while (cursor.moveToNext()) {
String data = cursor.getString(0);
idlist.add(Integer.parseInt(data), null);
}
return idlist;
}
public String[] details(int position) {
String username = null, password=null;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(tblname, new String[] { id, uname, pass }, null, null, null, null, null);
while (cursor.moveToNext()) {
if (position == cursor.getInt(0)) {
username = cursor.getString(1);
password = cursor.getString(2);
} else {
return null;
}
}
return new String[] {username, password};
}
}
and a user.java to get and set the details:
public class user {
String id, name, uname, pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
I was getting an error in MainActivity.java file as incompatible operand types r.integer and int. This is on the line if(idlist.get(position)==position) ---- It is in the spinner set on item selected listener which is now solved by changing integer to Integer. But the statement is somehow invalid. It cannot compare Integer and int. Any suggestions to rectify it?
'integer' really exists as a nested class of class 'R'
. So your List was interpreted as a List for data type R.integer, but 'R.integer' and the primitive data type 'int' are not compatible.
As the purpose of class 'Integer' is to turn integer numbers into objects when needed, it is not compatible as well.
EDIT:
So the first thing you want to do is to change every 'integer' in your code to 'Integer', because you want to deal with numbers, not with android resources.
Looking at the method where your crash occurred, it's a bit difficult to tell what you need to do to make your code work (not just 'not crash').
The 'position' value in your 'onItemSelected()' method will give you the index of your List 'l' corresponding to the selected ListView row.
Now you seem to check wether the list index of one user name is equal to the userid in your SQLite DB. As I don't know your data model, I can't tell wether doing so makes sense. I only know that you did fill 'idlist' and 'l' by separate queries into the database and you included no 'ORDER BY', so maybe the names and the ids will even not be ordered the same way.
But that's another question... :)
You have to use:
List<Integer> list = new ArrayList<Integer>();
There is a difference between integer and Integer.
Try to use this, I hope it will help you.

Change Password In SQLite Database in Android

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.

Categories

Resources