How stop text to speech in Base adapter - java

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

Related

How to call another activity by menuitem? Android Studio Error: method call expected

I am completely new to Android Studio and just learned Object-oriented programming. My project requires me to build something on open-source code. I added a new menu item to a menu and want to start another activity once the user clicks the menu item with id: plot. I followed a recipe on the internet but got an error with it. It said 'method call expected' which means Terminal Fragment may be a method. I got confused, as I thought it is a class(an activity). Could anyone give me instructions to start an activity (turn to the next page with a different activity) in this case? What will be the simplest way to do this? Much Appreciated.
I added this in onOptionsItemSelected(MenuItem item).
if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}
TerminalFragment.java (entire code)
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {
receive(data);
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
menu_terminal.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/plot"
android:title="PLOTDATA"
app:showAsAction="always" />
<item
android:id="#+id/clear"
android:icon="#drawable/ic_delete_white_24dp"
android:title="Clear"
app:showAsAction="always" />
<item
android:id="#+id/newline"
android:title="Newline"
app:showAsAction="never" />
<item
android:id="#+id/hex"
android:title="HEX Mode"
android:checkable="true"
app:showAsAction="never" />
</menu>
Here, TerminalFragment is a fragment, not an activity. And so, instead of using TerminalFragment.this in new Intent(), you should use getActivity().
So, the final code would look something like this:
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
You can also check this: Intent from Fragment to Activity

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

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

how to call onOptionsItemSelected on a different activity

I have an activity with uses onOptionsItemSelected(MenuItem item) method in FolderActivity and I want to call this method on another activity (MainActivity)
the main activity uses CMU Sphinx - Speech Recognition Toolkit.
I need to call some methods from FolderActivity to MainActivity.
package com.evolution.filemanager.folders;
import static android.widget.Toast.makeText;
import java.io.File;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.evolution.filemanager.FileManagerApplication;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.clipboard.Clipboard;
import com.evolution.filemanager.clipboard.Clipboard.ClipboardListener;
import com.evolution.filemanager.clipboard.ClipboardFileAdapter;
import com.evolution.filemanager.favourites.FavouritesManager;
import com.evolution.filemanager.favourites.FavouritesManager.FavouritesListener;
import com.evolution.filemanager.nav_drawer.NavDrawerAdapter;
import com.evolution.utils.FontApplicator;
import com.evolution.utils.ListViewUtils;
import edu.cmu.pocketsphinx.demo.R;
public class FolderActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
{
public static class FolderNotOpenException extends Exception
{
}
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private FontApplicator fontApplicator;
public static Activity FOLDERACTIVITY;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_folder);
setupDrawers();
Clipboard.getInstance().addListener(this);
FOLDERACTIVITY = this;
fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
}
public FontApplicator getFontApplicator()
{
return fontApplicator;
}
#Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getFavouritesManager().removeFavouritesListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
#Override
protected void onPause()
{
if (lastFolder != null)
{
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
public void setActionbarVisible(boolean visible)
{
ActionBar actionBar = getActionBar();
if (actionBar == null) return;
if (visible)
{
actionBar.show();
setSystemBarTranslucency(false);
}
else
{
actionBar.hide();
setSystemBarTranslucency(true);
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected void setSystemBarTranslucency(boolean translucent)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
if (translucent)
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
else
{
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags &= (~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setAttributes(params);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
public void setupDrawers()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;
#Override
public void onDrawerOpened(View drawerView)
{
makeText(getApplicationContext(), "drawer open", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView)
{
makeText(getApplicationContext(), "drawer close", Toast.LENGTH_SHORT).show();
actionBarShown=false;
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
drawerLayout.setFocusableInTouchMode(false);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setupNavDrawer();
setupClipboardDrawer();
}
#Override
public void onBackPressed()
{
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else if (drawerLayout.isDrawerOpen(GravityCompat.END))
drawerLayout.closeDrawer(GravityCompat.END);
else
super.onBackPressed();
}
void setupNavDrawer()
{
FileManagerApplication application = (FileManagerApplication) getApplication();
// add listview header to push items below the actionbar
ListView navListView = (ListView) findViewById(R.id.listNavigation);
ListViewUtils.addListViewPadding(navListView, this, true);
loadFavourites(application.getFavouritesManager());
application.getFavouritesManager().addFavouritesListener(this);
}
void setupClipboardDrawer()
{
// add listview header to push items below the actionbar
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
ListViewUtils.addListViewHeader(clipboardListView, this);
onClipboardContentsChange(Clipboard.getInstance());
}
void loadFavourites(FavouritesManager favouritesManager)
{
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
navDrawerAdapter.setFontApplicator(fontApplicator);
listNavigation.setAdapter(navDrawerAdapter);
listNavigation.setOnItemClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
makeText(getApplicationContext(), "unsa ni?", Toast.LENGTH_SHORT).show();
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
makeText(getApplicationContext(), item.toString(), Toast.LENGTH_SHORT).show();
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId())
{
case R.id.menu_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public void goBack()
{
getFragmentManager().popBackStack();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public FolderFragment getFolderFragment()
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof FolderFragment)
return (FolderFragment) fragment;
else return null;
}
public File getCurrentFolder() throws FolderNotOpenException
{
FolderFragment folderFragment = getFolderFragment();
if (folderFragment == null)
throw new FolderNotOpenException();
else return folderFragment.currentDir;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerAdapter.NavDrawerItem item = (NavDrawerAdapter.NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
FolderFragment folderFragment = getFolderFragment();
if (folderFragment != null)
{
// TODO: paste single file
}
break;
default:
break;
}
}
public File getLastFolder()
{
return lastFolder;
}
#Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
if (clipboard.isEmpty() && drawerLayout != null)
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
else
{
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
FileManagerApplication application = (FileManagerApplication) getApplication();
if (clipboardListView != null)
{
ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
clipboardFileAdapter.setFontApplicator(fontApplicator);
clipboardListView.setAdapter(clipboardFileAdapter);
}
}
}
#Override
public void onFavouritesChanged(FavouritesManager favouritesManager)
{
loadFavourites(favouritesManager);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event)
{
Log.d("Key Long Press", event.toString());
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
return true;
}
else return super.onKeyLongPress(keyCode, event);
}
}
and the activity where I want to call
package edu.cmu.pocketsphinx.demo;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.evolution.filemanager.about.AboutActivity;
import com.evolution.filemanager.folders.FolderActivity;
import com.evolution.utils.DataClearer;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
public class MainActivity extends Activity implements
RecognitionListener {
public AnimationDrawable rocketAnimation;
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "digits";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "frost";
private static final String GO_BACK = "back";
private static final String PREVIOUS = "previous";
private static final String OPEN_FILE_MANAGER = "open file manager";
private static final String OPEN_ABOUT = "open about";
private static final String OPEN_MUSIC = "open music";
private static final String OPEN_PICTURES = "open pictures";
private static final String OPEN_VIDEOS = "open videos";
private static final String SHOW_COMMANDS = "show commands";
private static final String CLOSE_FILE_MANAGER = "close file manager";
private static final String CLOSE_ABOUT = "close about";
private static final String CLOSE_MUSIC = "close music";
private static final String CLOSE_PICTURES = "close pictures";
private static final String CLOSE_VIDEOS = "close videos";
private static final String CLOSE_COMMANDS = "close commands";
private static final String SHOW_DRAWER = "show drawer";
private static final String HIDE_DRAWER = "hide drawer";
public static boolean isOPEN_FILE_MANAGER = false;
private static boolean isOPEN_ABOUT = false;
private static boolean isOPEN_MUSIC = false;
private static boolean isOPEN_PICTURES = false;
private static boolean isOPEN_VIDEOS = false;
private static boolean isSHOW_COMMANDS = false;
private static boolean isSHOW_DRAWER = false;
private static String MENU_CAPTION;
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
ImageView rocketImage = (ImageView) findViewById(R.id.imageViewAnim);
rocketImage.setBackgroundResource(R.drawable.heart_animation);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
TextView tv = ((TextView) findViewById(R.id.caption_text));
if (text.equals(KEYPHRASE))
{
switchSearch(MENU_SEARCH);
rocketAnimation.start();
}
else if (text.equals(OPEN_FILE_MANAGER))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , FolderActivity.class);
startActivity(intent);
isOPEN_FILE_MANAGER = true;
}
else if (text.equals(CLOSE_FILE_MANAGER))
{
if(isOPEN_FILE_MANAGER == true)
{
switchSearch(KWS_SEARCH);
FolderActivity.FOLDERACTIVITY.finish();
isOPEN_FILE_MANAGER = false;
}
}
else if (text.equals(SHOW_COMMANDS))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , Commands.class);
startActivity(intent);
isSHOW_COMMANDS = true;
}
else if (text.equals(CLOSE_COMMANDS))
{
if(isSHOW_COMMANDS == true)
{
switchSearch(KWS_SEARCH);
Commands.SHOWCOMMANDS.finish();
}
}
else if (text.equals(OPEN_PICTURES))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent (PocketSphinxActivity.this , AboutActivity.class);
startActivity(intent);
}
else if(text.equals(OPEN_ABOUT))
{
switchSearch(KWS_SEARCH);
Intent intent = new Intent(PocketSphinxActivity.this, AboutActivity.class);
startActivity(intent);
isOPEN_ABOUT = true;
}
else if(text.equals(CLOSE_ABOUT))
{
if (isOPEN_ABOUT == true)
{
switchSearch(KWS_SEARCH);
AboutActivity.ABOUTACTIVITY.finish();
}
}
else if(text.equals(GO_BACK) || text.equals(PREVIOUS))
{
if(isOPEN_FILE_MANAGER == true )
{
FolderActivity.FOLDERACTIVITY//where i want to call onOptionsItemSelected
switchSearch(KWS_SEARCH);
}
}
else
{
switchSearch(KWS_SEARCH);
((TextView) findViewById(R.id.result_text)).setText(text);
}
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName())
|| OPEN_FILE_MANAGER.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/menu.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this); //clear cache to minimize the app size
DataClearer.getInstance().clearApplicationData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
the FolderActivity runs on top of the MainActivty but the voice recognition in MainActivity is still active and I want the voice itself do some manipulation in the FolderActivity
Here's a few suggestions:
Have FolderActivity register a BroadcastReceiver as a listener for a certain Intent. When MainActivity wants to do something in FolderActivity, it can send a broadcast Intent which will be seen by the BroadcastReceiver in FolderActivity, which can then call the appropriate method in the `Activity.
When MainActivity wants to do something in FolderActivity, it can launch FolderActivity again using an Intent with flag Intent.FLAG_ACTIVITY_SINGLE_TOP and some "extra" that describes what FolderActivity should do. In FolderActivity override onNewIntent(), read the passed Intent parameter and use it to determine what method to call in FolderActivity. Because the Activity was launched withIntent.FLAG_ACTIVITY_SINGLE_TOP, Android won't create a new instance of the Activity, it will just callonNewIntent()` on the existing instance.
Have FolderActivity set a public static variable of type Activity to a reference to itself in onCreate(). MainActivity can then call a method on FolderActivity by doing something like FolderActivity.activityReference.doSomething()
Method 3 is not the preferred method, since you need to make sure that you set the public static variable to null in FolderActivity.onDestroy() and there are other concerns (timing issues, memory leaks, etc.) that need to be dealt with properly.
NOTE: You probably don't want to call onOptionsItemSelected() directly. This method is called by the Android framework when an options item is selected by the user. You should call directly the method that actually does something, not this framework callback method.

Value of EditText not appearing in my logs

I an new to Android. I have the following code for a Twitter Client search:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
if (searchResults == null)
{
Log.w(LogConstants.LOG, "searchResults is null");
}
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
The issue is, I have tried to log the results of the EditText, however I never see that in the logs. What is going on here? I can't work out why I'm never seeing "Text value is " + queryText in the logs.
The problem is you initialize the String value queryText in the event of the screen being created (onCreate()) and not when you actually type in values (after screen creation & dynamic activity on the screen).
This is why the following would work
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals("")) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
Change
Log.i(LogConstants.LOG, "Text value is " + queryText);
to
Log.i(LogConstants.LOG, "Text value is " + queryEditText.getText().toString());
Move
queryText = (queryEditText.getText().toString());
inside the onClick
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if ("".equals(queryText)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});

Categories