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

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

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

How stop text to speech in Base adapter

I have a custom ListView with BaseAdapter. In this custom ListView when a user clicks on any particular text, it speaks the text but the problem is that when any user clicks on the back button how to stop this text from the BaseAdapter. I know how to stop from an Activity but don't know how to stop from BaseAdapter when the user presses back button. Here is my code:
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.Inflater;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
public class BaseAdopter extends BaseAdapter implements TextToSpeech.OnInitListener{
public BaseAdopter(Context context, List<String> versenumber, List<String> verseid, List<String> verselist, List<String> refernce) {
this.context = context;
this.versenumber = versenumber;
this.verseid = verseid;
this.verselist = verselist;
this.refernce = refernce;
}
ALLVERSE allverse;
ArrayList<String> colors;
private Context context;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
#Override
public int getCount() {
return versenumber.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.versedisplayrow,parent,false);
textToSpeech = new TextToSpeech(context, this);
final TextView verseno;
final TextView verselistview;
ImageView share;
ToggleButton addfavoruite;
ImageView speakverse;
final LinearLayout linearLayout;
verseno=(TextView)view.findViewById(R.id.versenumber);
verseno.setText(versenumber.get(position));
verselistview=(TextView)view.findViewById(R.id.verse);
verselistview.setText(verselist.get(position));
addfavoruite=(ToggleButton)view.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)view.findViewById(R.id.layout);
share=(ImageView)view.findViewById(R.id.share);
speakverse=(ImageView)view.findViewById(R.id.speak);
if(DefaultSettings.nightmode(context)){
linearLayout.setBackgroundColor(Color.parseColor("#363437"));
verselistview.setTextColor(Color.parseColor("#ffffff"));
verseno.setTextColor(Color.parseColor("#ffffff"));
}
speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
singleverse(verselist.get(position).toString());
}
});
int a=position+1;
colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
SharedPreferences sharedPreferences=context.getSharedPreferences("DATA",MODE_PRIVATE);
int getverse=sharedPreferences.getInt("versenumber",1);
if(a==getverse){
if(DefaultSettings.highlight(context)){
DefaultSettings.color(context);
linearLayout.setBackgroundColor(DefaultSettings.colorpicked);
}
}
if(Checkisfavourite("favourite","id",verseid.get(position)))
{
if(verseid.get(position).equals(verseid.get(position))){
addfavoruite.setChecked(true);
}else {
addfavoruite.setChecked(false);
}
}
addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Toasty.success(context, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}
else {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(context, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(context, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position) +
+'\n' +'\n' +'\n' +"https://play.google.com/store/apps/details?id=bible.swordof.God");
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
});
/* linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("verseid",colors.get(position));
final long check=mDb.insert("highlight",null,contentValues);
//id get
//postion
//Toast.makeText(activity, ""+getItemId(position), Toast.LENGTH_SHORT).show();
ColorPicker colorPicker = new ColorPicker(context);
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
linearLayout.setBackgroundColor(Color.parseColor(colors.get(position)));
}
#Override
public void onCancel() {
}
}).show();
return false;
}
});
*/
return view;
}
public boolean Checkisfavourite(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
public boolean colorcheck(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void singleverse(String text) {
DefaultSettings.speed(context);
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void stop(){
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
}
The main problem is that your TextToSpeech object belongs to your BaseAdapter when it should belong to the parent activity.
Instead of housing it in the adapter and calling speak on it every time the user clicks an item, I would instead house it in the parent activity and use an "interface callback" that sends a message to the parent when the user clicks an item, sending back the string to speak. This callback relationship works the exact same way as the TextToSpeech.OnInitListener callback that you're already using.
Once the TTS belongs to the parent activity, you can use the activity lifecycle functions to control the shutdown of the TTS like normal.
If you study and understand the following, you should be able to merge it into your code and get a working solution:
Make these changes to your custom BaseAdapter:
// Remove the TextToSpeech object from this class.
public class MyBaseAdapter {
// add this interface definition to your adapter
public interface SpeechClickSubscriber {
void stringNeedsToBeSpoken(String verse);
}
// add this property (the subscriber)
private SpeechClickSubscriber speechClickSubscriber;
// *add* this functionality to your adapter's existing constructor
MyBaseAdapter(SpeechClickSubscriber parent) {
speechClickSubscriber = parent;
}
//...
// change this section of code in your getView() method
speakverse.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
// change this...
// singleverse(verselist.get(position).toString());
// to this:
speechClickSubscriber.stringNeedsToBeSpoken(verselist.get(position).toString());
}
});
// ...
}
Make these changes to your MainActivity (or whatever your parent activity is):
// add the SpeechClickSubscriber implementation
public class MainActivity extends AppCompatActivity implements MyBaseAdapter.SpeechClickSubscriber, TextToSpeech.OnInitListener {
MyBaseAdapter adapter;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// using app context is better and less error prone.
textToSpeech = new TextToSpeech(getApplicationContext(), this);
}
// *add* this method to this activity (this is the answer to your question)
#Override
protected void onStop() {
super.onStop();
stopTTS();
}
// use this method as your "onStart()" method...
// this will help prevent any user input processing until the tts is initialized.
private void start_Activity_Because_TTS_Has_Initialized() {
adapter = new MyBaseAdapter(this);
}
// *MOVE* this method from your base adapter to this (parent) activity:
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
// *move* and *rename* this method from your adapter to the parent activity:
// from:
/*
private void singleverse(String text) {
DefaultSettings.speed(context);
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} */
// to:
#Override
public void stringNeedsToBeSpoken(String verse) {
Log.i("XXX","stringNeedsToBeSpoken() was called because the user clicked an item.");
Log.i("XXX","This method is being called because this activity subscribes to the callback we created and added to our base adapter.");
//DefaultSettings.speed(context); // <----------------- I don't know what this does.
// I'm assuming that DefaultSettings is a static class you have made.
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(verse, TextToSpeech.QUEUE_FLUSH, null);
}
public void stopTTS(){
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
}

Nullpointerexception when trying to insert a value into SQLite

I'm trying to insert some values into an SQLite Database which are entered by the user, however when I press the button to save the values it crashes and a NullPointer exception is thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference at com.example.w4e74.farmanimalfinal.DatabaseHelper.insertRecord(DatabaseHelper.java:61)at com.example.w4e74.farmanimalfinal.Activity_item.onOptionsItemSelected(Activity_item.java:66)
I do not know what is causing the exception. My code is below, any help would be very appreciated.
Activity_item.java
package com.example.w4e74.farmanimalfinal;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewDebug;
import android.widget.EditText;
import android.widget.ListView;
public class Activity_item extends AppCompatActivity {
EditText editText_item;
boolean newItem;
long item_index;
private SQLiteDatabase db;
private Cursor cursor;
CustomCursorAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
DatabaseHelper db = new DatabaseHelper(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_item);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
item_index = intent.getLongExtra("item_index", -1);
if(item_index == -1) {
newItem = true;
} else {
newItem = false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_item:
DatabaseHelper.insertRecord(db, (R.id.editText_date),(R.id.editText_time), Integer.toString(R.id.editText_staff),(R.id.editText_animal),Integer.toString(R.id.editText_activity),Integer.toString(R.id.editText_details));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabaseHelper.java
package com.example.w4e74.farmanimalfinal;
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 DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "farmanimals";
private static final int DB_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE RECORD ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "DATE INTEGER, "
+ "TIME INTEGER, "
+ "STAFF TEXT,"
+ "ANIMAL INTEGER,"
+ "ACTIVITY TEXT,"
+ "DETAIL TEXT);"
);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
#Override
public void onDowngrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public static long insertRecord(SQLiteDatabase db, int date, int time, String staff, int animal, String activity, String detail ) {
ContentValues recordValues = new ContentValues();
recordValues.put("DATE", date);
recordValues.put("TIME", time);
recordValues.put("STAFF", staff);
recordValues.put("ANIMAL", animal);
recordValues.put("ACTIVITY", activity);
recordValues.put("DETAIL", detail);
long newRecordID = db.insert("RECORD", null, recordValues);
return newRecordID;
}
public static String getDatabaseContentsAsString(SQLiteDatabase db) {
Cursor cursor = db.query("RECORD",
new String[]{"_id", "DATE", "TIME", "STAFF", "ANIMAL", "ACTIVITY", "DETAIL"},
null, null, null, null, "_id ASC");
String databaseAsString = System.getProperty("line.separator");
if(cursor.getCount() != 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
for (int i=0; i < cursor.getColumnCount() - 1; i++) {
databaseAsString += cursor.getString(i) + " ";
}
databaseAsString += System.getProperty("line.separator");
cursor.moveToNext();
}
if(cursor != null) cursor.close();
}
return databaseAsString;
}
public static void deleteRecord(SQLiteDatabase db, Long id) {
db.delete("RECORD", "_id=?", new String[] {Long.toString(id)});
}
public static void deleteAllRecords(SQLiteDatabase db) {
db.delete("RECORD", null, null);
db.delete("SQLITE_SEQUENCE","NAME = ?",new String[]{"RECORD"});
}
}
Edit: Error message received:
Incompatible types.
Required:
android.database.sqlite.SQLiteDatabase
Found:
com.example.w4e74.farmanimalfinal.DatabaseHelper
Your problem is the scope of db In onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
DatabaseHelper db = new DatabaseHelper(this);
...
}
You have this instance of db declared as a local variable, effectively creating two variables, both called db but operating at different scopes. This means that as soon as onCreate() is finished, this reference to db will be lost and garbage collected.
Your two instances of db are also of different types - SQLiteDatabase and DatabaseHelper, so a better variable naming strategy would help avoid problems like this in the future. As we'll be using the SQLiteDatabase version of db, we'll need to grab a writable instance of your database to use with the helper in future:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
db = new DatabaseHelper(this).getWritableDatabase();
...
}
This will ensure that you're setting the member variable rather than a local variable.

Query Database using selected item from drop down spinner

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

Categories