I have a weird problem. When i click the first time on the checkbox it works, but when i uncheck and check again, the image won`t show.
Please help.
private void ratedialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Rate it!");
dialog.setCancelable(true);
dialog.show();
seekbar = (SeekBar) dialog.findViewById(R.id.rate_seekbar);
button_done = (Button) dialog.findViewById(R.id.button_done);
seekbar_result = (TextView) dialog.findViewById(R.id.seekbar_result);
checkBox_seen = (CheckBox) dialog.findViewById(R.id.checkBox_seen);
button_done.setOnClickListener(EditActivity.this);
seekbar.setOnSeekBarChangeListener(EditActivity.this);
checkBox_seen.setOnCheckedChangeListener(EditActivity.this);
seekbar.setProgress(rate);
}
Listener:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e(TAG, isChecked+"");
if (isChecked) {
//seen = true;
checkBox_seen.setChecked(true);
Log.e(TAG, "Second time " + isChecked + "");
image_seen.setImageResource(R.drawable.seen);
} else {
// seen = false;
checkBox_seen.setChecked(false);
Log.e(TAG, "Third time" + isChecked + "");
image_seen.setVisibility(View.INVISIBLE);
}
}
change your code to
if (isChecked) {
//seen = true;
checkBox_seen.setChecked(true);
Log.e(TAG, "Second time " + isChecked + "");
image_seen.setVisibility(View.VISIBLE);
image_seen.setImageResource(R.drawable.seen);
} else {
// seen = false;
checkBox_seen.setChecked(false);
Log.e(TAG, "Third time" + isChecked + "");
image_seen.setVisibility(View.INVISIBLE);
}
In Else condition you change the visiblity to INVISIBLE so it become invisible when your if condition runs you do not change the Visiblity to visible so that's why you image not shows.
Problem is you are not changing the visibility in checked state setting the CheckBoxinstance checked again.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e(TAG, isChecked+"");
if (isChecked) {
//seen = true;
**checkBox_seen.setChecked(true);// remove this line**
Log.e(TAG, "Second time " + isChecked + "");
**image_seen.setVisibility(View.VISIBLE);//Add this line**
image_seen.setImageResource(R.drawable.seen);//Move this line to `ratedialog()`method.
} else {
// seen = false;
**checkBox_seen.setChecked(false);//Remove this line**
Log.e(TAG, "Third time" + isChecked + "");
image_seen.setVisibility(View.INVISIBLE);
}
}
The simple code will look like
if (isChecked) {
image_seen.setVisibility(View.VISIBLE);
} else {
image_seen.setVisibility(View.INVISIBLE);
}
Related
In my program, I have a switch, a text view and an accessibility service running.
When the switch is turned ON, the second screen opens from where I need to switch on my service and by doing this, the text in the first screen should change to ON(the text should change to ON only if the service is enabled).
But the problem is that the text in the first screen is changing to ON, as soon as I switch ON the switch, but before I enable my service from the second screen.
This is my code for the switch:
private void setSwitchAndText(){
boolean ifON;
ifON = isAccessibilitySettingsOn(getApplicationContext());
if(ifON) {
mySwitch.setChecked(true);
} else {
mySwitch.setChecked(false);
}
myTextview.setText(ifON ? R.string.on : R.string.off);
}
and this is how I check whether the service is enable or not:
private boolean isAccessibilitySettingsOn(Context mContext) {
int accessibilityEnabled = 0;
final String service = getPackageName() + "/" + myService.class.getCanonicalName();
boolean accessibilityFound = false;
try {
accessibilityEnabled = Settings.Secure.getInt(this.getContentResolver(),android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
Log.d(LOGTAG, "ACCESSIBILITY: " + accessibilityEnabled);
} catch (Settings.SettingNotFoundException e) {
Log.d(LOGTAG, "Error finding setting, default accessibility to not found: " + e.getMessage());
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
Log.d(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
String settingValue = Settings.Secure.getString(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
Log.d(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service);
if (accessibilityService.equalsIgnoreCase(service)) {
Log.d(TAG, "We've found the correct setting - accessibility is switched on!");
return true;
}
}
}
} else {
Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
}
return accessibilityFound;
}
and this is the relevant code in the onCreate:
myTextview = (TextView) findViewById(R.id.my_text);
mySwitch = (Switch) findViewById(R.id.my_switch);
mySwitch.setChecked(false);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
myTextview.setText(isChecked ? R.string.on : R.string.off);
if (isChecked) {
askToStartAccessibilityService(getResources().getString(R.string.on));
} else {
askToStartAccessibilityService(getResources().getString(R.string.off));
}
}
});
The way your detecting active accessibility services is pretty intense and there's no reason for this. Try this code instead:
AccessibilityManager accessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> serviceInfoList = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_SPOKEN);
return (serviceInfoList.size() > 0);
I want save isClickedState for imageButton, if clicked on this imageButton save this state and change color and when not clicked show default color and save false state!
I write below codes, but when click on button not save this state and when back to other activity and go to again this activity see not save state!
MyActivityCodes:
private ShineButton postShow_favPost;
private String favData = "FavPrefsList";
private Boolean favState;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);
bindActivity();
//Give Data
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}
mAppBarLayout.addOnOffsetChangedListener(this);
//// Save Fav state
final SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);
final SharedPreferences.Editor editor = saveFavPrefs.edit();
favState = saveFavPrefs.getBoolean("isChecked", false);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.po_image1);
postShow_favPost.init(this);
postShow_favPost.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (favState == true) {
editor.putBoolean("isChecked", true);
editor.commit();
Toast.makeText(context, "Checked True", Toast.LENGTH_SHORT).show();
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
}
});
How can i fix this issue?
Make the following changes to your code. In the else part make the value false again. Its important because if your isChecked value was previously true, then the else part will be able to make it false:
I changed if(favState == true) to if(checked ==true)
if (checked == true) {
editor.putBoolean("isChecked", true);
editor.commit();
Toast.makeText(context, "Checked True", Toast.LENGTH_SHORT).show();
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
Boolean can be check by if(favState) not need to do this if(favState == true) boolean itself is true or false.
and save alternative state as i commented in else section.
if (favState) {
editor.putBoolean("isChecked", checked);
editor.commit();
Toast.makeText(context, "Checked True", Toast.LENGTH_SHORT).show();
} else {
//editor.putBoolean("isChecked", False);
//editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
If you haven't defined default value of checked as true then you need do following as default value of boolean is false:
//change this
editor.putBoolean("isChecked", checked);
//to this
editor.putBoolean("isChecked", true);
Let me know if this changes anything for you.
I want to use a switch: http://developer.android.com/guide/topics/ui/controls/togglebutton.html
to toggle something like Bluetooth which needs a prompt. The problem is when the user denies the action. If it's done just as shown in the example, the toggle will shown "on" even though the Bluetooth device is turned off, because the user denied. Is there a way to make the switch only show "on" if the user accepts the prompt and otherwise stay at "off"?
this is what I am trying to use the switch for:
Switch toggler = (Switch) findViewById(R.id.switch2);
toggler.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
final Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivityForResult(discoverableIntent, DISCOVERABLE_REQUEST);
} else {
// The toggle is disabled
final Intent stopDiscoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
stopDiscoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3);
startActivityForResult(stopDiscoverableIntent,DISCOVERABLE_REQUEST);
}
}
});
public void onActivityResult(int req_code, int res_code, Intent data){
System.out.println("Prior Check: " + res_code);
if(req_code==REQUEST_ENABLE_BT){
if(res_code==RESULT_OK){
Toast.makeText(getBaseContext(),"Bluetooth is now turned ON",Toast.LENGTH_SHORT).show();
System.out.println("BT Req.: " + res_code);
}
if(res_code==RESULT_CANCELED){
Toast.makeText(getBaseContext(),"Bluetooth enable totally failed bru!",Toast.LENGTH_SHORT).show();
System.out.println("BT Req.: " + res_code);
}
}
else if(req_code==DISCOVERABLE_REQUEST){
if (res_code==1){
toggle = true;
Toast.makeText(getBaseContext(),"Infinite discoverability enabled",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
}
if(res_code==3){
toggle = false;
Toast.makeText(getBaseContext(),"Discover mode ending",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
}
if(res_code==RESULT_CANCELED && toggle == true){
Toast.makeText(getBaseContext(),"Discover mode ending denied",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
//Switch sw = (Switch) findViewById(R.id.switch2);
//sw.setChecked(false);
}
if(res_code==RESULT_CANCELED && toggle == false){
Toast.makeText(getBaseContext(),"Infinite discoverability denied",Toast.LENGTH_SHORT).show();
System.out.println("Disc. Req.: " + res_code);
//Switch sw = (Switch) findViewById(R.id.switch2);
//sw.setChecked(false);
}
}
}
Here once you press the switch you get a prompt for bluetooth, if you accept it does what it should do, but if I deny it still switches, which i would like it not to. I hope the question is more clear now.
You can use:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isEnabled())
{
//User accpeted keep toggle on or if off, programmatically turn on
}
else
{
//User rejected keep toggle off or if on, programmatically turn off
}
}
I am a beginer in android and java,can anybody help me to find out the reason of this error in my code plz???
serviceSwitch =(Switch) this.findViewById(R.id.switchservice);
serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
try{
if(isChecked){
arrayChecking();
Toast.makeText(getApplicationContext(), "set date n time ", Toast.LENGTH_LONG).show();
}
}
catch(Exception e){
Log.e("switchfailed",e.toString());
}
}
});
Code for arrayChecking
It checks the tbpreferenceArray is empty or not?,If it is empty it shows the toast,else it pass an intent to call background service in my app
public void arrayChecking(){
if(tbPreferenceArray.length>0){
Toast.makeText(getApplicationContext(), "Please Set the Time and Day", Toast.LENGTH_LONG).show();
serviceSwitch.setChecked(false);
}
else{
Intent i = new Intent(MainActivity.this, TimerService.class);
MainActivity.this.startService(i);
Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_LONG).show();
}
}
Shared Preference code
SharedPreferences prefs = getApplicationContext().getSharedPreferences("TogglePreference", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("tbPreferenceArray" +"_size", toggleButtonArray.length);
for(int i=0;i<toggleButtonArray.length;i++)
{
editor.putBoolean("tbPreferenceArray" + "_" + i, toggleButtonArray[i]);
}
editor.commit();
Toast.makeText(getApplicationContext(), "Your timetable is ok",Toast.LENGTH_LONG).show();
Please correct your code as follow:
if(tbPreferenceArray!= null && tbPreferenceArray.length>0)
In my app i have dailog with edittext and submit button, if the edittext is empty
i gave a toast message "please enter something" ..my code is below
Button reviewPost = (Button) dialog.findViewById(R.id.submit);
reviewPost.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
v.setEnabled(false);
EditText ratingComment = (EditText) dialog
.findViewById(R.id.reviewcomment);
String comment = ratingComment.getText().toString();
String postStatus = "Y";
if (spinner.getSelectedItemPosition() > 0) {
postStatus = "N";
}
RadioGroup rating = (RadioGroup) dialog
.findViewById(R.id.customrating);
int radioButtonID = rating.getCheckedRadioButtonId();
View radioButton = rating.findViewById(radioButtonID);
int ratingNo = rating.indexOfChild(radioButton);
String ratingValue = (ratingNo + 1) + "";
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
But even if the edittext is empty it is submitting which should not happen.i am checking the condition as follows but its not working
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
use comment.trim().equals("") instead of comment.equalsIgnoreCase("")
or put a check on comment string length that it should exceed the minimum characters.
use
if(comment != null && !comment.isEmpty())
You can used this.
if(comment != null && !comment.isEmpty() && comment.length()!=0){
//your task
}else{
//give some message
}
Solved with below code..the problem is with the v.setEnabled(false);...i moved it into the if condition
if (comment != null && !comment.equalsIgnoreCase("")){
v.setEnabled(false);
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}