How can I use method speakOut from (Detail java) in (NoteEdit java)
so I use it after menu_search instead of viewDetails(mDateText).
This is Detail class
public class Detail extends Activity implements TextToSpeech.OnInitListener{
private Button prsstospeak;
public String data;
private int result=0;
private TextToSpeech tts;
private TextView passedView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.disp);
tts = new TextToSpeech(this, this);
prsstospeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
//It will called before TTS started
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
//check status for TTS is initialized or not
if (status == TextToSpeech.SUCCESS) {
//if TTS initialized than set language
result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // you can set pitch level
// tts.setSpeechRate(2); //you can set speech speed rate
//check language is supported or not
//check language data is available or not
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Missing data", Toast.LENGTH_LONG).show();
//disable button
prsstospeak.setEnabled(false);
} else {
prsstospeak.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
if(result!=tts.setLanguage(Locale.US))
{
Toast.makeText(getApplicationContext(), "Enter right Words...... ", Toast.LENGTH_LONG).show();
}else
{
//speak given text
tts.speak(data, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
This is NoteEdie:
public class NoteEdit extends Activity {
public static int numTitle = 1;
public static String curDate = "";
public static String curText = "";
private EditText mTitleText;
private EditText mBodyText;
private TextView mDateText;
private Long mRowId;
private Cursor note;
private NotesDbAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.app_name);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateText = (TextView) findViewById(R.id.notelist_date);
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("d'/'M'/'y");
curDate = formatter.format(curDateTime);
mDateText.setText(""+curDate);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
}
public static class LineEditText extends EditText{
public LineEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE);
}
private Rect mRect;
private Paint mPaint;
#Override
protected void onDraw(Canvas canvas) {
int height = getHeight();
int line_height = getLineHeight();
int count = height / line_height;
if (getLineCount() > count)
count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
int baseline = getLineBounds(0, r);
for (int i = 0; i < count; i++) {
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
baseline += getLineHeight();
super.onDraw(canvas);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.noteedit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
return true;
case R.id.menu_delete:
if(note != null){
note.close();
note = null;
}
if(mRowId != null){
mDbHelper.deleteNote(mRowId);
}
finish();
return true;
//speech button
case R.id.menu_search:
viewDetails(mDateText);
finish();
return true;
case R.id.menu_save:
saveState();
finish();
return true;
/* case android.R.id.home:
finish(); */
default:
return super.onOptionsItemSelected(item);
}
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if(mRowId == null){
long id = mDbHelper.createNote(title, body, curDate);
if(id > 0){
mRowId = id;
}else{
Log.e("saveState","failed to create note");
}
}else{
if(!mDbHelper.updateNote(mRowId, title, body, curDate)){
Log.e("saveState","failed to update note");
}
}
}
private void populateFields() {
if (mRowId != null) {
note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
curText = note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
}
}
public void viewDetails(View view){
String data= mDbHelper.getALLData();
}
}
How can I use method speakOut from (Detail java) in (NoteEdit java)
so I use it after menu_search instead of viewDetails(mDateText).
Its not a good way to call a method in activity from another activity !
You have 2 solution :
the easiest way (I think) : if you have a method (or methods) that
you use alot and in different classes (such as activity or
fragment), put them in a class and import this class to your
activity and use this method.
call the activity that contain this method with
startActivityForResult and intent and return the result your
activity. For more info about how is this way:
How to manage `startActivityForResult` on Android?
Related
I was in trouble with logical error somewhere in my program, what happening is when I use time picker and Switch in my MainActivity then the time selected and Switch state getting changed in my another activity i.e: UtilMainActivity which is a subclass. But whereas, when I change the switch state and time in my UtilMainActivity it is not resulting in a change of switch state and alarm time in my MainActivity.What I actually need is when I change alarm time and switch in MainActivity does not lead to change of time and switch in my UtilMainActivity.......Hope You understand my problem. Here is My MainActivity.
UtilMainActivity
public class UtilMainActivity extends AppCompatActivity implements
TimePickerDialog.OnTimeSetListener {
SwitchCompat onOffSwitch;
TextView firstAlarmTextView;
TextView timeLeftTextView;
LinearLayout firstAlarmLayout;
UtilSharedPreferencesHelper sharPrefHelper;
UtilTimerManager utilTimerManager;
UtilAlarmParams utilAlarmParams;
BroadcastReceiver timeLeftReceiver;
private final String LOG_TAG = UtilMainActivity.class.getSimpleName();
final int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 45;
final float DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION = 2f; // number of alarms, first alarm, interval values text size is larger than text around them
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.utility_activity_main);
onOffSwitch = (SwitchCompat) findViewById(R.id.switch_main);
firstAlarmLayout = (LinearLayout) findViewById(R.id.layout_main_firstalarm);
firstAlarmTextView = (TextView) findViewById(R.id.textview_main_firstalarm_time);
timeLeftTextView = (TextView) findViewById(R.id.textview_main_timeleft);
sharPrefHelper = new UtilSharedPreferencesHelper(UtilMainActivity.this);
sharPrefHelper.printAll();
utilAlarmParams = sharPrefHelper.utilgetParams();
utilTimerManager = new UtilTimerManager(UtilMainActivity.this);
showFirstAlarmTime(utilAlarmParams.firstUtilAlarmTime.toString());
showTimeLeft(utilAlarmParams);
onOffSwitch.setChecked(sharPrefHelper.isAlarmTurnedOn());
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
utilAlarmParams.turnedOn = isChecked;
if (isChecked) {
checkNotificationPolicy();
checkOverlayPermission();
utilTimerManager.startSingleAlarmTimer(utilAlarmParams.firstUtilAlarmTime.toMillis());
showToast(getString(R.string.utility_main_alarm_turned_on_toast));
} else {
utilTimerManager.cancelTimer();
showToast(getString(R.string.utility_main_alarm_turned_off_toast));
}
showTimeLeft(utilAlarmParams);
sharPrefHelper.utilsetAlarmState(isChecked);
}
});
firstAlarmLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle timePickerBundle = new Bundle();
timePickerBundle.putInt(UtilTimePickerDialogFragment.BUNDLE_KEY_ALARM_HOUR, sharPrefHelper.utilgetHour());
timePickerBundle.putInt(UtilTimePickerDialogFragment.BUNDLE_KEY_ALARM_MINUTE, sharPrefHelper.utilgetMinute());
UtilTimePickerDialogFragment timePicker = new UtilTimePickerDialogFragment();
timePicker.setArguments(timePickerBundle);
timePicker.show(getFragmentManager(), UtilTimePickerDialogFragment.FRAGMENT_TAG);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onResume() {
super.onResume();
showTimeLeft(utilAlarmParams);
timeLeftReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) { //i.e. every minute
showTimeLeft(utilAlarmParams);
}
}
};
registerReceiver(timeLeftReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
protected void onPause() {
super.onPause();
if (timeLeftReceiver != null) {
unregisterReceiver(timeLeftReceiver);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
UtilAlarmTime utilAlarmTime = new UtilAlarmTime(hour, minute);
utilAlarmParams.firstUtilAlarmTime = utilAlarmTime;
showFirstAlarmTime(utilAlarmTime.toString());
showTimeLeft(utilAlarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.utilsetTime(utilAlarmTime);
}
private void showToast(String message) {
Toast.makeText(UtilMainActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void resetTimerIfTurnedOn() {
if (onOffSwitch.isChecked()) {
utilTimerManager.resetSingleAlarmTimer(utilAlarmParams.firstUtilAlarmTime.toMillis());
showToast(getString(R.string.utility_main_alarm_reset_toast));
}
}
private void showFirstAlarmTime(String firstAlarmTime) {
String wholeTitle = getString(R.string.utility_main_firstalarm_time, firstAlarmTime);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(firstAlarmTime) - 1,
wholeTitle.indexOf(firstAlarmTime) + firstAlarmTime.length(), 0);
firstAlarmTextView.setText(wholeTitleSpan);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void showTimeLeft(UtilAlarmParams utilAlarmParams) {
UtilAlarmTime utilAlarmTime = utilAlarmParams.firstUtilAlarmTime;
timeLeftTextView.setText(getString(R.string.utility_all_time_left, utilAlarmTime.getHoursLeft(), utilAlarmTime.getMinutesLeft()));
if (utilAlarmParams.turnedOn) {
timeLeftTextView.setTextColor(getColor(R.color.primary));
} else {
timeLeftTextView.setTextColor(getColor(R.color.main_disabled_textcolor));
}
Log.d(LOG_TAG, "Time left: "+ utilAlarmTime.getHoursLeft() + ":" + utilAlarmTime.getMinutesLeft());
}
private void checkNotificationPolicy() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
/**
* needed for Android Q: on some devices activity doesn't show from fullScreenNotification without
* permission SYSTEM_ALERT_WINDOW
*/
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkOverlayPermission() {
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.P) && (!Settings.canDrawOverlays(this))) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements
IntervalDialogFragment.IntervalDialogListener,
NumberOfAlarmsDialogFragment.NumberOfAlarmsDialogListener,
TimePickerDialog.OnTimeSetListener {
SwitchCompat onOffSwitch;
ListView alarmsListView;
TextView intervalBetweenAlarmsTextView;
TextView numberOfAlarmsTextView;
TextView firstAlarmTextView;
TextView timeLeftTextView;
LinearLayout firstAlarmLayout;
LinearLayout intervalLayout;
LinearLayout numberOfAlarmsLayout;
AlarmsListHelper alarmsListHelper;
SharedPreferencesHelper sharPrefHelper;
TimerManager timerManager;
AlarmParams alarmParams;
BroadcastReceiver timeLeftReceiver;
Button sleepTimer;
private final String LOG_TAG = MainActivity.class.getSimpleName();
final int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 45;
final float DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION = 2f; // number of alarms, first alarm, interval values text size is larger than text around them
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmsListView = (ListView) findViewById(R.id.listview_main_alarmslist);
onOffSwitch = (SwitchCompat) findViewById(R.id.util_switch_main);
intervalBetweenAlarmsTextView = (TextView) findViewById(R.id.textview_main_interval);
numberOfAlarmsTextView = (TextView) findViewById(R.id.textview_main_numberofalarms);
firstAlarmLayout = (LinearLayout) findViewById(R.id.layout_main_firstalarm);
firstAlarmTextView = (TextView) findViewById(R.id.util_textview_main_firstalarm_time);
timeLeftTextView = (TextView) findViewById(R.id.textview_main_timeleft);
intervalLayout = (LinearLayout) findViewById(R.id.layout_main_interval);
numberOfAlarmsLayout = (LinearLayout) findViewById(R.id.layout_main_numberofalarms);
sleepTimer = (Button) findViewById(R.id.sleepTimer);
sharPrefHelper = new SharedPreferencesHelper(MainActivity.this);
sharPrefHelper.printAll();
alarmParams = sharPrefHelper.getParams();
timerManager = new TimerManager(MainActivity.this);
alarmsListHelper = new AlarmsListHelper(MainActivity.this, alarmsListView);
showFirstAlarmTime(alarmParams.firstAlarmTime.toString());
showTimeLeft(alarmParams);
showInterval(sharPrefHelper.getIntervalStr());
showNumberOfAlarms(sharPrefHelper.getNumberOfAlarmsStr());
onOffSwitch.setChecked(sharPrefHelper.isAlarmTurnedOn());
alarmsListHelper.showList(alarmParams);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
alarmParams.turnedOn = isChecked;
if (isChecked) {
checkNotificationPolicy();
checkOverlayPermission();
timerManager.startSingleAlarmTimer(alarmParams.firstAlarmTime.toMillis());
showToast(getString(R.string.main_alarm_turned_on_toast));
sharPrefHelper.setNumberOfAlreadyRangAlarms(0);
} else {
timerManager.cancelTimer();
showToast(getString(R.string.main_alarm_turned_off_toast));
}
alarmsListHelper.showList(alarmParams);
showTimeLeft(alarmParams);
sharPrefHelper.setAlarmState(isChecked);
}
});
intervalLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntervalDialogFragment dialog = new IntervalDialogFragment();
Bundle intervalBundle = new Bundle();
intervalBundle.putString(IntervalDialogFragment.BUNDLE_KEY_INTERVAL, sharPrefHelper.getIntervalStr());
dialog.setArguments(intervalBundle);
dialog.show(getFragmentManager(), IntervalDialogFragment.FRAGMENT_TAG);
}
});
numberOfAlarmsLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NumberOfAlarmsDialogFragment dialog = new NumberOfAlarmsDialogFragment();
Bundle numberOfAlarmsBundle = new Bundle();
numberOfAlarmsBundle.putString(NumberOfAlarmsDialogFragment.BUNDLE_KEY_NUMBER_OF_ALARMS, sharPrefHelper.getNumberOfAlarmsStr());
dialog.setArguments(numberOfAlarmsBundle);
dialog.show(getFragmentManager(), NumberOfAlarmsDialogFragment.FRAGMENT_TAG);
}
});
firstAlarmLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle timePickerBundle = new Bundle();
timePickerBundle.putInt(TimePickerDialogFragment.BUNDLE_KEY_ALARM_HOUR, sharPrefHelper.getHour());
timePickerBundle.putInt(TimePickerDialogFragment.BUNDLE_KEY_ALARM_MINUTE, sharPrefHelper.getMinute());
TimePickerDialogFragment timePicker = new TimePickerDialogFragment();
timePicker.setArguments(timePickerBundle);
timePicker.show(getFragmentManager(), TimePickerDialogFragment.FRAGMENT_TAG);
}
});
sleepTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNewActivity();
}
});
}
public void openNewActivity(){
Intent intent = new Intent(this, SleepTimerActivity.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
showTimeLeft(alarmParams);
timeLeftReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) { //i.e. every minute
showTimeLeft(alarmParams);
}
}
};
registerReceiver(timeLeftReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
protected void onPause() {
super.onPause();
if (timeLeftReceiver != null) {
unregisterReceiver(timeLeftReceiver);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
new Handler().post(new Runnable() {
#Override
public void run() {
final View view = findViewById(R.id.scheduleactivity);
if (view != null) {
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do something...
Toast.makeText(getApplicationContext(), "Scheduled Utilities Stopper", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings: {
Intent intent = new Intent(this, PrefActivity.class);
startActivity(intent);
break;
}
case R.id.scheduleactivity: {
Intent intent = new Intent(this, UtilMainActivity.class);
startActivity(intent);
break;
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onIntervalChanged(String intervalStr) {
showInterval(intervalStr);
alarmParams.interval = Integer.parseInt(intervalStr);
alarmsListHelper.showList(alarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.setInterval(intervalStr);
}
#Override
public void onNumberOfAlarmsChanged(String numberOfAlarmsStr) {
showNumberOfAlarms(numberOfAlarmsStr);
alarmParams.numberOfAlarms = Integer.parseInt(numberOfAlarmsStr);
alarmsListHelper.showList(alarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.setNumberOfAlarms(numberOfAlarmsStr);
}
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
AlarmTime alarmTime = new AlarmTime(hour, minute);
alarmParams.firstAlarmTime = alarmTime;
showFirstAlarmTime(alarmTime.toString());
alarmsListHelper.showList(alarmParams);
showTimeLeft(alarmParams);
sharPrefHelper.setNumberOfAlreadyRangAlarms(0);
resetTimerIfTurnedOn();
sharPrefHelper.setTime(alarmTime);
}
private void showToast(String message) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void resetTimerIfTurnedOn() {
if (onOffSwitch.isChecked()) {
timerManager.resetSingleAlarmTimer(alarmParams.firstAlarmTime.toMillis());
showToast(getString(R.string.main_alarm_reset_toast));
}
}
private void showInterval(String interval) {
String wholeTitle = getString(R.string.main_interval, interval);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION), wholeTitle.indexOf(interval), interval.length() + 1, 0);
intervalBetweenAlarmsTextView.setText(wholeTitleSpan);
}
private void showNumberOfAlarms(String numberOfAlarms) {
int numberOfAlarmsInt = Integer.parseInt(numberOfAlarms);
String wholeTitle = this.getResources().getQuantityString(R.plurals.main_number_of_alarms, numberOfAlarmsInt, numberOfAlarmsInt);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(numberOfAlarms),
numberOfAlarms.length() + 1, 0);
numberOfAlarmsTextView.setText(wholeTitleSpan);
}
private void showFirstAlarmTime(String firstAlarmTime) {
String wholeTitle = getString(R.string.main_firstalarm_time, firstAlarmTime);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(firstAlarmTime) - 1,
wholeTitle.indexOf(firstAlarmTime) + firstAlarmTime.length(), 0);
firstAlarmTextView.setText(wholeTitleSpan);
}
private void showTimeLeft(AlarmParams alarmParams) {
AlarmTime alarmTime = alarmParams.firstAlarmTime;
timeLeftTextView.setText(getString(R.string.all_time_left, alarmTime.getHoursLeft(), alarmTime.getMinutesLeft()));
if (alarmParams.turnedOn) {
timeLeftTextView.setTextColor(getColor(R.color.primary));
} else {
timeLeftTextView.setTextColor(getColor(R.color.main_disabled_textcolor));
}
Log.d(LOG_TAG, "Time left: "+alarmTime.getHoursLeft() + ":" + alarmTime.getMinutesLeft());
}
private void checkNotificationPolicy() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
/**
* needed for Android Q: on some devices activity doesn't show from fullScreenNotification without
* permission SYSTEM_ALERT_WINDOW
*/
private void checkOverlayPermission() {
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.P) && (!Settings.canDrawOverlays(this))) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}
}
Your activity, won't get the new data, because it's receiver was already unregistered, to make this easier for you, I would advise, you start the activity with startActivityForResult that way when you are done, you can set the data and the previous activity will receive the data in a bundle on this callback onActivityResult(...)
I am creating this application which has three tabs. Tab1 is used to handle bluetooth incoming and outgoing connections. The major problem comes here is once i click the connect button the connection is created but when i switch tabs and then jump back to tab1 everything is lost as the tab is reinitialized. I want to stop this from happening. Please suggest me the correction in my code.
Here is the MainActivity.java file
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
private TabLayout tabLayout;
StringBuilder recDataString = new StringBuilder();
int handlerState = 0;
private ViewPager viewPager;
int initialize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Manual"));
tabLayout.setSelectedTabIndicatorColor(Color.BLACK);
tabLayout.addTab(tabLayout.newTab().setText("Status"));
tabLayout.addTab(tabLayout.newTab().setText("Database"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager)findViewById(R.id.pager);
Pager adapter = new Pager(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setOnTabSelectedListener(this);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("BS");
Log.d("********", "ID = " + id);
/*if (id.equalsIgnoreCase("F")) {
sendToConnectedThread(id);
}*/
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.nitesh.finaltab.DATA_BROADCAST");
getApplicationContext().registerReceiver(broadcastReceiver,filter);
}
public int getInitialize(){
return initialize;
}
public void setInitialize(int m){
this.initialize = m;
}
#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 void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Here is the Pager.java file
public class Pager extends FragmentStatePagerAdapter {
int tabcount;
public Pager(FragmentManager fm, int tabcount){
super(fm);
this.tabcount = tabcount;
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
#Override
public int getCount(){return tabcount;}
}
And here is the Tab1.java file
public class Tab1 extends Fragment {
SQLiteDatabase alexadb,activitydb;
MainActivity mainActivity= new MainActivity();
StringBuilder recDataString = new StringBuilder();
String address = "98:D3:32:20:5A:57";
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
int handlerState = 0;
public boolean isBtConnected = false;
ProgressDialog progressDialog;
int initialize = 0;
Handler bluetoothIn;
BluetoothAdapter myBluetooth;
BluetoothSocket bluetoothSocket;
ConnectedThread connectedThread ;
Button connect,forward,reverse,left,right,stop;
int speed;
String datatoSend;
private final long REPEAT_DELAY = 50;
boolean autoIncreament,autoDecreament;
View view;
private Handler repeatUpdateHandler = new Handler();
private Handler senddataUpdatehandler = new Handler();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
createDatabase();
view = inflater.inflate(R.layout.tab1, container, false);
forward = (Button) view.findViewById(R.id.bforward);
reverse = (Button) view.findViewById(R.id.breverse);
left = (Button) view.findViewById(R.id.bleft);
stop = (Button) view.findViewById(R.id.bstop);
connect = (Button)view.findViewById(R.id.buttonConnect);
right = (Button) view.findViewById(R.id.bright);
Toast.makeText(getContext(), "Tab1 Initiated", Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setMessage("Ready to connect?");
handler();
class RepetitiveUpdater implements Runnable {
#Override
public void run() {
if (autoIncreament) {
increment();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
} else if (autoDecreament) {
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Process Initiated", Toast.LENGTH_SHORT).show();
new CheckBT().execute();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// bluetoothConnect.sendData("R");
Log.d("Right", "Button is clicked");
sendData("R");
insertIntoActivityDB("Right Button is clicked");
}
});
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("L");
insertIntoActivityDB("Left Button is clicked");
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("B");
insertIntoActivityDB("Reverse Button is clicked");
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
autoDecreament = false;
autoIncreament = false;
sendData("S");
insertIntoActivityDB("Stop Button is clicked");
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment();
sendData("F");
insertIntoActivityDB("Forward Button is clicked");
}
});
forward.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
autoIncreament = true;
autoDecreament = false;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
forward.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && autoIncreament) {
autoIncreament = false;
autoDecreament = true;
sendData("D");
repeatUpdateHandler.post(new RepetitiveUpdater());
}
return false;
}
});
return view;
}
public void handler() {
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endofLineIndex = recDataString.indexOf("~");
if (endofLineIndex > 0) {
// String dataInPrint = recDataString.substring(0,endofLineIndex);
String data = recDataString.substring(1, endofLineIndex);
Log.d("Received Text", "" + data);
String first = recDataString.substring(0, 1);
Log.d("First letter ", "Hello" + first);
if (first.equalsIgnoreCase("P")) {
insertIntoAlexaDB(data);
}
if (first.equalsIgnoreCase("V")) {
insertIntoAlexaDB(data);
} else {
}
recDataString.delete(0, recDataString.length());
// dataInPrint = " ";
data = "";
first = " ";
}
}
}
};
}
public void increment(){
speed++;
sendData("F");
Log.d("Increasing Speed"," "+speed);
}
public void decrement() {
if (speed > 0) {
speed--;
sendData("D");
Log.d("Decreasing Speed", " " + speed);
}
}
public class CheckBT extends AsyncTask<Void, Void, Void>//UI Thread
{
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getContext(), "Connecting you", "From Alexa");
Toast.makeText(getContext(),"Conneting",Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
if (bluetoothSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = myBluetooth.getRemoteDevice(address);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID); //Create RFCOMM connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
bluetoothSocket.connect();
}
} catch (IOException e) {
ConnectSuccess = false;
Toast.makeText(getContext(), "HC-05 didn't respond", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getContext(), "Connection Failed. Try Again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Connected", Toast.LENGTH_SHORT).show();
isBtConnected = true;
connectedThread = new ConnectedThread(bluetoothSocket);
connectedThread.start();
}
progressDialog.dismiss();
}
}
private class ConnectedThread extends Thread{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the thread
public ConnectedThread(BluetoothSocket bluetoothSocket){
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
//create I/O streams for connection
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
}catch (IOException
e){}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public boolean getBluetoothStatus() {
Toast.makeText(getContext(),"Bluetooth Status from thread"+isBtConnected,Toast.LENGTH_SHORT).show();
return isBtConnected;
}
public void run(){
byte[] buffer = new byte[256];
int bytes;
//keep looping ot listen for received messages
while(true){
try{
Log.d("Running"," Connected_Thread");
isBtConnected = true;
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer,0,bytes);
//Send the obtained bytes to the UIActivity via handler
bluetoothIn.obtainMessage(handlerState,bytes,-1,readMessage).sendToTarget();
}catch (IOException e){
break;
}
}
}
}
public void sendData(String data) {
try {
bluetoothSocket.getOutputStream().write(data.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creation of DATABASE**/
public void createDatabase(){
alexadb = getContext().openOrCreateDatabase("AlexaDB", Context.MODE_PRIVATE,null);
activitydb= getContext().openOrCreateDatabase("ActivityDB",Context.MODE_PRIVATE,null);
alexadb.execSQL("CREATE TABLE IF NOT EXISTS alexa(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
activitydb.execSQL("CREATE TABLE IF NOT EXISTS activity(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
}
public boolean insertIntoAlexaDB( String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO alexa(data)VALUES('" + data + "');";
alexadb.execSQL(query);
return true;
}
}
public boolean insertIntoActivityDB(String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO activity(data)VALUES('" + data + "');";
activitydb.execSQL(query);
return true;
}
}
}
Is this happening only when you select the last tab? Take a look at the offscreen page limit parameter: basically you can set the number of pages to retain in memory when you scroll the ViewPager. In your case, an offscreen page limit of 2 should be enough to always keep all the pages in memory.
I read data via Bluetooth from a sensor. I created a DataReceiverClass which creates objects with the attributes I need, it looks like this:
public class DataReceiverClass{
public int heartRate;
public int heartBeatNo;
public long distance;
public long speed;
public long strides;
public DataReceiverClass(int heartRate, int heartBeatNo,long distance, long speed, long strides) {
this.heartRate = heartRate;
this.heartBeatNo = heartBeatNo;
this.distance = distance;
this.speed = speed;
this.strides = strides;
}
public int getHeartRate() {
return heartRate;
}
public void setHeartRate(int heartRate) {
this.heartRate = heartRate;
}
public int getHeartBeatNo() {
return heartBeatNo;
}
public void setHeartBeatNo(int heartBeatNo) {
this.heartBeatNo = heartBeatNo;
}
public long getDistance() {
return distance;
}
public void setDistance(long distance) {
this.distance = distance;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public long getStrides() {
return strides;
}
public void setStrides(long strides) {
this.strides = strides;
}
}
And this is the class where I call it. I used a method called getInfo(). I must save around 100 objects of this type somewhere and after that to insert them into a SQLite database(with something like bulk insert I guess).
Here is my main class code. Does anybody know how to do this?
public class hxmDemo extends Activity {
private static final String TAG = "hxmDemo";
private TextView mTitle;
private TextView mStatus;
private String mHxMName = null;
private String mHxMAddress = null;
private BluetoothAdapter mBluetoothAdapter = null;
private HxmService mHxmService = null;
private ArrayList<DataReceiverClass> dataReceiverList = new ArrayList<DataReceiverClass>();
private void connectToHxm() {
//connection stuff
}
private boolean getFirstConnectedHxm() {
//connection stuff
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// other stuff
}
#Override
public void onStart() {
super.onStart();
//onStart() stuff
}
#Override
public synchronized void onResume() {
super.onResume();
//resume stuff
}
private void setupHrm() {
}
#Override
public synchronized void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case R.string.HXM_SERVICE_MSG_STATE:
Log.d(TAG, "handleMessage(): MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case R.string.HXM_SERVICE_CONNECTED:
if ((mStatus != null) && (mHxMName != null)) {
mStatus.setText(R.string.connectedTo);
mStatus.append(mHxMName);
}
break;
case R.string.HXM_SERVICE_CONNECTING:
mStatus.setText(R.string.connecting);
break;
case R.string.HXM_SERVICE_RESTING:
if (mStatus != null ) {
mStatus.setText(R.string.notConnected);
}
break;
}
break;
case R.string.HXM_SERVICE_MSG_READ: {
byte[] readBuf = (byte[]) msg.obj;
HrmReading hrm = new HrmReading( readBuf );
hrm.displayRaw();
dataReceiverList.add(hrm.getInfo());
break;
}
case R.string.HXM_SERVICE_MSG_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(null),Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// ...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// ...
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// ...
}
public class HrmReading {
// reading the 5 info from the sensor: heartRate,heartBeatNumber,distance,speed,strides
}
private DataReceiverClass getInfo(){
DataReceiverClass dataReceiverClass = new DataReceiverClass(heartRate,heartBeatNumber,distance,speed,strides);
return dataReceiverClass;
}
private void displayRaw() {
display ( R.id.heartRate, (int)heartRate );
display ( R.id.heartBeatNumber, (int)heartBeatNumber );
display ( R.id.distance, distance );
display ( R.id.speed, speed );
display ( R.id.strides, (int)strides );
}
private DataReceiverClass getInfo(){
DataReceiverClass dataReceiverClass = new DataReceiverClass(heartRate,heartBeatNumber,distance,speed,strides);
return dataReceiverClass;
}
}
Gson gson = new Gson();
String backUpData = gson.toJson(dataReceiverClass,DataReceiverClass.class);
After this you can insert this String straight into the db.
I have I think simple problem which I can't fix on my own. In the code below I need to set the loudBars variable to the other class. I made the setLoudBars() but it just doesn't work. Anyone sees any solution in this?
public class DrumActivity extends Activity {
private final short minBpm = 40;
private final short maxBpm = 208;
private short bpm = 100;
private short noteValue = 4;
private short beats = 4;
private short volume;
private short initialVolume;
private double beatSound = 2440;
private double sound = 6440;
private AudioManager audio;
private MetronomeAsyncTask metroTask;
private Button plusButton;
private Button minusButton;
private TextView currentBeat;
private Handler mHandler;
private int loudBars = 2;
private short silentBars = 1;
// have in mind that: http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler
// in this case we should be fine as no delayed messages are queued
private Handler getHandler() {
return new Handler() {
#Override
public void handleMessage(Message msg) {
String message = (String)msg.obj;
if(message.equals("1")) {
currentBeat.setTextColor(Color.GREEN);
}else {
currentBeat.setTextColor(getResources().getColor(R.color.yellow));
}
currentBeat.setText(message);
}
};
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drum);
metroTask = new MetronomeAsyncTask();
/* Set values and listeners to buttons and stuff */
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
TextView eSilentBars = (TextView) findViewById(R.id.eSilentBars);
Button minusLoud = (Button) findViewById(R.id.lbminus);
minusLoud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loudBars--;
if(loudBars < 1)
loudBars = 1;
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
metroTask.setLoudBars(loudBars);
}
});
Button plusLoud = (Button) findViewById(R.id.lbplus);
plusLoud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loudBars++;
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
metroTask.setLoudBars(loudBars);
}
});
Button minusSilent = (Button) findViewById(R.id.sbminus);
Button plusSilent = (Button) findViewById(R.id.sbplus);
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
TextView timeSignatureText = (TextView) findViewById(R.id.timesignature);
timeSignatureText.setText(""+beats+"/"+noteValue);
plusButton = (Button) findViewById(R.id.plus);
plusButton.setOnLongClickListener(plusListener);
minusButton = (Button) findViewById(R.id.minus);
minusButton.setOnLongClickListener(minusListener);
currentBeat = (TextView) findViewById(R.id.currentBeat);
currentBeat.setTextColor(Color.GREEN);
Spinner beatSpinner = (Spinner) findViewById(R.id.beatspinner);
ArrayAdapter<Beats> arrayBeats =
new ArrayAdapter<Beats>(this,
android.R.layout.simple_spinner_item, Beats.values());
beatSpinner.setAdapter(arrayBeats);
beatSpinner.setSelection(Beats.four.ordinal());
arrayBeats.setDropDownViewResource(R.layout.spinner_dropdown);
beatSpinner.setOnItemSelectedListener(beatsSpinnerListener);
Spinner noteValuesdSpinner = (Spinner) findViewById(R.id.notespinner);
ArrayAdapter<NoteValues> noteValues =
new ArrayAdapter<NoteValues>(this,
android.R.layout.simple_spinner_item, NoteValues.values());
noteValuesdSpinner.setAdapter(noteValues);
noteValues.setDropDownViewResource(R.layout.spinner_dropdown);
noteValuesdSpinner.setOnItemSelectedListener(noteValueSpinnerListener);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
initialVolume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
volume = initialVolume;
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volumebar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumebar.setProgress(volume);
volumebar.setOnSeekBarChangeListener(volumeListener);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public synchronized void onStartStopClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
if(buttonText.equalsIgnoreCase("start")) {
button.setText(R.string.stop);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
metroTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
else
metroTask.execute();
} else {
button.setText(R.string.start);
metroTask.stop();
metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
}
}
private void maxBpmGuard() {
if(bpm >= maxBpm) {
plusButton.setEnabled(false);
plusButton.setPressed(false);
} else if(!minusButton.isEnabled() && bpm>minBpm) {
minusButton.setEnabled(true);
}
}
public void onPlusClick(View view) {
bpm++;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
}
private OnLongClickListener plusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
bpm+=20;
if(bpm >= maxBpm)
bpm = maxBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
return true;
}
};
private void minBpmGuard() {
if(bpm <= minBpm) {
minusButton.setEnabled(false);
minusButton.setPressed(false);
} else if(!plusButton.isEnabled() && bpm<maxBpm) {
plusButton.setEnabled(true);
}
}
public void onMinusClick(View view) {
bpm--;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
}
private OnLongClickListener minusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
bpm-=20;
if(bpm <= minBpm)
bpm = minBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
return true;
}
};
private OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
volume = (short) progress;
audio.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener beatsSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Beats beat = (Beats) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beat+"/"+noteValue);
metroTask.setBeat(beat.getNum());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener noteValueSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
NoteValues noteValue = (NoteValues) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beats+"/"+noteValue);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
public boolean onKeyUp(int keycode, KeyEvent e) {
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
switch(keycode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
volumebar.setProgress(volume);
break;
}
return super.onKeyUp(keycode, e);
}
public void onBackPressed() {
metroTask.stop();
// metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
audio.setStreamVolume(AudioManager.STREAM_MUSIC, initialVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
finish();
}
private class MetronomeAsyncTask extends AsyncTask<Void,Void,String> {
Metronome metronome;
MetronomeAsyncTask() {
mHandler = getHandler();
metronome = new Metronome(mHandler);
}
protected String doInBackground(Void... params) {
metronome.setBeat(beats);
metronome.setNoteValue(noteValue);
metronome.setBpm(bpm);
metronome.setBeatSound(beatSound);
metronome.setSound(sound);
metronome.setLoudBars(loudBars);
metronome.play();
return null;
}
public void stop() {
metronome.stop();
metronome = null;
}
public void setBpm(short bpm) {
metronome.setBpm(bpm);
metronome.calcSilence();
}
public void setBeat(short beat) {
if(metronome != null)
metronome.setBeat(beat);
}
public void setLoudBars(int loudBars) {
if(metronome != null)
metronome.setLoudBars(loudBars);
}
}
}
My Activity is named BlacklistAddActivity.
UI element: EditText editText, Button btn1. When I click btn1, it will launch contact list activity and I can pick a contact from the contact list. Then send the contact info back to BlacklistAddActivity, and set the contact's name to the text1 by editText.setText(contact.name).
The problem is, sometimes, in contact list, if I do some operations: enter dialer from recent applicaton window(long press home key), and make a call etc... As we know, the android will check memory to decide destroying the activity stack or not. If memory is low, it will destroy the background activities, including BlacklistActivity.
Now, resume to contact list and pick a contact, resume to BlacklistActivity, it will be recreated. I can get contact's info correctly at onActivityResult(). Then, editText.setText(contact.name). Strange thing is: the editText shown on UI is still empty.
The following is my code: (not completely)
public class BlacklistAddActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
static final boolean DBG = true;
private static final String TAG = "BlacklistAddActivity";
private static final String KEY_MATCH_CRITERIA = "match_criteria";
private SharedPreferences mSharedPreferences;
private ListPreference mCriteria;
private static final int CONTACT_ITEM = 0;
private static final int LOGS_ITEM = 1;
private static final String NUM_PROJECTION[] = { Phone.DISPLAY_NAME, Phone.NUMBER };
protected static final Intent CONTACT_IMPORT_INTENT;
static {
CONTACT_IMPORT_INTENT = new Intent(Intent.ACTION_GET_CONTENT);
CONTACT_IMPORT_INTENT.setType(Phone.CONTENT_ITEM_TYPE);
}
private Context mContext;
private EditText editText;
private ImageButton searchButton;
private TwSoftkeyItem mLeftSoftkey, mRightSoftkey;
private AlertDialog mSearchDialog = null;
private InputMethodManager imm;
private boolean updateMode;
private String mNumber;
private int mMatchCriteria;
#Override
protected void onCreate(Bundle savedInstanceState) {
initTitle();
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate()");
setContentView(R.layout.blacklist_number_layout);
addPreferencesFromResource(R.xml.blacklist_add_num_prefs);
mSharedPreferences = getPreferenceScreen().getSharedPreferences();
mContext = getBaseContext();
mCriteria = (ListPreference) findPreference(KEY_MATCH_CRITERIA);
editText = (EditText) findViewById(R.id.edit_text);
editText.requestFocus();
searchButton = (ImageButton) findViewById(R.id.search_button);
mLeftSoftkey = (TwSoftkeyItem) findViewById(R.id.skleft);
mRightSoftkey = (TwSoftkeyItem) findViewById(R.id.skright);
initValue();
initEvent();
imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
}
private void initTitle() {
String str = getIntent().getStringExtra("FROM");
if (str != null) {
if (DBG) Log.i(TAG, "initTitle() => from: " + str);
if (str.equals("msg")) {
setTitle(R.string.list_msg_block_num);
} else {
setTitle(R.string.list_call_block_num);
}
}
}
private void initValue() {
updateMode = getIntent().getBooleanExtra("UPDATE_MODE", false);
Log.i(TAG, "the updatemode is: "+ updateMode);
if (updateMode == true) { //from Edit
mNumber = getIntent().getStringExtra("NUMBER");
mMatchCriteria = getIntent().getIntExtra("CRITERIA", 0);
editText.setText(mNumber);
editText.setSelection(mNumber.length());
mCriteria.setValueIndex(mMatchCriteria);
mCriteria.setSummary(mCriteria.getEntry());
} else { // from Add
mCriteria.setValueIndex(0);
mCriteria.setSummary(mCriteria.getEntry());
}
}
private void initEvent() {
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDialogSearch();
}
});
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean focused) {
if (focused == true) {
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
} else {
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
});
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_UP) {
editText.requestFocus();
return true;
}
return false;
}
});
mLeftSoftkey.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NUMBER", editText.getText().toString());
intent.putExtra("CRITERIA", mCriteria.findIndexOfValue(mCriteria.getValue()));
setResult(RESULT_OK, intent);
finish();
}
});
mRightSoftkey.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED, null);
finish();
}
});
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
if(DBG){
if(null != editText)
Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
}
super.onRestoreInstanceState(savedInstanceState);
if(DBG){
if(null != editText)
Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
}
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
if(null != editText)
if (DBG) Log.d(TAG, "onResume() Edit Text is: "+editText.getText().toString());
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
mCriteria.setSummary(mCriteria.getEntry());
}
#Override
protected void onPause() {
super.onPause();
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
if (mSearchDialog != null) {
mSearchDialog.dismiss();
mSearchDialog = null;
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (DBG) Log.v(TAG, "onSharedPreferenceChanged(), key: " + key);
if (KEY_MATCH_CRITERIA.equals(key)) {
if (mCriteria.getEntry() == null) {
mCriteria.setValueIndex(0);
}
mCriteria.setValue(sharedPreferences.getString(key, mCriteria.getEntry().toString()));
mCriteria.setSummary(mCriteria.getEntry());
if (DBG) Log.v(TAG, "setValue: " + mCriteria.getEntry().toString());
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
System.out.println("DONE");
break;
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String output = "";
switch (requestCode) {
case CONTACT_ITEM:
if (resultCode != RESULT_OK) {
Log.e(TAG, "onActivityResult() => canceled");
} else {
Cursor cursor = getContentResolver().query(data.getData(), NUM_PROJECTION, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
output = cursor.getString(1);
if (DBG) Log.d(TAG, "onActivityResult() => contact output: " + output);
if (Utils.isValidNum(mContext, output)) {
editText.setText(output);
if (DBG) Log.d(TAG, "onActivityResult() Edit Text is: "+editText.getText().toString());
}
}
cursor.close();
}
}
break;
case LOGS_ITEM:
if (resultCode == RESULT_OK) {
output = data.getStringExtra("NUMBER");
if (DBG) Log.d(TAG, "onActivityResult() => logs output: " + output);
if (Utils.isValidNum(mContext, output)) {
editText.setText(output);
} else {
output = null;
Utils.displayToast(mContext, getString(R.string.vip_msg_wrong_number));
}
}
break;
}
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
if (output != null && output.length() > 0) {
editText.requestFocus();
editText.setSelection(output.length());
}
}
private void alertDialogSearch() {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle(R.string.title_search).setItems(R.array.dialog_search, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case CONTACT_ITEM:
startActivityForResult(CONTACT_IMPORT_INTENT, CONTACT_ITEM);
break;
case LOGS_ITEM:
intent = new Intent("contacts.com.sec.android.app.dialertab.calllog.LogsListActivity");
intent.putExtra("OPTION", 1);
startActivityForResult(intent, LOGS_ITEM);
break;
}
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
mSearchDialog = ad.show();
}
}
Android does not automatically backup any data on your Activity when it gets destroyed. You have to manually back your data up before it gets destroyed and restore it when your Activity is recreated.
To backup your data, you must override this method. (It will be called before your activity gets destroyed.)
#Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("key", value); //save your data in key-value pair
}
To restore your data, you must override this method. (It will be called before your activity resumes.)
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
value = savedInstanceState.getString("key"); //retrieve your data using its corresponding key
}
if your text is not set/displayed correctly you should take a close look at your onCreate(), onResume() and onRestoreInstanceState() implementation.
so the answer from arci is what i would also answer in this case.
you say it is working the first time and also working if the Activity will not get killed. But when the Activity got killed and recreated it is not working. This sounds like you work on the wrong reference at some point.Especially when you use Listeners this can happen easily
You should go into debug mode and check your Activity and EditText instance (via memory adress) are the same/correct every time you access it.
I don't realy see the problem with your code but it has to be something like this.
Note: everytime you use startActivity(), go into landscape/portrait mode or something other calling onCreate() you may get a new Activity instance.
Note II: everytime onCreate() is called you get most likely call setContentView() what ends up in getting a newly inflated/created view. this means your EditText and other Views will be a new instance.