Query Database using selected item from drop down spinner - java

I have an app that writes to and deletes from a database. I have a 2 spinners that are generated from 2 different columns in that database. I want to run a query for all records matching the selected item from the given drop down spinner. As of right now everything works fine however when I select an item from the drop down, nothing happens. I know I'm missing something just not sure what or where. Please help
Here is my Dbhelper.Java
package com.gamingbrothers.pat.passwordencrypter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//table structure
public class Dbhelper extends SQLiteOpenHelper {
public static final String DB_NAME = "LogInInfo.db";
public static final String TABLE_NAME = "LogInInfo_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "USER_NAME";
public static final String COL_3 = "USER_PASSWORD";
public static final String COL_4 = "APPLICATION";
public static final String COL_5 = "CUSTOMER";
public Dbhelper(Context context) {
super(context, DB_NAME, null, 1);
}
c.close();
return notes_array;
}
#Override
public void onCreate (SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"USER_NAME TEXT,USER_PASSWORD TEXT," +
"APPLICATION TEXT,CUSTOMER TEXT)");
}
//Query Database with item selected from drop down
public Cursor getChoiceData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("select * from LogInInfo_table where CUSTOMER = ?",null);
return result;
}
//Gather Data
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("select * from LogInInfo_table",null);
return result;
}
//getting customers for drop down
public List<String> getAllCustomers(){
List<String> customers = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToPosition(0)) {
do {
customers.add(cursor.getString(4));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning customers
return customers;
}
//getting apps for drop down
public List<String> getAllApps(){
List<String> apps = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToPosition(0)) {
do {
apps.add(cursor.getString(3));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning apps
return apps;
}
//creating update data function
public boolean updateData(String ID,String User_Name,String Password,String Application,String Customer){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,ID);
contentValues.put(COL_2,User_Name);
contentValues.put(COL_3,Password);
contentValues.put(COL_4, Application);
contentValues.put(COL_5,Customer);
db.update(TABLE_NAME,contentValues, "ID = ?",new String[] {ID});
return true;
}
//deleting data
public Integer deleteData (String ID){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[]{ID});
}
}
Here is my MainActivity.Java
package com.gamingbrothers.pat.passwordencrypter;
//Created by Pat 8/6/15
import android.app.AlertDialog;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Dbhelper myDB;
Button btnAdd;
Button btnDelete;
Button btnView;
Button btnUpdate;
Spinner spinner;
Spinner spinner2;
String itemSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new Dbhelper(this);
//initializing objects
editUserName = (EditText) findViewById(R.id.editText_user);
editPassword = (EditText) findViewById(R.id.editText_pass);
editApplication = (EditText) findViewById(R.id.editText_app);
editID = (EditText) findViewById(R.id.editText_id);
editCustomer = (EditText) findViewById(R.id.editText_customer);
btnAdd = (Button) findViewById(R.id.button_Add);
btnDelete = (Button) findViewById(R.id.button_Delete);
btnView = (Button) findViewById(R.id.button_View);
btnUpdate = (Button) findViewById(R.id.button_update);
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
AddData();
viewAll();
UpdateData();
DeleteData();
loadSpinnerData();
loadSpinner2Data();
}
public void loadSpinner2Data() {
//db handler
Dbhelper db2 = new Dbhelper(getApplicationContext());
//Spinner drop elem.
List<String> apps = db2.getAllApps();
//Create adapter for spinner
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, apps);
// Drop down layout style - list view with radio button
dataAdapter2
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//attaching data adapter
spinner2.setAdapter(dataAdapter2);
}
private void loadSpinnerData() {
// database handler
Dbhelper db = new Dbhelper(getApplicationContext());
// Spinner Drop down elements
List<String> customers = db.getAllCustomers();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, customers);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public void DeleteData() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deletedRows = myDB.deleteData(editID.getText().toString());
if(deletedRows >0)
Toast.makeText(MainActivity.this, "Data Deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Deleted", Toast.LENGTH_LONG).show();
}
}
);
}
//creating update data function
public void UpdateData() {
btnUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdated = myDB.updateData(editID.getText().toString(),
editUserName.getText().toString(),
editPassword.getText().toString(),
editApplication.getText().toString(),
editCustomer.getText().toString());
//Parse update completion
if (isUpdated == true)
Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Updated", Toast.LENGTH_LONG).show();
}
});
}
//add data to database
public void AddData() {
btnAdd.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(editUserName.getText().toString(),
editPassword.getText().toString(),
editApplication.getText().toString(),
editCustomer.getText().toString());
//parse add completion
if (isInserted == true)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
});
}
//Get results from database when button is clicked
public void viewAll() {
btnView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = myDB.getAllData();
//Check if database is empty
if (result.getCount() == 0) {
//Show Message
showMessage("Error", "No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()) {
buffer.append("ID:" + result.getString(0) + "\n");
buffer.append("User Name:" + result.getString(1) + "\n");
buffer.append("Password:" + result.getString(2) + "\n");
buffer.append("App:" + result.getString(3) + "\n");
buffer.append("Customer:" + result.getString(4) + "\n\n");
}
//Show all data
showMessage("Data", buffer.toString());
}
}
);
}
//show data
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();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String label = parent.getItemAtPosition(position).toString();
myDB.getChoiceData().toString();
Toast.makeText(parent.getContext(), "Here is your information: "+ label,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
If you need me to post my XML just ask, but I didn't think it was neccessary and I didn't post my logcat because it doesn't give me an error.

From the code you posted you seem to be missing the selected item listener, add the following, for example, to your onCreate:
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);

Related

How to compare data from different activities using SQLite on Android Studio

//MAIN ACTIVITY
package com.example.saosteste2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BancoDados_Registo dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new BancoDados_Registo(MainActivity.this);
TextView email = (TextView) findViewById(R.id.id_email);
TextView password = (TextView) findViewById(R.id.id_password);
Button BLogIn = (Button) findViewById(R.id.id_Blogin);
Button conta_btn = (Button) findViewById(R.id.id_criarconta);
//testing email e password
BLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ????
}
});
conta_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, registo.class);
startActivity(intent);
}
});
}
}
//-----------------------SECOND ACTIVITY WITH THE DATABASE-----------------------//
//BANCODADOS_REGISTOS
package com.example.saosteste2;
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 android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class BancoDados_Registo extends SQLiteOpenHelper {
public BancoDados_Registo(Context context) {
super(context, "REGISTOS.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create Table Registos(nome TEXT primary key, email TEXT, password TEXT, morada TEXT, telemovel TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop Table if exists Registos");
}
// INSERT DATA
public Boolean insertuserdata(String nome, String email, String password, String morada, String telemovel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
long result=db.insert("Registos", null, contentValues);
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}
//UPDATE DATA
public Boolean updateuserdata(String nome, String email, String password, String morada, String telemovel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
Cursor cursor = db.rawQuery("Select * from Registos where nome = ?", new String[] {nome});
if (cursor.getCount()>0){ //se o cursor tiver dados
long result=db.update("Registos", contentValues, "nome=?", new String [] {nome});
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}else {
return false;
}
}
//DELETEDATA
public Boolean deleteuserdata(String nome){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Registos where nome = ?", new String[] {nome});
if (cursor.getCount()>0){ //se o cursor tiver dados
long result=db.delete("Registos", "nome=?", new String [] {nome});
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}else {
return false;
}
}
public Cursor getuserdata(String email, String password){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Registos", null);
return cursor;
}
Hi everyone!
I'm new in the world of Java and Android Studio. I don't know how to transmit data from the databse created in the second Activity to the first one. I need help checking if the email and password that the user puts on the first Activity (MainActivity) already exists in the database I created in the second Activity (BancoDados_Registo). Thank you for your attention in advance!
Here's a working example (but one that uses the deprecated startActivityForresult) based upon your code.
You should really look at https://developer.android.com/training/basics/intents/result for the non-deprecated way though.
When the App is started MainActivity displays the login/registo buttons:-
note hints added for email and password just to show where the TextViews.
Clicking the Registo button starts the Registo activity with empty EditTexts
for the nome,email,password morada and telemovel and a button to register (add) :-
Entering suitable data e.g. :-
And then clicking the Registo button, adds the user (if not a duplicate) and returns to MainActivity passing the nome and rowid which is then used to complete the email and password TextViews (not that you would do this, but rather to show extracting the data from the database) :-
The code:-
MainActivty
public class MainActivity extends AppCompatActivity {
private BancoDados_Registo dbManager;
TextView email; //<<<<< MOVED for full scope
TextView password; //<<<<< Moved for full scope
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new BancoDados_Registo(MainActivity.this);
email = (TextView) findViewById(R.id.id_email);
password = (TextView) findViewById(R.id.id_password);
Button BLogIn = (Button) findViewById(R.id.id_Blogin);
Button conta_btn = (Button) findViewById(R.id.id_criarconta);
//testing email e password
BLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ????
}
});
conta_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Registo.class);
startActivityForResult(intent,Registo.REGISTO_RESULTSCODE); // deprecated but works
}
});
}
#SuppressLint("Range")
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Registo.REGISTO_RESULTSCODE && resultCode == RESULT_OK) {
Toast.makeText(this,"Registered with ID " + data.getLongExtra(Registo.INTENTEXTRAKEY_REGISTOID,-1),Toast.LENGTH_LONG).show();
if (data.getLongExtra(Registo.INTENTEXTRAKEY_REGISTOID,-1) > 0) {
Cursor csr = dbManager.getUserDataByNome(data.getStringExtra(Registo.INTENTEXTRAKEY_REGISTONOME));
if (csr.moveToFirst()) {
password.setText(csr.getString(csr.getColumnIndex("password")));
email.setText(csr.getString(csr.getColumnIndex("email")));
}
}
}
}
}
BancoDados_Registo (changed/added methods only) :-
// INSERT DATA <<<<< CHANGED (to return rowid which can be more useful as it can be used to get the row)
public Long insertuserdata(String nome, String email, String password, String morada, String telemovel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
return db.insert("Registos", null, contentValues);
}
/* ADDED to get User just by nome */
public Cursor getUserDataByNome(String nome) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query("Registos",null,"nome=?",new String[]{nome},null,null,null);
}
Registo activity (note capitalised) :-
public class Registo extends AppCompatActivity {
private BancoDados_Registo dbManager;
public static final int REGISTO_REQUESTCODE = 98; //<<<
public static final String INTENTEXTRAKEY_REGISTOID = "ie_registo_id";
public static final String INTENTEXTRAKEY_REGISTONOME = "ie_registo_nome";
EditText nome;
EditText email;
EditText password;
EditText morada;
EditText telemovel;
Button registro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registo);
nome = this.findViewById(R.id.id_nome);
email = this.findViewById(R.id.id_email);
password = this.findViewById(R.id.id_password);
morada = this.findViewById(R.id.id_morada);
telemovel = this.findViewById(R.id.id_telemovel);
registro = (Button) findViewById(R.id.id_registro);
dbManager = new BancoDados_Registo(this);
registro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* Only insert in valid data - else Toast incomplete*/
if (
email.getText().length() > 0
&& password.getText().length() >= 8
&& morada.getText().length() > 0
&& telemovel.getText().length() > 0
) {
Long rowid = dbManager.insertuserdata(nome.getText().toString(),email.getText().toString(),password.getText().toString(),morada.getText().toString(),telemovel.getText().toString());
if (rowid > 0) {
Toast.makeText(view.getContext(),"Registered",Toast.LENGTH_LONG).show();
Intent resultIntent = new Intent();
resultIntent.putExtra(INTENTEXTRAKEY_REGISTOID,rowid);
resultIntent.putExtra(INTENTEXTRAKEY_REGISTONOME,nome.getText().toString());
setResult(RESULT_OK,resultIntent);
finish();
} else {
Toast.makeText(view.getContext(),"Not Registered (duplicate)",Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(view.getContext(),"Not Registered Incomplete input fields!!",Toast.LENGTH_LONG).show();
}
}
});
}
}

listView cannot update dynamically

I am using sqlite for database. When i add data in ListView. Data added correctly. But when i close app then updated list lost data which i added before. With code Statically added data shows but using app when create reminder then data added successfully in ListView. But when i restart app new data lost after restart app I mean creating reminder delete automatically after restart app.
Even I delete reminders which added by code after restart app all deleted reminders showing in ListView again. But Dynamically added data not show.
Please help me to solve this problem.
Here is my Activity code
RemindersActivity.java
package com.example.remindersapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
public class RemindersActivity extends AppCompatActivity {
private ListView mlistView;
private RemindersDbAdapter remindersDbAdapter;
private ReminderSimpleCursorAdapter reminderSimpleCursorAdapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminders);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.ic_launcher_reminder);
mlistView = (ListView) findViewById(R.id.reminder_listView);
// mlistView.setDivider(null);
remindersDbAdapter = new RemindersDbAdapter(this);
remindersDbAdapter.open();
if (savedInstanceState == null) {
//clear all data
remindersDbAdapter.deleteAllReminders();
//add some data
insertSomeReminders();
}
Cursor cursor = remindersDbAdapter.fetchAllReminders();
//from columns defined in the db
String[] from = new String[]{remindersDbAdapter.COL_CONTENT};
//to the ids of views in the layout
int[] to = new int[]{R.id.row_text};
reminderSimpleCursorAdapter = new ReminderSimpleCursorAdapter(
RemindersActivity.this,
//the layout of the row
R.layout.reminders_row,
cursor,
//from columns defined in the db
from,
//to the ids of views in the layout
to,
//flag - not used
0);
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
// this,
// R.layout.reminders_row,
// R.id.row_text,
// new String[]{"fisrt record", "second record", "third record"
// , "fourth record", "fifth record"});
mlistView.setAdapter(reminderSimpleCursorAdapter);
//Adapter is a
//special Java class defined as part of the Android SDK that functions as the Controller in
//the Model-View-Controller relationship
//when we click an individual item in the listview
mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int masterposition, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(RemindersActivity.this);
ListView modeListView = new ListView(RemindersActivity.this);
String[] modes = new String[]{"Edit Reminder", "Delete Reminder", "Scheduled Reminder"};
ArrayAdapter<String> modeAdapter = new ArrayAdapter<>(RemindersActivity.this,
android.R.layout.simple_list_item_1, android.R.id.text1, modes);
modeListView.setAdapter(modeAdapter);
builder.setView(modeListView);
final Dialog dialog = builder.create();
dialog.show();
modeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//edit reminder
// if (position == 0) {
// Toast.makeText(RemindersActivity.this, "edit" + masterposition, Toast.LENGTH_SHORT).show();
// } else {
// Toast.makeText(RemindersActivity.this, "delete" + masterposition, Toast.LENGTH_SHORT).show();
// }
// dialog.dismiss();
int nId = getIdFromPosition(masterposition);
final Reminder reminder = remindersDbAdapter.fetchReminderById(nId);
if (position == 0) {
fireCustomDialog(reminder);
//delete reminder
} else if (position == 1) {
remindersDbAdapter.deleteReminderById(getIdFromPosition(masterposition));
reminderSimpleCursorAdapter.changeCursor(remindersDbAdapter.fetchAllReminders());
}
else {
// final Date today = new Date();
// new TimePickerDialog(RemindersActivity.this,null,today.getHours(),today.getMinutes(),
// false).show();
TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Date alarm = new Date(today.getYear(), today.getMonth(), today.getDate(), hourOfDay, minute);
// scheduleReminder(alarm.getTime(), reminder.getmContent());
//This creates a listener for the time picker dialog box. Inside this listener, you use today’s
//date as the base time for your alarm. You then include the hour and minute chosen from
//the dialog box to create the alarm date variable for your reminder. You use both the alarm
//time and the reminder’s content in a new scheduleReminder() method
//Fix the deprecation warnings
final Calendar alarmTime = Calendar.getInstance();
alarmTime.set(Calendar.HOUR, hourOfDay);
alarmTime.set(Calendar.MINUTE, minute);
scheduleReminder(alarmTime.getTimeInMillis(), reminder.getmContent());
}
};
final Calendar today = Calendar.getInstance();
// new TimePickerDialog(RemindersActivity.this, null,
// today.get(Calendar.HOUR), today.get(Calendar.MINUTE), false).show();
//the following change to connect the
//listener that invokes the BroadcastReceiver to the TimePickerDialog
new TimePickerDialog(RemindersActivity.this, listener,
today.get(Calendar.HOUR), today.get(Calendar.MINUTE), false).show();
}
dialog.dismiss();
}
});
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mlistView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mlistView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
//The preceding logic defines a MultiChoiceModeListener and attaches it to the ListView.
//Whenever you long-press an item in the ListView, the runtime invokes the onCreateActionMode()
//method on the MultiChoiceModeListener. If the method returns with the boolean true value,
//multichoice action mode is entered.
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.cam_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_reminder:
for (int nC = reminderSimpleCursorAdapter.getCount() - 1; nC >= 0; nC--) {
if (mlistView.isItemChecked(nC)) {
remindersDbAdapter.deleteReminderById(getIdFromPosition(nC));
}
}
mode.finish();
reminderSimpleCursorAdapter.changeCursor(remindersDbAdapter.fetchAllReminders());
return true;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
}
private void scheduleReminder(long time, String getmContent) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, ReminderAlarmReceiver.class);
alarmIntent.putExtra(ReminderAlarmReceiver.REMINDER_TEXT, getmContent);
PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, broadcast);
}
private int getIdFromPosition(int nC) {
return (int) reminderSimpleCursorAdapter.getItemId(nC);
}
private void insertSomeReminders() {
remindersDbAdapter.createReminder("Learn android Development", true);
remindersDbAdapter.createReminder("data Mining Assignment", false);
remindersDbAdapter.createReminder("Networking Assignment", false);
remindersDbAdapter.createReminder("English Assignment", true);
// //There are several calls to the createReminder() method, each taking a String value
//with the reminder text and a boolean value flagging the reminder as important. We set
//a few values to true to provide a good visual effect.
}
private void fireCustomDialog(final Reminder reminder) {
// custom dialog
Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_custom);
TextView titleView = (TextView) dialog.findViewById(R.id.custom_title);
final EditText editCustom = (EditText) dialog.findViewById(R.id.custom_edit_reminder);
Button commitButton = (Button) dialog.findViewById(R.id.custom_button_commit);
final CheckBox checkBox = (CheckBox) dialog.findViewById(R.id.custom_check_box);
// checkBox.setChecked(true);
LinearLayout rootLayout = (LinearLayout) dialog.findViewById(R.id.custom_root_layout);
final boolean isEditOperation = (reminder != null);
//this is for an edit
if (isEditOperation) {
titleView.setText("Edit Reminder");
checkBox.setChecked(reminder.getImportant() == 1);
editCustom.setText(reminder.getmContent());
rootLayout.setBackgroundColor(getResources().getColor(R.color.check_box));
}
commitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String reminderText = editCustom.getText().toString();
if (isEditOperation) {
Reminder reminderEdit = new Reminder(reminder.getmId(),
reminderText, checkBox.isChecked() ? 1 : 0);
remindersDbAdapter.updateReminder(reminderEdit);
} else {
remindersDbAdapter.createReminder(reminderText, checkBox.isChecked());
}
reminderSimpleCursorAdapter.changeCursor(remindersDbAdapter.fetchAllReminders());
dialog.dismiss();
}
});
Button buttonCancel = (Button) dialog.findViewById(R.id.custom_button_cancel);
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.reminder_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_new:
//create new reminder
Log.d(getLocalClassName(), "create new reminder");
fireCustomDialog(null);
return true;
case R.id.action_exit:
finish();
return true;
case R.id.action_about:
fireAboutDialog();
return true;
default:
return false;
}
}
private void fireAboutDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_about);
dialog.show();
}
}
RemindersDbAdapter.java
package com.example.remindersapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class RemindersDbAdapter {
//these are the column names
public static final String COL_ID = "_id";
public static final String COL_CONTENT = "content" ;
public static final String COL_IMPORTANT = "important";
//these are the corresponding indices
private static final int INDEX_ID = 0;
private static final int INDEX_CONTENT = INDEX_ID + 1;
private static final int INDEX_IMPORTANT = INDEX_ID + 2;
//used for logging
private static final String TAG = "RemindersDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "dba_reminder";
private static final String TABLE_NAME = "table_reminder";
private static final int DATABASE_VERSION = 3;
private final Context mCtx;
////SQL statement used to create the database
private static final String DATABSE_CREATE = "CREATE TABLE if not exists " + TABLE_NAME + " ( " +
COL_ID + " INTEGER PRIMARY KEY autoincrement, " +
COL_CONTENT + " TEXT, " +
COL_IMPORTANT + " INTEGER );";
public RemindersDbAdapter(Context Ctx) {
//The constructor saves an instance of Context, which is passed to DatabaseHelper
this.mCtx = Ctx;
}
//The open()
//method initializes the helper and uses it to get an instance of the database,
public void open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
}
//the close()
//method uses the helper to close the database.
public void close() throws SQLException {
if (mDbHelper != null) {
mDbHelper.close();
}
}
//CREATE
//note that the id will be created for you automatically
public void createReminder(String name, boolean important) {
ContentValues values = new ContentValues();
values.put(COL_CONTENT, name);
values.put(COL_IMPORTANT, important ? 1 : 0);
mDb.insert(TABLE_NAME, null, values);
}
////overloaded to take a reminder
public long createReminder(Reminder reminder) {
ContentValues values = new ContentValues();
values.put(COL_CONTENT, reminder.getmContent()); //Contact name
values.put(COL_IMPORTANT, reminder.getImportant()); //Contact phone number
//// Inserting Row
return mDb.insert(TABLE_NAME, null, values);
}
//READ
public Reminder fetchReminderById(int id) {
Cursor cursor = mDb.query(TABLE_NAME,
new String[]{COL_ID, COL_CONTENT, COL_IMPORTANT},
COL_ID + " =? ",
new String[]{String.valueOf(id)},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
return new Reminder(
cursor.getInt(INDEX_ID),
cursor.getString(INDEX_CONTENT),
cursor.getInt(INDEX_IMPORTANT));
}
public Cursor fetchAllReminders() {
Cursor mcursor = mDb.query(TABLE_NAME, new String[]{COL_ID, COL_CONTENT, COL_IMPORTANT},
null, null, null, null, null);
if (mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
//UPDATE
public void updateReminder(Reminder reminder) {
ContentValues values = new ContentValues();
values.put(COL_CONTENT, reminder.getmContent());
values.put(COL_IMPORTANT, reminder.getImportant());
mDb.update(TABLE_NAME, values, COL_ID + " =? ", new String[]{String.valueOf(reminder.getmId())});
}
//DELETE
public void deleteReminderById(int id){
mDb.delete(TABLE_NAME,COL_ID + "=?", new String[]{String.valueOf(id)});
}
public void deleteAllReminders(){
mDb.delete(TABLE_NAME,null,null);
}
//sqlite open helper
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABSE_CREATE);
db.execSQL(DATABSE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + "to " + newVersion + ",which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
onCreate(db);
}
}
}
ReminderSimpleCursorAdapter.java
package com.example.remindersapp;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import androidx.recyclerview.widget.RecyclerView;
public class ReminderSimpleCursorAdapter extends SimpleCursorAdapter {
public ReminderSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int i) {
super(context, layout, c, from, to,i);
}
////to use a viewholder, you must override the following two methods and define a ViewHolder class
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return super.newView(context, cursor, parent);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
ViewHolder holder=(ViewHolder)view.getTag();
if (holder == null){
holder=new ViewHolder();
holder.colImp=cursor.getColumnIndexOrThrow(RemindersDbAdapter.COL_IMPORTANT);
holder.listTab=view.findViewById(R.id.row_tab);
view.setTag(holder);
}
if (cursor.getInt(holder.colImp) > 0){
holder.listTab.setBackgroundColor(context.getResources().getColor(R.color.false_result));
}else {
holder.listTab.setBackgroundColor(context.getResources().getColor(R.color.txt_color));
}
}
//Here you see an example of the ViewHolder pattern. This is a well-known Android pattern
//in which a small ViewHolder object is attached as a tag on each view. This object adds
//decoration for View objects in the list by using values from the data source, which in this
//example is the Cursor. The ViewHolder is defined as a static inner class with two instance
//variables, one for the index of the Important table column and one for the row_tab view you
//defined in the layout.
static class ViewHolder{
//store the column index
int colImp;
//store the view
View listTab;
}
}

Populate Android Listview with data extracted from a database

I am a newbie to Android programming.I want to use data inputted into an SQLite database to populate an Android Listview. However, Android keeps highlighting the SimpleCursorAdapter below as error. Can anyone help?
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
Below is the full code:
package com.allmycode.databaseinsertwithlistview;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText GetName,GetPhoneNumber,GetSubject ;
Button Submit ;
String Name, PhoneNumber, Subject ;
Boolean CheckEditTextEmpty ;
String SQLiteQuery;
SQLiteDatabase SQLITEDATABASE;
TextView display;
Cursor cursor;
ListView listView;
//Make these declarations to enable the fetchallitems() method work
public static final String name = "name";
public static final String phone_number = "Phone_number";
public static final String subject = "subject";
private SimpleCursorAdapter dataAdapter;
private static final String demoTable = "demoTable";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);GetName = (EditText)findViewById(R.id.editText1);
GetPhoneNumber = (EditText)findViewById(R.id.editText2);
GetSubject = (EditText)findViewById(R.id.editText3);
listView = (ListView) findViewById(R.id.ListVw);
//display= (TextView) findViewById(R.id.textView) ;
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DBCreate();
SubmitData2SQLiteDB();
displayListView();
}
});
}
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("DemoDataBase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS demoTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name String, phone_number String, subject String);");
}
public void SubmitData2SQLiteDB(){
Name = GetName.getText().toString();
PhoneNumber = GetPhoneNumber.getText().toString();
Subject = GetSubject.getText().toString();
CheckEditTextIsEmptyOrNot( Name,PhoneNumber, Subject);
if(CheckEditTextEmpty == true)
{
SQLiteQuery = "INSERT INTO demoTable (name,phone_number,subject) VALUES('"+Name+"', '"+PhoneNumber+"', '"+Subject+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(MainActivity.this,"Data Submit Successfully", Toast.LENGTH_LONG).show();
ClearEditTextAfterDoneTask();
// addtoTextView();
}
else {
Toast.makeText(MainActivity.this,"Please Fill All the Fields", Toast.LENGTH_LONG).show();
}
}
public void CheckEditTextIsEmptyOrNot(String Name,String PhoneNumber, String subject ){
if(TextUtils.isEmpty(Name) || TextUtils.isEmpty(PhoneNumber) || TextUtils.isEmpty(Subject)){
CheckEditTextEmpty = false ;
}
else {
CheckEditTextEmpty = true ;
}
}
public void ClearEditTextAfterDoneTask(){
GetName.getText().clear();
GetPhoneNumber.getText().clear();
GetSubject.getText().clear();
}
/* void addtoTextView(){
cursor= SQLITEDATABASE.rawQuery("SELECT * FROM demoTable;",null);
if (cursor !=null && cursor.moveToFirst()){
String name;
do{
name = cursor.getString(0);
String pnone_number=cursor.getString(1);
String test2=cursor.getString(2);
String test3 = cursor.getString(3);
display.append(name + " " + pnone_number +" "+test2 +" "+ test3 +"\n");
} while (cursor.moveToNext());
}
display.append("-------------\n");
} */
public Cursor fetchAllItems() {
Cursor mCursor = SQLITEDATABASE.query(this.demoTable, new String[] {this.name,
this.phone_number, this.subject},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
private void displayListView()
{
Cursor cursor= fetchAllItems();
//The desired columns to be bound
String[] columns=new String[]{
this.name,
this.phone_number,
this.subject
};
//The XML defined views which the data will be bound to
int[] to = new int[] {
R.id.name,
R.id.phone_number,
R.id.subject,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
}

How do I save a getIntent() value in a SQLite database?

I'm new to Android development.
Recently I wanted to make an app which First Activity calculates a number and sends it through an intent to the Second activity.
So far so good.
But in this stage I'm facing some problem.
That is, when I receive the intent via getIntent(), it is OK.
But I don't know how do I save the getIntent() value in a SQLite database?
Hope you guys will help me to fix this problem.
This is my First Activity
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DrinkActivity extends AppCompatActivity {
// Remove the below line after defining your own ad unit ID.
//private static final String TOAST_TEXT = "Test ads are being shown. "
// + "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
//this is how many count
int a = 0;
//this is hoq much
int b = 0;
//this is button who is send information and go next page
Button B1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
// Load an ad into the AdMob banner view.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
// Toasts the test ad message on the screen. Remove this after defining your own ad unit ID.
//Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();
B1 = (Button) findViewById(R.id.gonextPage);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DrinkActivity.this,ScrollingActivity.class);
int x = a ;
int y = b;
int z = a * b;
intent.putExtra("drinkhowmany",x);
intent.putExtra("drinkhowmuch",y);
intent.putExtra("drinktotal",z);
startActivity(intent);
}
});
}
//this method count down how many drink plus calculation
public void howmanyPlusButton(View view){
if (a == 100){
return;
}
a = a + 1;
displayHowMany(a);
}
//this method count down how many drink minus calculation
public void howmanyMinusButton(View view){
if (a == -0){
return;
}
a = a - 1;
displayHowMany(a);
}
//this method count down how much price drink plus calculation
public void howmuchPlusButton(View view){
if (b == 100){
return;
}
b = b +1;
displayHowMuch(b);
}
//this method count down how much price minus drink calculation
public void howmuchMinusButton(View view){
if (b == -0){
return;
}
b = b -1;
displayHowMuch(b);
}
//this text show user how many digit
private void displayHowMany(int i){
TextView textView = (TextView) findViewById(R.id.howMany);
textView.setText(""+i);
}
//this text show user how much price digit
private void displayHowMuch(int i){
TextView textView = (TextView) findViewById(R.id.howMuch);
textView.setText("$"+i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_drink, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my 2nd Activity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ScrollingActivity extends AppCompatActivity {
//drink text working hear
TextView drinkhowmany,drinkhowmuch,drinktotal;
//data save button and data delete button
Button save,delete;
//database
SQLiteDataBase sqLiteDataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
Intent intent = new Intent(ScrollingActivity.this,MenuActivity.class);
startActivity(intent);
}
});
//main text working and shoq user preview hear
//database call hear
sqLiteDataBase = new SQLiteDataBase(this);
//this is drink section
//this is show user hoq many drink user order
drinkhowmany = (TextView) findViewById(R.id.drinkHowMany);
drinkhowmany.setText(""+getIntent().getIntExtra("drinkhowmany",0));
//thisis show user how much drink price
drinkhowmuch = (TextView) findViewById(R.id.drinkHowMuch);
drinkhowmuch.setText("$"+getIntent().getIntExtra("drinkhowmuch",0));
//this is show user total drink price
final int drinkTotalInt = +getIntent().getIntExtra("drinktotal",0);
drinktotal = (TextView) findViewById(R.id.drinkTotal);
drinktotal.setText("$"+drinkTotalInt);
//buttton with database
save = (Button) findViewById(R.id.savedataButton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean chaker = saveDataFile.addtoTable(`what i need to write hear also ?` );
if (chaker == true){
Toast.makeText(getBaseContext(),"SAVE YOUR DATA",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getBaseContext(),"Your Data Not Save",Toast.LENGTH_SHORT).show();
}
}
});
}
}
SQLITE ACTIVITY
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by AIB Nihan on 10/4/2016.
*/
public class SQLiteDataBase extends SQLiteOpenHelper {
//this is the like box of information this is the box of which user input ther value
private static final String DATABASE_NAME = "mydatabase.db";
private static final String TABLE_NAME = "mytable";
private static final String DRINK_PRICE = "drink";
public SQLiteDataBase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String query;
query = "CREATE TABLE " +TABLE_NAME+ "(" +CIG_PRICE+ " INTEGER, "+ ")";
sqLiteDatabase.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP FILE IF EXITS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
//int coffee,,int drink,int food,int other
public boolean addtotable(int cig){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(DRINK_PRICE,drink);
long chaker = sqLiteDatabase.insert(TABLE_NAME,null,contentValues);
if (chaker == 1){
return false;
}else {
return true;
}
}
public Cursor display(){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor res = sqLiteDatabase.rawQuery("SELECT * FORM" + TABLE_NAME,null);
return res;
}
}
As per your code , You can pass integer to addtotable() by passing drinkTotalInt or some integer value.
e.g
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { boolean chaker =
saveDataFile.addtoTable(drinkTotalIn); if (chaker == true){
Toast.makeText(getBaseContext(),"SAVE YOUR
DATA",Toast.LENGTH_SHORT).show(); }else {
Toast.makeText(getBaseContext(),"Your Data Not
Save",Toast.LENGTH_SHORT).show();
}
}
});
and in addtable() insert passing value as below,
contentValues.put(DRINK_PRICE, [insert data]);
If You want to insert intent into sqlite, change sqlite schema as:
query = "CREATE TABLE " +TABLE_NAME+ "(" +CIG_PRICE+ " **TEXT**, "+ ")";
then, pass intent as argument to addtable().
e.g ,
addtable(getIntent());
In addtable():
public boolean addtotable(Intent intent){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues contentValues = new ContentValues();
String intentDescription = intent.toUri(0);
contentValues.put(DRINK_PRICE,intentDescription);
long chaker = sqLiteDatabase.insert(TABLE_NAME,null,contentValues);
if (chaker == 1){
return false;
}else {
return true;
}
}
Get intent from sqlite:
String intentDescription = cursor.getString(intentIndex);
Intent intent = Intent.parseUri(intentDescription, 0);
Now you can parse intent to get all values.
Edit:
Getting intent from sqlite in more details:
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
Cursor cursor = sqLiteDatabase .rawQuery("select * from [table-name] ");
if (cursor.moveToFirst()) {
do {
String intentDescription = cursor.getString(0); // getting intent from sqlite at index 0
Intent intent = Intent.parseUri(intentDescription, 0);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
if(db!=null)
{
db.close();
}
You will need to use ContentValues.
I would recommend using this tutorial:
https://www.tutorialspoint.com/android/android_sqlite_database.htm

Hashing passwords in Java application

I have a Android application written in Java which utilises an SQLite database.
I want the passwords upon input on the sign up page to generate an MD5 or SHA1 hash which is stored in the database. Which can then be used when logging back into the application.
Can anyone offer any help?
Signup
package com.example.oliver.beckettreg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class SignUp extends Activity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
//if button clicked
public void onSignUpClick(View v) {
if (v.getId() == R.id.Bsignupbutton) {
EditText name = (EditText) findViewById(R.id.TFname);
EditText email = (EditText) findViewById(R.id.TFemail);
EditText uname = (EditText) findViewById(R.id.TFuname);
EditText pass1 = (EditText) findViewById(R.id.TFpass1);
EditText pass2 = (EditText) findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = email.getText().toString();
String unamestr = uname.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
//check passwords match
if(!pass1str.equals(pass2str))
{
//popup msg if fails
Toast pass = Toast.makeText(SignUp.this , "Passwords don't match!" , Toast.LENGTH_SHORT);
pass.show();
}
else
{
//validations for data input
if (name.getText().toString().length() == 0)
{name.setError("Name Required");}
else if (!email.getText().toString().matches("[a-z]{1}\\.[a-z]*[0-9]{4}#student\\.leedsbeckett\\.ac\\.uk"))
{email.setError("Incorrect Email Format");}
else if (!uname.getText().toString().matches("[cC][0-9]{7}"))
{uname.setError("Incorrect ID Format");}
else if (!pass1.getText().toString().matches("(?=.*[\\d])(?=.*[a-z])(?=.*[A-Z]).{8,}"))
{pass1.setError("Incorrect Password Format");}
else{
//insert the details in database
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setUname(unamestr);
c.setPass(pass1str);
helper.insertContact(c);
//popup if data passes validations
Toast pass = Toast.makeText(SignUp.this , "User Registered" , Toast.LENGTH_LONG);
pass.show();
}
}
}
}
public void onButtonClick(View v) {
if (v.getId() == R.id.Blogin2) {
Intent i = new Intent(SignUp.this, com.example.oliver.beckettreg.MainActivity.class);
startActivity(i);
}
}
}
Login
package com.example.oliver.beckettreg;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onButtonClick(View v)
{
//if button clicked
if(v.getId() == R.id.Blogin)
{
//check if passwords match
EditText a = (EditText)findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password))
{
Intent i = new Intent(MainActivity.this, NFC.class);
i.putExtra("Username",str);
startActivity(i);
}
else
{å
Toast temp = Toast.makeText(MainActivity.this , "Username and password don't match!" , Toast.LENGTH_SHORT);
temp.show();
}
}
//sign up button if data passes
if(v.getId() == R.id.Bsignup)
{
Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.SignUp.class);
startActivity(i);
}
if(v.getId() == R.id.Bnfc)
{
Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.AttendanceRegistration.class);
startActivity(i);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Database Helper
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
public class
DatabaseHelper extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "contacts.db";
//Table Names
private static final String REGISTER_TABLE_NAME = "register";
private static final String CONTACTS_TABLE_NAME = "contacts";
//Contacts Column Names
private static final String CONTACTS_COLUMN_ID = "id";
private static final String CONTACTS_COLUMN_NAME = "name";
private static final String CONTACTS_COLUMN_EMAIL = "email";
private static final String CONTACTS_COLUMN_UNAME = "uname";
private static final String CONTACTS_COLUMN_PASS = "pass";
//Register Column Names
private static final String REGISTER_COLUMN_ID = "id";
private static final String REGISTER_COLUMN_SEMINAR = "seminar";
private static final String REGISTER_COLUMN_LECTURE = "lecture";
SQLiteDatabase db;
//Table Create Statements
private static final String CONTACTS_TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"name text not null , email text not null , uname text not null , pass text not null);";
private static final String REGISTER_TABLE_CREATE = "create table register (id integer primary key not null , " +
" time DATETIME DEFAULT CURRENT_TIMESTAMP, seminar text not null , lecture text not null, );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Creating Required Tables
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(REGISTER_TABLE_CREATE);
db.execSQL(CONTACTS_TABLE_CREATE);
this.db = db;
}
public void insertContact(Contact c) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query , null);
int count = cursor.getCount();
values.put(CONTACTS_COLUMN_ID, count);
values.put(CONTACTS_COLUMN_NAME, c.getName());
values.put(CONTACTS_COLUMN_EMAIL, c.getEmail());
values.put(CONTACTS_COLUMN_UNAME, c.getUname());
values.put(CONTACTS_COLUMN_PASS, c.getPass());
db.insert(CONTACTS_TABLE_NAME, null, values);
db.close();
}
public void insertRegister(Register r) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from register";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(REGISTER_COLUMN_ID, count);
values.put(REGISTER_COLUMN_SEMINAR, r.getSeminar());
values.put(REGISTER_COLUMN_LECTURE, r.getLecture());
db.insert(REGISTER_TABLE_NAME, null, values);
db.close();
}
public String searchPass(String uname)
{
db = this.getReadableDatabase();
String query = "select uname, pass from "+CONTACTS_TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
String a, b;
b = "not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(uname))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
//On Upgrade Drop Older Tables
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + REGISTER_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME);
//Create New Tables
this.onCreate(db);
}
}
You can implement this method, which will return the hash as a string.
private String hashMe(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1"); //could also be MD5, SHA-256 etc.
md.reset();
md.update(password.getBytes("UTF-8"));
byte[] resultByte = md.digest();
password = String.format("%01x", new java.math.BigInteger(1, resultByte));
} catch (NoSuchAlgorithmException e) {
//do something.
} catch (UnsupportedEncodingException ex) {
//do something
}
return password;
}
Since you are dealing with passwords, you should also salt the hash, and save them both in your Db.

Categories