save state of switchview - android

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

Related

How to make the app go to another page if it is not run by first time

I have RegisterPage and LoginPage. When the app is run, it will check whether the app is first time run or not in RegisterPage. If it is first time run and the save button is not clicked, it will in RegisterPage. If it is run second times but the save button is never clicked, it will remain in RegisterPage too. Otherwise it will go to LoginPage.
Here my updated code
Register
appGetFirstTimeRun();
boolean clicked=false;
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked=true;
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences.edit().putInt("app_second_time",
appCurrentBuildVersion).apply();
String name = editTextName.getText().toString();
String pass = editTextPassword.getText().toString();
String confirm = editTextConfirm.getText().toString();
if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) {
Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show();
}
else
{
insertData(name, pass, imageUri); // insert to SQLite
Intent intent = new Intent(MainActivity.this, AddMonthlyExpenses.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
});
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
if (appLastBuildVersion == appCurrentBuildVersion && clicked) {
Intent intent = new Intent(MainActivity.this,LoginPage.class);
startActivity(intent);
return 1;
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show();
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
The problem is when I click the save button and exit from the app. When I run the app again it still in the RegisterPage, not in LoginPage.
Check button click after inserting data into SQLite, So you can confirm that your data has successfully saved and you can proceed to next screen.
Find my comments in below code and edit your code:-
public class Register extends AppCompatActivity {
Button buttonSave;
boolean clicked=false;//remove this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
appGetFirstTimeRun();//call this method here
buttonSave=(Button)findViewById(R.id.button);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked=true;//remove this
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences.edit().putInt("app_second_time", appCurrentBuildVersion).apply();
String name = editTextName.getText().toString();
String pass = editTextPassword.getText().toString();
String confirm = editTextConfirm.getText().toString();
if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) {
Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show();
}
else
{
insertData(name, pass, imageUri); // insert to SQLite
appPreferences.edit().putBoolean("btn_clicked", true).apply();//add this line
Intent intent = new Intent(Register.this, AddMonthlyExpenses.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
});
}
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
boolean is_btn_click=appPreferences.getBoolean("btn_clicked",false);//add this line
if ((appLastBuildVersion == appCurrentBuildVersion) && is_btn_click) { //edit this line like this
Intent intent = new Intent(Register.this,LoginPage.class);
startActivity(intent);
return 1;
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show();
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
}
you are depending on SharedPreferences as well as on clicked variable, you can depend on SharePreferences but not on variable because on each run you are setting clicked value to false.
1) Save current version in preference when button is clicked
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
2) save clicked value in preference when button is clicked
appPreferences.edit().putBoolean("clicked",
true).apply();
Now inside your appGetFirstTimeRun() fetch the value of version and clicked from SharedPreferences
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
boolean clicked = appPreferences.getBoolean("clicked", false);
You also need to change the shared preferences value on click of save button. Then only next time when you open the app appGetFirstTimeRun method will load the Login page.
In you btnSave click listener where you are starting intent for activity just before startActivity add this code
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
in start of onCreate(); method, call checkStages();
in end of buttonSave.onClick() method, call Prefs.putStage(this, 1); followed by checkStages();
/*Prefs.getStage(this) default value is 0*/
public void checkStages() {
switch(Prefs.getStage(this)) {
case 1: //Login Page
startActivity(new Intent(this, LoginPage.class));
finish();
break;
default:
break;
}
}
This is the sample Android Application Template I use, to write any of my Android App.
You can get the Prefs class from this project
add this code to your splash screen
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", false);
if (!isFirstRun) {
startActivity(new Intent(context,RegirstorActivity.class));
}else{
startActivity(new Intent(context,LoginActivty.class));
}
so basically it will decide Is it first time (user registered) or not, after registration update the SharedPreferences
your are using click variable to identify if button is clicked or not but when you exist from the app and again then click value reset to false so instead of saving value in click variable you can use shared preference to save value true or false on button click and get value from shared preference to check
on click of save button
appPreferences.edit().putInt("app_second_time",
appCurrentBuildVersion).apply();
Try using following custom getter and setter method.
private static SharedPreferences getInstance(Context context) {
context.getSharedPreferences("MY_APP", Context.MODE_PRIVATE);
return sharedPreferences;
}
public boolean getAppStatus(Context context) {
return getInstance(context).getString("FIRST_TIME", false);
}
public void setAppStatus(Context context, boolean status) {
getInstance(context).edit().putString("FIRST_TIME", status).commit();
}
Now, When for the first time when you call getAppStatus() or in case where user haven't clicked save button even once. It will return false. You can update the value of "FIRST_TIME" variable when the user clicks on save button to true. Thus validating, whether user has interacted with register page or not.
#Override
public void onClick(View v) {
if(v.getId()==R.id.save_button)
setAppStatus(context,true);
}
I think this may be the answer. on your code clicked boolean variable is not stored on shared preferences but you are checking condition inside appGetFirstTimeRun() (button may not be clicked at second launch, but your condition needs to be true) so change your code by
Adding this line appPreferences.edit().putBoolean("first_run", true).apply();on buttonSave clicklistener and then add this line clicked = appPreferences.getBoolean("first_run", false);on appGetFirstTimeRun() function
and the complete code would be.
appGetFirstTimeRun();
boolean clicked=false;
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences = appPreferences.edit().putBoolean("first_run",
true).apply(); //***Add this ****
appPreferences.edit().putInt("app_second_time",
appCurrentBuildVersion).apply();
String name = editTextName.getText().toString();
String pass = editTextPassword.getText().toString();
String confirm = editTextConfirm.getText().toString();
if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) {
Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show();
}
else
{
insertData(name, pass, imageUri); // insert to SQLite
Intent intent = new Intent(MainActivity.this, AddMonthlyExpenses.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
});
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
clicked = appPreferences.getBoolean("first_run", false); //*** Add this ***
if (appLastBuildVersion == appCurrentBuildVersion && clicked) {
Intent intent = new Intent(MainActivity.this,LoginPage.class);
startActivity(intent);
return 1;
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show();
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
//Use shared preference to save.
SharedPreferences preferedName=getSharedPreferences("firstrun", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferedName.edit();
editor.putboolean("firstrun",value);
editor.apply();
editor.commit();
//and to retrive.
SharedPreferences preferedName=getSharedPreferences("firstrun", Activity.MODE_PRIVATE);
boolean rstate =preferedName.getString("firstrun",false);
check if "rstste" is false show register page else show the login page.

How can save state into SharedPreferences in Android

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.

Null pointer exception on the following code

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)

how to start an inapp billing activity

I got a code from internet for inapp billing and I want to use that code in my application but I am getting an error that when I click the the buy button of my app it redirect me to the another layout of the code where I get an another Button and after that click my in-app billing starts.
I want that when I click my buy button then the in-app billing should start. without any another button clicks.
This is the code from where the the in-app billing start.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSP = PreferenceManager.getDefaultSharedPreferences(this);
Log.i("BillingService", "Starting");
setContentView(R.layout.contact_market);
mContext = this;
mPurchaseButton = (Button) findViewById(R.id.main_purchase_yes);
mPurchaseButton.setOnClickListener(this);
mPreview = (TextView) findViewById(R.id.chakkde);
startService(new Intent(mContext, BillingService.class));
BillingHelper.setCompletedHandler(mTransactionHandler);
}
public Handler mTransactionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Log.i(TAG, "Transaction complete");
Log.i(TAG, "Transaction status: "
+ BillingHelper.latestPurchase.purchaseState);
Log.i(TAG, "Item purchased is: "
+ BillingHelper.latestPurchase.productId);
if (BillingHelper.latestPurchase.isPurchased()) {
showItem();
}
};
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_purchase_yes:
if (BillingHelper.isBillingSupported()) {
BillingHelper.requestPurchase(mContext,
"android.test.purchased");
} else {
Log.i(TAG, "Can't purchase on this device");
mPurchaseButton.setEnabled(false);
}
break;
default:
Log.i(TAG, "default. ID: " + v.getId());
break;
}
}
private void showItem() {
mPreview.setVisibility(View.VISIBLE);
SharedPreferences.Editor prefEditor = mSP.edit();
prefEditor.putBoolean(DroidSugarPreference.KEY_ENABLE,
true);
prefEditor.commit();
startActivity(new Intent(InAppMain.this, Setup.class));
InAppMain.this.finish();
}
#Override
protected void onPause() {
Log.i(TAG, "onPause())");
super.onPause();
}
#Override
protected void onDestroy() {
BillingHelper.stopService();
super.onDestroy();
}
}
this if from where I call the above class
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.gtask_button:
startActivity(new Intent(getActivity(), InAppMain.class));
default:
break;
}
but now i want that from case R.id.gtask_button: i should start the in-app billing activity that i was starting from R.id.main_purchase_yes.
thnx in advance...
From what i see, this is called when you click the button
BillingHelper.requestPurchase(mContext, "android.test.purchased");
So maybe thats where it changes your layout to something else...
Post the method so we can take a look.
EDIT:
Ok, here's the code
protected static void requestPurchase(Context activityContext, String itemId){
if (amIDead()) {
return;
}
Log.i(TAG, "requestPurchase()");
Bundle request = makeRequestBundle("REQUEST_PURCHASE");
request.putString("ITEM_ID", itemId);
try {
Bundle response = mService.sendBillingRequest(request);
//The RESPONSE_CODE key provides you with the status of the request
Integer responseCodeIndex = (Integer) response.get("RESPONSE_CODE");
//The PURCHASE_INTENT key provides you with a PendingIntent, which you can use to launch the checkout UI
PendingIntent pendingIntent = (PendingIntent) response.get("PURCHASE_INTENT");
//The REQUEST_ID key provides you with a unique request identifier for the request
Long requestIndentifier = (Long) response.get("REQUEST_ID");
Log.i(TAG, "current request is:" + requestIndentifier);
C.ResponseCode responseCode = C.ResponseCode.valueOf(responseCodeIndex);
Log.i(TAG, "REQUEST_PURCHASE Sync Response code: "+responseCode.toString());
startBuyPageActivity(pendingIntent, new Intent(), activityContext);
} catch (RemoteException e) {
Log.e(TAG, "Failed, internet error maybe", e);
Log.e(TAG, "Billing supported: "+isBillingSupported());
}
}
and we find the culprit -
startBuyPageActivity(pendingIntent, new Intent(), activityContext);

Splash screen when initializing, connecting and logging in

I am very new to Android and am a beginner programmer. I am making a prototype of an app that displays a slash screen, initializes, connects to a server (haven't worked on this yet), determines if login information is needed (if so goes to the LoginActivity), then logs in.
Right now this is a prototype so initialize, connect and login function just return true.
The trouble I am having is the the splash screen examples I have found on the web only have a wait in the thread. Also, in debug, when setContentView(R.layout.loading_screen) is called, it doesn't immediately load the screen.
I was wondering if someone could point me in the right direction.
public class LoadingScreenActivity extends Activity {
private Thread mLoadingScreenThread;
#Override
public void onCreate(Bundle savedInstanceState)
{
final LoadingScreenActivity loading_screen = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_screen);
mLoadingScreenThread = new Thread()
{
#Override
public void run(){
boolean loggedIn = false;
synchronized(this)
{
while(loggedIn == false)
{
if (initialize()) //Initialize
{
if (connectToServer()) //Connect to Server
{
//Check to see if we need login information or registration
if (needLogin())
{
//Load LoginActivity and have user Login
Intent intent = new Intent();
intent.setClass(loading_screen, LoginActivity.class);
startActivity(intent);
}
//Login to server
if (login())
{
loggedIn = true;
}
}
}
}
}
//We are initialized, connected and logged in
finish();
Intent intent = new Intent();
intent.setClass(loading_screen, UserMainActivity.class);
startActivity(intent);
stop();
}
};
mLoadingScreenThread.start();
}
//Determine if we need the user to provide login information
private boolean needLogin()
{
Toast toast = Toast.makeText(LoadingScreenActivity.this, "Checking for Login Info", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
waitForMilliseconds(5000);
return true;
}
//Initialize Application
private boolean initialize()
{
Toast toast = Toast.makeText(LoadingScreenActivity.this, "Inializing", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
waitForMilliseconds(5000);
return true;
}
//Connect Application to Server
private boolean connectToServer()
{
Toast toast = Toast.makeText(LoadingScreenActivity.this, "Connecting to Server", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
waitForMilliseconds(5000);
return true;
}
private boolean login() {
Toast toast = Toast.makeText(LoadingScreenActivity.this, "Logging In", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
waitForMilliseconds(5000);
return true;
}
private void waitForMilliseconds(int milliseconds)
{
Timer timer = new Timer();
try {
timer.wait(milliseconds);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm not 100% sure what your question is, but it seems as if you've mixed two concepts.
A splash screen is simply an image/animation on a timer (or while something is loading).
Having a login-functionality doesn't have any obvious connection to the concept of a splash screen as far as I can tell. You simply want a normal activity which takes some input (login info) and then processes it (checks a database for example).
And when you say that it doesn't load the image immediately, do you mean that it lags somehow, or simply stays black for a while. You might need a loading(splash)screen separate from the login activity to handle that.

Categories

Resources