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)
Related
I’m using Shared Preferences to store user data and set Login Status in a web view app for eCommerce Website. The user can either login via Login URL or at the Checkout Page. The issue I’m facing I can’t set Login status to “True” after the user successfully logged in so I can retrieve the username it keeps showing as "False".
EDIT: After posting the question I was able to find part of the solution for the Login URL to set the status to true however the CARTURL isn't working. I defined isRedirected = true; and set the condition to get the right status.
I'm reposting the code after edit:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.e(TAG, "should override url loading" + url);
view.loadUrl(url);
isRedirected = true;
return true;
}
public void onPageFinished(WebView view, String url) {
//webView.setClickable(true);menuBtn.setClickable(true);cartImg.setClickable(true);logoImg.setClickable(true);
Log.e(TAG, "on page finished" + url);
Log.e(TAG, "is logged in==" + isLoggedin);
isRedirected = true;
String isLoggedin = "false";
if(url.equals(Constants.ACCOUNTURL) && isRedirected && isLoggedin.equals("false")) {
Log.e(TAG, "reload");
//webView.loadUrl(Constants.ACCOUNTEDITURL);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("isLogedin", "true");
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have signed in", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
};
if(url.equals(Constants.CARTURL) && isRedirected && isLoggedin.equals("false")) {
Log.e(TAG, "Cart Login");
//webView.loadUrl(Constants.ACCOUNTEDITURL);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("isLogedin", "true");
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have signed in", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
};
//if(url.equals(Constants.LOGOUTURL) && isLoggedin.equals("true")) {
if(url.equals(Constants.LOGOUTURL)) {
Log.e(TAG, "logging out-----------------");
SharedPreferences pref = getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("isLogedin", "false");
//editor.clear();
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have logged out", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
//return;
}
if(isLoggedin.equals("true")) {
Log.e(TAG, "in get name-----------------");
mainView.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
//String getnamejs = "(document.getElementById('input-firstname').value);";
String getnamejs = "(document.getElementById('app_customer_name').innerHTML);";
mainView.loadUrl("javascript: window.CallToAnAndroidFunction.getUserName" + getnamejs);
}
Your help is highly appreciated, thank you in advanced.
Do you mean that the string variable isLoggedin is always false? could you mention where are you assigning the value for the variable isLoggedin.
Please try the below code, I have modified the putString with boolean.
boolean isLoggedin;
SharedPreferences pref =
getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.e(TAG, "should override url loading" + url);
view.loadUrl(url);
isRedirected = true;
return true;
}
public void onPageFinished(WebView view, String url) {
Log.e(TAG, "on page finished" + url);
isLoggedin = pref.getBoolean(“isLoggedin”, false);
if (url.equals(Constants.ACCOUNTURL) && url.equals(Constants.CARTURL) && !isLoggedin) {
Log.e(TAG, "reload");
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(“isLoggedin", true);
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have signed in", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Log.e(TAG, "in get name-----------------");
mainView.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
//String getnamejs = "(document.getElementById('input-firstname').value);";
String getnamejs = "(document.getElementById('app_customer_name')[0].innerHTML);";
mainView.loadUrl("javascript: window.CallToAnAndroidFunction.getUserName" + getnamejs);
}
//if(url.equals(Constants.LOGOUTURL) && isLoggedin) {
if (url.equals(Constants.LOGOUTURL)) {
Log.e(TAG, "logging out-----------------");
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLoggedin", false);
//editor.clear();
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have logged out", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
//return;
}
Let me know if that helps!
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 the value of shared preferences from one activity to another activity, like if my pin from pin_activity is set on, the pattern from another activity should be disabled, and show the Toast that "PinService is ON, You can't Make PatternService ON" and vice versa. i am not getting how to use shared preference values. Please help me out in doing this
here is my code for both activities.
pin_activity.java
s2 = (Switch) findViewById(R.id.switch2);
spref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
s2.setChecked(spref.getBoolean("SwitchButton", false));
s2.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("SwitchButton", s2.isChecked());
// editor.putString("switch_state", "value");
//switch_state=editor.putBoolean("SwitchButton", s2.isChecked());
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
Pattern_activity.java
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
s1.setChecked(sharedPreferences.getBoolean("toggleButton", false));
switch1= sharedPreferences.getBoolean("editor",s1.isChecked() );
if (switch1== true)
{
s1.setEnabled(false);
Toast.makeText(getApplicationContext(), "PinService is ON, You can't Make PatternService ON", Toast.LENGTH_SHORT).show();
}
else
{
s1.setEnabled(true);
}
s1.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
//switch1= sharedPreferences.getString("switch_state", null);
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
You need to use the same key for your setting.
In your example you use "SwitchButton" to read/write the state of the switch in pin_activity and "editor" to read (supposedly) that same value. Which cannot work.
So extract a key string to a constant like public static String PIN_STATE = "PIN_STATE";.
in pin_activity:
s2 = (Switch) findViewById(R.id.switch2);
spref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
s2.setChecked(spref.getBoolean(PIN_STATE, false));
s2.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean(PIN_STATE, s2.isChecked());
// editor.putString("switch_state", "value");
//switch_state=editor.putBoolean(PIN_STATE, s2.isChecked());
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
in Pattern_activity:
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
s1.setChecked(sharedPreferences.getBoolean("toggleButton", false));
switch1= sharedPreferences.getBoolean(PIN_STATE, s1.isChecked() );
if (switch1== true)
{
s1.setEnabled(false);
Toast.makeText(getApplicationContext(), "PinService is ON, You can't Make PatternService ON", Toast.LENGTH_SHORT).show();
}
else
{
s1.setEnabled(true);
}
And from that on you probably need to do something similar for PATTERN_STATE and in general straighten out you button states, as they seem a bit jumbled.
how to save toggle button state to database and if user edits then edited state should be saved to database in android.the following is my code it is working fine.but the problem is that when user edits to on it is in on state and green light displays on toggle button. and then user performs the required actions.when user again comes back to edit again it displays on only but no green light is visible.so it looks bad so please help me and following is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
db.close();
}
#Override
public void onBackPressed(){
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
slight=light.getText().toString();
salarm=alarm.getText().toString();
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
intent.putExtra("Daddress",pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}
}
You can use SharedPrefernce for saving the state of toggle button.
sharedpreferences = context.getSharedPreferences("Toggle_pref", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("button_state", "state");
editor.commit();
This is code for Toogle Button with saved state..
private SharedPreferences spref;
private ToggleButton tb;
private boolean on;
spref = getSharedPreferences("APP", MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.toogleButton);
on = spref.getBoolean("On", true); //default is true
if (on)
{
tb.setChecked(true);
} else
{
tb.setChecked(false);
}
tb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (tb.isChecked()) {
//Toast.makeText(MainActivity.this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
} else {
// Toast.makeText(MainActivity.this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor =spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
}
}
});
in the following way i done and my problem solved.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
Log.v("___EDIT CLASS____________", "__LIGHT TEXT_____________"+slight);
Log.v("_____EDIT CLASS_____________", "___ALARM TEXT____________"+salarm);
Log.v("___EDIT CLASS____________", "__LIGHT boolean_____________"+blight);
Log.v("_____EDIT CLASS_____________", "___ALARM boolean____________"+balarm);
// edittext.setText(val);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
Log.v("___________edittext", "_______________"+edittext.getText());
Log.v("__________address", "_______________"+pos);
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
if(slight.equalsIgnoreCase("on"))
{
light.setChecked(true);
}
else
{
light.setChecked(false);
}
if(salarm.equalsIgnoreCase("on"))
{
alarm.setChecked(true);
}
else
{
alarm.setChecked(false);
}
db.close();
}
#Override
public void onBackPressed(){
//saveData();
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
// slight=light.setClickable(true);
//salarm= String.valueOf(balarm);
Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______pos", "______UUID___________"+pos);
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
Log.v("___QUERY ", "_________________"+db.select(strSQL));
slight=light.getText().toString();
salarm=alarm.getText().toString();
Log.v("___EDIT CLASS____________", "__SLIGHT ___AFTER__________"+slight);
Log.v("_____EDIT CLASS_____________", "___SALARM ___AFTER_________"+salarm);
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
/*Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______cccccc", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
/* Log.v("______device_____text", "_______________"+c.getString(c.getColumnIndex("devicename")));
Log.v("___________edittext", "_______________"+edittext.getText().toString());
Log.v("_____ADDRESS______edittext", "_______________"+pos);
*/ Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
Log.v("_____edittext in intent________", "__________"+edittext.getText().toString());
intent.putExtra("Daddress",pos);
Log.v("_____edittext in intent________", "__________"+pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
/* Log.v("_______EDIT IN DB", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}
My application have a switchview. It used to lock some messages.It works fine, but the problem is in the state of switch..if i on the switch means message is locked, after i close the app and when i restart the app, its state changed to previous one, means message is unlocked.
I want to save state where i drag the switch earlier. Here is my code:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
try{
Database_SMS info = new Database_SMS(this);
String data = info.getData();
info.close();
Global.lock = true;
Toast.makeText(getApplicationContext(), "Message is locked", Toast.LENGTH_LONG).show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Message is not selected", Toast.LENGTH_LONG).show();
}
}
else {
Global.lock = false;
Toast.makeText(getApplicationContext(), "Message is unlocked", Toast.LENGTH_LONG).show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
}
}
Please help me.
You should use SharedPreferences for saving this type of information and you can lock/unlock messages in init time.
Storing value you can do something like this:
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
prefs.edit().putBoolean("value_name", true).commit();
And reading value:
boolean value = prefs.getBoolean("value_name", false);