trying to get coords from database but nothing happens - java

as you can see from the code below im just trying to get the coords pushed out to the logcat. however i never see the message or the coords. it shows me the sql string then finishes. so i believe the try is failing but even the catch statement doesnt return anything.
Button ButtonMap = (Button) findViewById(R.id.ButMap);
ButtonMap.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
/* Query for some results with Selection and Projection. */
String sql = "SELECT _id,Longitude,Latitude FROM " + MY_DATABASE_TABLE + " WHERE _id = "+ID;
Cursor c = db.rawQuery(sql,null);
//db.query(MY_DATABASE_TABLE, new String[] {"_id", "Longitude", "Latitude"},
// "_id = " + "'%"+ID+"%'", null, null, null, null);
Log.e("SQL Select", sql);
/* Get the indices of the Columns we will need */
int longitude, latitude ;
longitude = c.getColumnIndex("Longitude");
latitude = c.getColumnIndex("Latitude");
/* Check if our result was valid. */
if (c.moveToFirst()) {
int i = 0;
/* Loop through all Results */
do {
i++;
/* Retrieve the values of the Entry
* the Cursor is pointing to. */
double lat = c.getDouble(latitude);
double lon = c.getDouble(longitude);
Log.e("GPS", "location for this record is: lat="+lat+", lon="+lon);
} while (c.moveToNext());
}
} catch (Throwable t) {
Log.e("GPS", t.toString());
}
finally {
if (db != null)
db.close();
}
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}

been to long to know exactly what fixed it but here is the answer code:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SqlLiteFishLoggerDao extends SQLiteOpenHelper implements
FishLoggerDao {
private static final String DB_NAME = "fishingLog";
private static final String TABLE_NAME = "LogEntries";
private static final String DELETE_LOG_ENTRY_SQL = "DELETE FROM LogEntries WHERE _id = ?;";
private static final String FIND_LOG_ENTRY_SQL = "SELECT * FROM LogEntries WHERE _id = ?";
private static final String FIND_ALL_ENTRIES_SQL = "SELECT * FROM LogEntries";
private static final String[] NO_ARGS = {};
private Context context;
private SQLiteDatabase DB;
public SqlLiteFishLoggerDao(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
#Override
public void deleteLogEntry(String id) {
DB = getWritableDatabase();
DB.execSQL(DELETE_LOG_ENTRY_SQL, new Object[] { id });
DB.close();
}
#Override
public LogEntry findEntry(String id) {
DB = getReadableDatabase();
Cursor cursor = DB.rawQuery(FIND_LOG_ENTRY_SQL,
new String[] { id });
if (!cursor.moveToFirst()) {
return null;
}
LogEntry entry = new LogEntry();
entry.setId(cursor.getString(cursor.getColumnIndex("_id")));
entry.setEntryDate(cursor.getString(cursor.getColumnIndex("CreateDate")));
entry.setSpecies(cursor.getString(cursor.getColumnIndex("Species")));
entry.setSizeOrWeight(cursor.getString(cursor.getColumnIndex("SizeOrWeight")));
entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
entry.setLongitude(cursor.getDouble(cursor.getColumnIndex("Longitude")));
entry.setPictureUrl(cursor.getString(cursor.getColumnIndex("PictureURL")));
cursor.close();
DB.close();
return entry;
}
#Override
public void insertLogEntry(LogEntry entry) {
DB = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Latitude", entry.getLatitude());
values.put("Longitude", entry.getLongitude());
values.put("PictureURL", entry.getPictureUrl());
values.put("SizeOrWeight", entry.getSizeOrWeight());
values.put("CreateDate", entry.getEntryDate());
values.put("Species", entry.getSpecies());
DB.insertOrThrow("LogEntries", null, values);
DB.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
String s;
try {
InputStream in = context.getResources().openRawResource(R.raw.sql);
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in, null);
NodeList statements = doc.getElementsByTagName("statement");
for (int i = 0; i < statements.getLength(); i++) {
s = statements.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
Log.e("DB", "DB Created Successfully");
} catch (Throwable t) {
Log.e("DB error: ",t.toString());
}
}
#Override
public List<LogEntry> findAllEntries() {
DB = getReadableDatabase();
List<LogEntry> entries = new ArrayList<LogEntry>();
Cursor cursor = DB.rawQuery(FIND_ALL_ENTRIES_SQL,
NO_ARGS);
if (cursor.moveToFirst()) {
do {
LogEntry entry = new LogEntry();
entry.setId(cursor.getString(cursor.getColumnIndex("_id")));
entry.setEntryDate(cursor.getString(cursor.getColumnIndex("CreateDate")));
entry.setSpecies(cursor.getString(cursor.getColumnIndex("Species")));
entry.setSizeOrWeight(cursor.getString(cursor.getColumnIndex("SizeOrWeight")));
entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
entry.setLongitude(cursor.getDouble(cursor.getColumnIndex("Longitude")));
entry.setPictureUrl(cursor.getString(cursor.getColumnIndex("PictureURL")));
if (entry.getSpecies() == null) {
entry.setSpecies("Not Entered");
}
if (entry.getSizeOrWeight() == null) {
entry.setSizeOrWeight("Not entered");
}
entries.add(entry);
} while (cursor.moveToNext());
}
cursor.close();
DB.close();
return entries;
}
#Override
public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
DB = getWritableDatabase();
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(getWritableDatabase());
DB.close();
}
}

Related

How to fix a database login issue?

I'm a beginner, and I want to ask about a problem I've got with my app. I try to log with the data I put into the database but it recognizes nothing.
Here's the code of the DatabaseHelper Java file. I think the problem is with my checkData_pseudo_pass function.
Thanks in advance for the response!
DatabaseHelper.java
package com.example.tp5;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "database.db";
public static final String TABLE_NAME = "tp4_table";
/*
public static final String COL_1 = "ID";
public static final String COL_2 = "NOM";
public static final String COL_3 = "PRENOM";
public static final String COL_4 = "PSEUDO";
public static final String COL_5 = "PASS";
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NOM TEXT,PRENOM TEXT,PSEUDO TEXT,PASS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean InsererData(String nom, String prenom, String pseudo, String pass){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nom",nom);
contentValues.put("prenom",prenom);
contentValues.put("pseudo", pseudo);
contentValues.put("pseudo", pass);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
/*
public boolean insertData(String nom, String prenom, String pseudo, String pass) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,nom);
contentValues.put(COL_3,prenom);
contentValues.put(COL_4,pseudo);
contentValues.put(COL_5,pass);
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 checkData_Pass(String pass){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res_pass = db.rawQuery("select * from tp4_table where PASS=? ",new String[]{pass});
if(res_pass.getCount()>0) return false;
else {
return true;
}
}
*/
public Boolean checkData_pseudo_pass(String pseudo, String pass){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res_unique = db.rawQuery("select * from tp4_table where PSEUDO=? and PASS=?", new String[]{pseudo, pass});
if(res_unique.getCount()>0) return false;
else {
return true;
}
}
}
MainActivity3.java
package com.example.tp5;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity3 extends AppCompatActivity{
DatabaseHelper myDb_connexion; // création de l'objet mydb de type DatabaseHelper
private Button valider_connexion2 = null;
private EditText pseudo_connexion = null;
private EditText pass_connexion = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitymain3);
myDb_connexion = new DatabaseHelper(this);
valider_connexion2 = findViewById(R.id.button3);
pseudo_connexion = findViewById(R.id.edit_pseudo_connexion);
pass_connexion = findViewById(R.id.edit_pass_connexion);
//EditText textView_pseudo = (EditText) findViewById(R.id.edit_pseudo_connexion);
//EditText textView_pass = (EditText) findViewById(R.id.edit_pass_connexion);
valider_connexion2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String _str_pseudo = pseudo_connexion.getText().toString().trim();
String _str_pass = pass_connexion.getText().toString().trim();
Intent intent3 = new Intent(MainActivity3.this, MainActivity4.class);
Boolean check_Pseudo_Pass = myDb_connexion.checkData_pseudo_pass(_str_pseudo, _str_pass);
//Si Check_Pseudo_Pass affiche le pseudo et le pass
//if (check_Pseudo_Pass == true && !str_pseudo.equals("") && !str_pass.equals(""))
if (check_Pseudo_Pass == true)
{
intent3.putExtra("pseudo", _str_pseudo);
intent3.putExtra("pass", _str_pass);
startActivity(intent3);
Toast.makeText(MainActivity3.this,"Connexion réussie !",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity3.this,"Connexion raté !",Toast.LENGTH_SHORT).show();
}
// Question 7:Connexion unique Login="Admin",pass="root" et Extra enregistre le pseudo et le mot de passe pour le récupérer à la pas MainActivité
/*
Intent intent3 = new Intent(MainActivity3.this, MainActivity4.class);
// if (!str_pseudo.equals("") && !str_pass.equals("") ) {
if (str_pseudo.equals("Admin") && str_pass.equals("root") ) {
intent3.putExtra("pseudo", str_pseudo);
intent3.putExtra("pass", str_pass);
Toast.makeText(MainActivity3.this,"Connexion réussie !",Toast.LENGTH_SHORT).show();
startActivity(intent3);
}else{
Toast.makeText(MainActivity3.this,"Connexion raté !",Toast.LENGTH_SHORT).show();
}
*/
}
});
}
}
Consider this method:
public Boolean checkData_pseudo_pass(String pseudo, String pass){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res_unique =
db.rawQuery("select * from tp4_table where PSEUDO=? and PASS=?",
new String[]{pseudo, pass});
if (res_unique.getCount() > 0) {
return false;
} else {
return true;
}
}
This returns false if any of the rows in tp4_table matches the given pseudo and pass and true otherwise.
In other words, it fails if the username and password are correct.
The logic of the test is backwards. It should be:
if (res_unique.getCount() > 0) {
return true;
} else {
return false;
}
or better still, just this:
return res_unique.getCount() > 0;
If you still have a problem after this change, then it is somewhere else in the code. For example, you may not have populated the database correctly.
And you should return boolean not Boolean.
And you should fix the numerous stye errors in your code, starting the many cases of identifiers that do not follow the style rules:
variable names and method names start with a lowercase letter
no underscores (_) as in variable names, method names, class names or package names
use camel case instead of underscores between words (except for constant names).

Why SQLite to ImageView, BitmapFactory.decodeByteArray Returning Null?

I'm developing a contacts app with a photo. I have Store and retrieve data from SQLite and it's working fine on my list view.
The problem is when I click a list item from it's supposed to show an image view and few other details. but the image is not showing on the Activity
List View on Main Activity
In the empty space here should be an image of the contacts
UserDBHelper.java
package com.example.arif.contacts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
public class UserDBHelper extends SQLiteOpenHelper {
String TAG = "DEBUG";
private static final String DATABASE_NAME = "USERINFO.DB";
private static final String TABLE_NAME = "ContactTable";
private static final String TABLE_COL_NAME = "NAME";
private static final String TABLE_COL_MOB = "MOB";
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
private static final String TABLE_COL_ID = "ID";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+TABLE_NAME+"("+TABLE_COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TABLE_COL_NAME+" TEXT, "+TABLE_COL_MOB+" TEXT, "+TABLE_COL_EMAIL+" TEXT, "+TABLE_COL_IMG+" blob)" ;
public UserDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("DataBase", "Database created / Opened");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DataBase", "Table Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public boolean AddInfo(String Name, String Mob , String Email, byte[] img )
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put("NAME", Name);
CV.put("MOB", Mob);
CV.put("EMAIL", Email );
CV.put("NewImage", img);
long result = db.insert(TABLE_NAME, null,CV);
Log.e("DataBase", "Add Info Bug");
if(result == -1)
{
return false;
}
else
{
return true;
}
}
public Cursor getInformation()
{
Cursor data;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select * from " + TABLE_NAME;
data = db.rawQuery(query,null);
return data;
}
public String fetch_Name(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_NAME+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_NAME+""));
}
return Str;
}
public String fetch_MOB(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_MOB+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_MOB+""));
}
return Str;
}
public String fetch_Email(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_EMAIL+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_EMAIL+""));
}
return Str;
}
public Bitmap fetch_Img(int i) { /// THIS FUNCTION IS NOT WORKING
byte[] ImgByte;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select "+TABLE_COL_IMG+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
ImgByte = data.getBlob(data.getColumnIndex(TABLE_COL_IMG+""));
Bitmap bitMAP = BitmapFactory.decodeByteArray(ImgByte, 0, ImgByte.length); // Here it's Always Returning Null
if(bitMAP == null)
{
Log.e( TAG, "Bitmap is null :/ ");
}
return bitMAP;
}
return null;
}
}
DetailsViewActivity
package com.example.arif.contacts;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class DetailsOfContacts extends AppCompatActivity {
int Pos;
TextView Name_View, Mob_View, Email_View;
ImageView Image_View;
UserDBHelper userDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_of_contacts);
//---- ---- Intend Bundle ---- ----
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Pos = -1;
if(bundle != null)
{
Pos = bundle.getInt("Position");
}
Toast.makeText(getApplicationContext(), "Position "+ Pos,Toast.LENGTH_SHORT).show();
// ---- ---- Find View ---- ----
Name_View = (TextView) findViewById(R.id.DetName);
Mob_View = (TextView) findViewById(R.id.DetMob);
Email_View = (TextView) findViewById(R.id.DetEmail);
Image_View = (ImageView) findViewById(R.id.DetImg);
/// --- --- DataBase -----
UserDBHelper userDBHelper = new UserDBHelper(getApplicationContext());
Name_View.setText(userDBHelper.fetch_Name(Pos+1)); // Working Fine
Mob_View.setText(userDBHelper.fetch_MOB(Pos+1));// Working Fine
Email_View.setText(userDBHelper.fetch_Email(Pos+1));// Working Fine
Image_View.setImageBitmap(userDBHelper.fetch_Img(Pos+1)); // it's Not showing The image in activity
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.edit_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id ;
id = item.getItemId();
if(id == R.id.EditButt)
{
Toast.makeText(getApplicationContext(),"Edit Button Clicked", Toast.LENGTH_SHORT).show();
Intent I = new Intent(DetailsOfContacts.this, EditActivity.class);
startActivity(I);
return true;
}
return super.onOptionsItemSelected(item);
}
}
09-18 09:35:56.866 26144-26144/com.example.arif.contacts E/DEBUG: Bitmap is null :/
Column name of image and email are same
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
Change column name of image.

How to iterate rows in turn in SQLite on android

EDIT ____________________________________________
How my code currently looks, with the same cannot find symbol error.
CompleteSurveyActivity.java
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.app.Dialog;
public class CompleteSurveyActivity extends DashBoardAppActivity
{
Button btnAnswer1, btnAnswer2, btnAnswer3;
LoginDataBaseAdapter DataBaseLink;
EditText editNameComplete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
DataBaseLink = new LoginDataBaseAdapter(CompleteSurveyActivity.this);
DataBaseLink.open();
TextView tv = (TextView) findViewById(R.id.questionnn);
tv.setText(DataBaseLink.getAllQuestions.get(index));
editNameComplete = (EditText) findViewById(R.id.editTextQuestion);
//tv.setText(LoginDataBaseAdapter.getQuestion());
//get refs of buttons
btnAnswer1 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer1.setText(DataBaseLink.getAnswer1());
btnAnswer2 = (Button) findViewById(R.id.buttonAnswer2);
btnAnswer2.setText(DataBaseLink.getAnswer2());
btnAnswer3 = (Button) findViewById(R.id.buttonAnswer3);
btnAnswer3.setText(DataBaseLink.getAnswer3());
}
public void answer1(View V) {
final EditText editNameComplete=(EditText)findViewById(R.id.editNameComplete);
// Set On ClickListener
Button btnAnswer1 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stud
String name = editNameComplete.getText().toString();
DataBaseLink.insertResponse(DataBaseLink.getQuestion(), name, DataBaseLink.getAnswer1());
Toast.makeText(getApplicationContext(), "Response Logged ", Toast.LENGTH_LONG).show();
index++;
}
});
}
public void answer2(View V) {
// Set On ClickListener
Button btnAnswer2 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stud
String name = editNameComplete.getText().toString();
DataBaseLink.insertResponse(DataBaseLink.getQuestion(), name, DataBaseLink.getAnswer2 ());
Toast.makeText(getApplicationContext(), "Response Logged ", Toast.LENGTH_LONG).show();
index++;
}
});
}
public void answer3(View V) {
// Set On ClickListener
Button btnAnswer3 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stud
String name = editNameComplete.getText().toString();
DataBaseLink.insertResponse(DataBaseLink.getQuestion(), name, DataBaseLink.getAnswer3());
Toast.makeText(getApplicationContext(), "Response Logged ", Toast.LENGTH_LONG).show();
index++;
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
DataBaseLink.close();
}
}
And my database adapter
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
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_CREATE1 = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); ";
static final String DATABASE_CREATE2 = "create table "+"QUESTIONS"+
"( " +"ID"+" integer primary key autoincrement," + "QUESTION text,ANSWER1 text,ANSWER2 text,ANSWER3 text); ";
static final String DATABASE_CREATE3 = "create table "+"RESPONSE"+
"( " +"ID"+" integer primary key autoincrement," + "QUESTION text,USER text, ANSWER int); ";
// 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);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
//new try
public void insertQuestion(String question, String answerOne, String answerTwo, String answerThree) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("QUESTION", question);
newValues.put("ANSWER1", answerOne);
newValues.put("ANSWER2", answerTwo);
newValues.put("ANSWER3", answerThree);
// Insert the row into your table
db.insert("QUESTIONS", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public void insertResponse(String question, String user, String answer) {
ContentValues newValues = new ContentValues();
//assign values for each row
newValues.put("QUESTION", question);
newValues.put("USER", user);
newValues.put("ANSWER", answer);
//insert
db.insert("RESPONSE", null, newValues);
}
/** public String getResponse()
{
Cursor cursor=db.query("RESPONSE", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question not exist
{
cursor.close();
return "NO RESPONSES";
}
cursor.moveToFirst();
String response= cursor.getString(cursor.getColumnIndex("QUESTION","USER","ANSWER"));
cursor.close();
return response;
}
*/
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
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;
}
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
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public String getQuestion()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question not exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String question= cursor.getString(cursor.getColumnIndex("QUESTION"));
cursor.close();
return question;
}
public List<String> getAllQuestions(){
List<String> questions = new ArrayList<>();
String query = "SELECT QUESTION FROM QUESTIONS ";
Cursor cursor=db.rawQuery(query, null);
while(cursor.moveToNext()) {
questions.add(cursor.getString(0));
}
cursor.close();
return questions;
}
public String getAnswer1()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question doesnt exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String answer1= cursor.getString(cursor.getColumnIndex("ANSWER1"));
cursor.close();
return answer1;
}
public String getAnswer2()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question doesnt exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String answer2= cursor.getString(cursor.getColumnIndex("ANSWER2"));
cursor.close();
return answer2;
}
public String getAnswer3()
{
Cursor cursor=db.query("QUESTIONS", null, null, null, null, null, null);
if(cursor.getCount()<1) // Question doesnt exist
{
cursor.close();
return "NO QUESTIONS";
}
cursor.moveToFirst();
String answer3= cursor.getString(cursor.getColumnIndex("ANSWER3"));
cursor.close();
return answer3;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
I still do not understand why the code is not recognising the mothod within the database class.
To get all questions from your database you should use this code:
public List<String> getAllQuestions(){
List<String> questions = new ArrayList<>();
String query = "SELECT questions FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
String question;
question = cursor.getString(0);
// Adding question to list
questions.add(question);
}while (cursor.moveToNext());
}
return questions;
}
EDIT:
Your final code in CompleteSurveyActivity.java will be:
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.app.Dialog;
import java.util.ArrayList;
import java.util.List;
public class CompleteSurveyActivity extends DashBoardAppActivity
{
Button btnAnswer1, btnAnswer2, btnAnswer3;
LoginDataBaseAdapter db;
EditText editNameComplete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
db = new LoginDataBaseAdapter(CompleteSurveyActivity.this);
db.open();
editNameComplete = (EditText) findViewById(R.id.editTextQuestion);
TextView tv = (TextView) findViewById(R.id.questionnn);
tv.setText(db.getAllQuestions.get(index));
//get refs of buttons
btnAnswer1 = (Button) findViewById(R.id.buttonAnswer1);
btnAnswer1.setText(db.getAnswer1());
btnAnswer2 = (Button) findViewById(R.id.buttonAnswer2);
btnAnswer2.setText(db.getAnswer2());
btnAnswer3 = (Button) findViewById(R.id.buttonAnswer3);
btnAnswer3.setText(db.getAnswer3());
}

I don't know how to verify if the phone number already exist. I'm just a newbie and i don't know what to do now

I an newbie to android studio and sq lite database, i am developing a login page for an application like the login in gmail. Here i am taking user phone number as primary key.when the user enter his phone number it will redirect to password screen if already exist. I don't know how to checked whether the phone number is already exist or not.
This my code.
PhoneNumber.java
package com.hernaezchristophergmail.projectitrack;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class PhoneNumber extends AppCompatActivity {
EditText Pnum;
Button Con;
UserDBHelper userDBHelper;
SQLiteDatabase sqLiteDatabase;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_number);
Pnum = (EditText) findViewById(R.id.tbPnumber);
Con = (Button) findViewById(R.id.btbCon);
Con.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String pnumber = Pnum.getText().toString().trim();
String storedPassword = UserDBHelper.getSingleEntry(pnumber,sqLiteDatabase);
/* if(pnumber.equals("")||pnumber1.equals("")){
Toast.makeText(PhoneNumber.this, "Please", Toast.LENGTH_LONG).show();
return;
}*/
if(!pnumber.equals(storedPassword)){
Toast.makeText(PhoneNumber.this, "Invalid Login details", Toast.LENGTH_LONG).show();
return;
}
else{
Intent intent = new Intent(PhoneNumber.this,PasswordScreen.class);
startActivity(intent);
}
}
});
}
/* public void add(View view){
String pnumber = Pnum.getText().toString();
Intent intent = new Intent(PhoneNumber.this, PasswordScreen.class);
startActivity(intent);
}
*/
public void create(View view) {
Intent intent = new Intent(PhoneNumber.this, SignUp.class);
startActivity(intent);
}
#Override
public void onBackPressed(){
}
}
UserDBHelper.java
package com.hernaezchristophergmail.projectitrack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Christopher on 4/26/2016.
*/
public class UserDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ITRACK_USER.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATEINFO_QUERY=
"CREATE TABLE "+ UserContact.UserInformation.TABLE_NAME+"("+ UserContact.UserInformation.User_Password+" TEXT," +
UserContact.UserInformation.User_PhoneNumber+" TEXT," + UserContact.UserInformation.User_Firstame+" TEXT," + UserContact.UserInformation.User_LastName+" TEXT);";
public UserDBHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS","DATABASE CREATED / OPENED ...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATEINFO_QUERY);
Log.e("DATABASE OPERATION", "TABLE CREATED ...");
}
public void saveInfo(String first,String last,String pnum, String pass, SQLiteDatabase db){
ContentValues contentvalues = new ContentValues();
contentvalues.put(UserContact.UserInformation.User_Firstame,first);
contentvalues.put(UserContact.UserInformation.User_LastName,last);
contentvalues.put(UserContact.UserInformation.User_PhoneNumber,pnum);
contentvalues.put(UserContact.UserInformation.User_Password,pass);
db.insert(UserContact.UserInformation.TABLE_NAME, null, contentvalues);
Log.e ("Database Operation", "one row inserted . . .");
}
public static String getSingleEntry(String pnum, SQLiteDatabase sqLiteDatabase) {
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, " User_PhoneNumber=?",
new String[] { pnum }, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String phonenum = cursor.getString(cursor.getColumnIndex("password"));
cursor.close();
return phonenum;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
UserContact.java
public class UserContact {
public static abstract class UserInformation{
public static final String TABLE_NAME = "info";
public static final String User_Password= "password";
public static final String User_LastName = "last_name";
public static final String User_Firstame = "first_name";
public static final String User_PhoneNumber = "phone_number";
public static final String PHOTOID = "photo_id";
}
}
What is the Error?
Also, please look into this.
public static String getSingleEntry(String pnum, SQLiteDatabase sqLiteDatabase) {
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, " User_PhoneNumber=?",
new String[] { pnum }, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String phonenum = cursor.getString(cursor.getColumnIndex("password"));
cursor.close();
return phonenum; //RETURN YES / NO if exist not the actual password for security purpose.
}
if(!pnumber.equals(storedPassword)){ //ALSO HERE, return YES/NO if exist or new, not the actual password.
Toast.makeText(PhoneNumber.this, "Invalid Login details", Toast.LENGTH_LONG).show();
return;
}
The below method will return the name for the given number. By this way you can trigger whether the number is available or not. Returns true if the number is there else false.
public Boolean numberExists(Context context, String phoneNumber) {
String contactName = null;
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);
try {
if (cursor != null) {
if (cursor.moveToFirst()) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return false;
}
Errors in query
1. Wrong column name User_PhoneNumber never exists in your table. Write query as below
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, UserContact.UserInformation.User_PhoneNumber+"=?",
new String[] { pnum }, null, null, null);
and
2. Wrong column name :) you are reading password instead of phone number.. write
String phonenum = cursor.getString(cursor.getColumnIndex(UserContact.UserInformation.User_PhoneNumber));
instead of
String phonenum = cursor.getString(cursor.getColumnIndex("password"));

Android Deleting Row from SQLITE

I'm currently having trouble deleting one row when user long presses on an item in listview. I am able to only delete one row at a time which is what I want, but when I delete the first few items it is successful and when I attempt to delete an item with a later id. The id does not get deleted and stays. I need help to consistently delete items when ever an item is to be deleted. Thanks.
this is my database helper class
package com.example.health.adapter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.health.dao.ExerciseDAO;
import com.example.health.dao.RecipeDAO;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "HealthDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE recipe ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, " +
"description TEXT )";
db.execSQL(CREATE_RECIPE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS recipe");
this.onCreate(db);
}
//START OF CRUD FOR RECIPE
private static final String TABLE_RECIPE = "recipe";
//column names
private static final String KEY_RID = "id";
private static final String KEY_RTITLE = "title";
private static final String KEY_RDESCRIPTION = "description";
private static final String[] RCOLUMNS = {KEY_RID,KEY_RTITLE,KEY_RDESCRIPTION};
public void addRecipe(RecipeDAO r) {
Log.d("addRecipe", r.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RTITLE, r.getTitle());
values.put(KEY_RDESCRIPTION, r.getDescription());
db.insert(TABLE_RECIPE, null, values);
Log.d("Data Added", r.toString());
db.close();
}
public RecipeDAO getRecipe(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(TABLE_RECIPE, // a. table
RCOLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null);
if (cursor != null)
cursor.moveToFirst();
RecipeDAO r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
Log.d("getRecipe("+id+")", r.toString());
return r;
}
public List<RecipeDAO> getAllRecipe() {
List<RecipeDAO> recipe = new ArrayList<RecipeDAO>();
String query = "SELECT * FROM " + TABLE_RECIPE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
RecipeDAO r = null;
if (cursor.moveToFirst()) {
do {
r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
recipe.add(r);
} while (cursor.moveToNext());
}
Log.d("getAllRecipe()", recipe.toString());
return recipe;
}
public int updateRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", r.getTitle());
values.put("description", r.getDescription());
int i = db.update(TABLE_RECIPE, //table
values, // column/value
KEY_RID+" = ?", // selections
new String[] { String.valueOf(r.getRecipeID()) });
db.close();
return i;
}
public void deleteAllRecipe() {
RecipeDAO r = new RecipeDAO();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE,null,null);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_RECIPE + "'");
db.close();
Log.d("deleteRecipe", r.toString());
}
/*
public void deleteRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE, KEY_RID+ " = ? ", new String[] { String.valueOf(r.getRecipeID()) });
db.close();
}*/
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + "=" + id, null) > 0;
}
//END OF CRUD FOR RECIPE
}
Class for database CRUD operations
package com.example.health.recipe;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.health.adapter.MySQLiteHelper;
import com.example.health.dao.RecipeDAO;
import com.example.health.healthplanner.R;
import java.util.List;
public class Recipes extends Fragment {
MySQLiteHelper db;
Button deleteButton;
ListView lv;
List<RecipeDAO> data;
RecipeDAO r = new RecipeDAO();
public Recipes() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.recipe_fragment, container, false);
db = new MySQLiteHelper(getActivity());
/*
db.addRecipe(new RecipeDAO("Windows", "Bill Gates"));//hardcode test
db.addRecipe(new RecipeDAO("IOS", "Steve Jobs"));//same
db.addRecipe(new RecipeDAO("Android", "Andy Rubin"));//same*/
data = db.getAllRecipe();
final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, data);
lv = (ListView) v.findViewById(R.id.listView2);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
deleteButton = (Button) v.findViewById(R.id.deletebutton);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete");
alertDialog.setMessage("Are you sure you want to delete all data?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.deleteAllRecipe();
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "All data delete", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.show();
/* data = db.getAllRecipe();
for(RecipeDAO re : data) { testing to see if data is in database
String log = "Id: " + re.getRecipeID() + ", Title: " + re.getTitle();
Log.d("Data", log);
}*/
}
});
return v;
}
}
try this
public void delete(String name) {
db.delete(your_table_name, "name= ?", new String[] { name });
}
Please revise this method,
//change code in setOnItemLongClickListener
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
data = db.getAllRecipe();
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, data);
//and call change adapter in listview
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
//this method for delete in sqlite database
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + " =?" , new String[]{id}) > 0;
}

Categories

Resources