Getting value from SharedPreferences - java

I am trying to get a saved value from an activity by this Settings.getMode(); Here is the Settings class :
public class Set extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private static String isNightMode;
Switch aSwitch;
Boolean mode;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = getSharedPreferences("xyz", MODE_PRIVATE);
isNightMode = sharedPreferences.getString("isNightMode", "no");
mode = sharedPreferences.getBoolean("mode", false);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set);
aSwitch = (Switch) findViewById(R.id.switch1);
aSwitch.setChecked(mode);
if (aSwitch.isChecked()) {
isNightMode = "yes";
} else {
isNightMode = "no";
}
aSwitch.setOnCheckedChangeListener(this);
}
public static String getMode() {
return isNightMode;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isNightMode = "yes";
mode = true;
SharedPreferences.Editor editor = getSharedPreferences("xyz", MODE_PRIVATE).edit();
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else {
isNightMode = "no";
mode = false;
SharedPreferences.Editor editor = getSharedPreferences("xyz", MODE_PRIVATE).edit();
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
When I change the value in Settings activity , the value is saved perfectly. But problem is , I am not getting the saved value when the app starts . When the app starts, the getMode() method returns null. There must be something wrong while getting saved value at the time of starting the app. I can't figure out the wrong.

1.you can use it MyApplication .
2.and call MyApplication.getMode(); in your Activity .
Try this .
public class MyApplication extends Application {
private static String isNightMode;
Boolean mode;
#Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = getSharedPreferences("xyz", MODE_PRIVATE);
isNightMode = sharedPreferences.getString("isNightMode", "no");
mode = sharedPreferences.getBoolean("mode", false);
}
public static String getMode() {
return isNightMode;
}
}
And add in the manifest
<application
android:name=".yourPackage.MyApplication"
... />

This modification might help you. Modification in onCreate() method:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // this - Activity
and
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); // this - Activity
if (isChecked) {
isNightMode = "yes";
mode = true;
} else {
isNightMode = "no";
mode = false;
}
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.apply();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}

Related

Android: How to save the best score in a game?

I am a beginner programmer and I create a game for android and I came across a problem that I want after finishing the game to show me the best score that I managed to achieve in playing this game I made a condition
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
of course I use sharedPreferences to save the best score here but this condition doesn't work at all and my sharedPreference takes any value even less than the last score
public class EndScreen extends AppCompatActivity {
TextView Levelwys,war;
Button GotoMenu;
int DOD,ODE,MNO,PIE,DZI,POT,SIL,LOG;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end_screen);
Levelwys = findViewById(R.id.textView15);
war = findViewById(R.id.textView19);
GotoMenu = findViewById(R.id.button);
sharedPreferences = getSharedPreferences("com.example.goodmath", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
Intent intent = getIntent();
int number = intent.getIntExtra(GameSingleActivity.LEVEL, 0);
DOD = intent.getIntExtra("DOD", 0);
ODE = intent.getIntExtra("ODE", 0);
MNO = intent.getIntExtra("MNO", 0);
PIE = intent.getIntExtra("PIE", 0);
DZI = intent.getIntExtra("DZI", 0);
POT = intent.getIntExtra("POT", 0);
SIL = intent.getIntExtra("SIL", 0);
LOG = intent.getIntExtra("LOG", 0);
Levelwys.setText(String.valueOf(number));
String test = String.valueOf(DOD);
Toast.makeText(getApplicationContext(), test, Toast.LENGTH_LONG).show();
Save();
GotoMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GotoMenu();
}
});
}
#Override
public void onBackPressed() {
}
void GotoMenu()
{
Intent intent1 = new Intent(this, MenuActivity.class);
startActivity(intent1);
}
void Save()
{
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}
}
}
You have typo in your if condition:
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
You have added extra semicolon at the end of this line. Because of this, the code below this condition was always called.
Delete this semicolon and everything should works fine:
if(DOD> sharedPreferences.getInt("DOD_SHA",0))
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}

shared preference not able to get data

I am trying to make promo code for my app when the user gives correct value in the EditText I will set a boolean value false and a number will be stored in shared preferences. But don't know why the value is not getting decremented and even if it decreases and even if I do it multiple times then only it moves from 30 to 29.
So I created a test app where I am setting the value in onClick what happens when the promo code is equal. So the decrement thing is when the user open the app the number will get decreased and stored back when the boolean value is false
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("ShowAd", false);
editor.putLong("daycounter", 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
SharedPreferences prefs = getSharedPreferences("apprater", 0);
SharedPreferences.Editor editor = prefs.edit();
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad > 0) {
editor.putLong("daycounter", ads);
editor.putBoolean("ShowAd", true);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
}
In the dummy app I am showing the data in TextView so I am calling onResume and onPause method otherwise I know onCreate is enough. I don't understand whats wrong in the algorithm. I am not getting any error at all and in the toast I am only able to decrease the value till 29 . I have tried all types of decrement operation. Any advice will be helpful.**I am able to save the data onle problem is with the lonng value is not getting saved and not getting decremented **
Put these methods in your utils class and use
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
You don't need to put shared preferences everywhere, just initialize it inside onCreate method and access from constant String, so will easy to access it.
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
SharedPreferences prefs;
SharedPreferences.Editor editor;
final String pref_name = "Admob";
final String ad_name = "ShowAd";
final String day_count = "daycounter";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
prefs = getSharedPreferences(pref_name, 0);
editor = prefs.edit();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putBoolean(ad_name, false);
editor.putLong(day_count, 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
boolean ad_start = prefs.getBoolean(ad_name, true);
long ad = prefs.getLong(day_count, 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad < 0) {
editor.putBoolean(ad_name, true);
}
editor.putLong(day_count, ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
I was making mistake in this method part thx to Ahmed sir My mistake was setting the value equal to
if (ad > 0) so when the value is more than zero the boolean was st as true and the data never get a chance to get decremented more
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
long ads = ad - 1;
if (ad < 0) {
editor.putBoolean("ShowAd", true);
}
editor.putLong("daycounter", ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}

service data reset after swiping away application

Purpose of program: I'm trying to make an app that will count how many times the user checked their phone by issuing a broadcast for Intent.ACTION_SCREEN_ON. it then increments a counter and updates the activity with the new counter.
The problem: This all works just fine but as soon as I swipe away the application from the apps tray, the counter goes back to zero.
obviously what is supposed to happen is the counter would continue.
I tried saving the counter value in the service onDestroy and then calling it again onCreate but onDestroy is never called.
Note that in the onCreate() for the activity it sends a broadcast to the service asking for the most recent value of counter and then updates it in the view. I couldn't find a better way to keep them in sync.
CounterService.java
public class CounterService extends Service {
public static boolean RERUN = true;
private int counter = 0;
private SharedPreferences SP;
private BroadcastReceiver mScreenStateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
counter++;
System.out.println("************************************* \n \n " + counter);
}
sendCounterBroadcast();
}
};
public void sendCounterBroadcast() {
Intent i = new Intent();
i.setAction("com.inc.count");
i.putExtra("counterValue", counter);
sendBroadcast(i);
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("********************** CounterService.onCreate()");
// get counter value from SP -- this is useful for when the service gets recreated
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
counter = SP.getInt("counter", 0);
// wait for screen to be turned on or for the activity to ask you for the counter number
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction("send.counter.to.phonecounteractivity");
registerReceiver(mScreenStateBroadcastReceiver, intentFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("***************************************** CounterService.OnDestroy()");
unregisterReceiver(mScreenStateBroadcastReceiver);
// Save counter value for when we restart service
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
SharedPreferences.Editor SPE = SP.edit();
if (RERUN) {
SPE.putInt("counter", counter);
System.out.println("******************************** RESTARTING SERVICE ");
startService(new Intent(getApplicationContext(), CounterService.class));
} else
SPE.putInt("counter", 0);
SPE.apply();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PhoneCheckerCounter.Java
public class PhoneCheckerCounter extends AppCompatActivity {
private BroadcastReceiver changeCount;
private IntentFilter filter;
private int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_checker_counter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
switcherOnClick();
assignValuesOnCreate();
System.out.println("**************************** onCreate()");
changeCounterText();
}
public void switcherOnClick() {
final Switch sCounter = findViewById(R.id.switchCounter);
sCounter.setOnClickListener(new View.OnClickListener() {
Intent intent = new Intent(getApplicationContext(), CounterService.class);
#Override
public void onClick(View v) {
if (sCounter.isChecked()) {
startService(intent);
CounterService.RERUN = true;
v.getContext().registerReceiver(changeCount, filter);
Toast.makeText(getApplicationContext(), "Counting has begun", Toast.LENGTH_SHORT).show();
} else {
TextView n = findViewById(R.id.counter);
n.setText("0");
CounterService.RERUN = false;
v.getContext().unregisterReceiver(changeCount);
stopService(intent);
Toast.makeText(getApplicationContext(), "The application stopped counting", Toast.LENGTH_SHORT).show();
}
}
});
}
public void changeCounterText() {
changeCount = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView n = findViewById(R.id.counter);
counter = intent.getIntExtra("counterValue", 0);
System.out.println("************************ RECEIVED!!!! value of: " + counter);
n.setText("" + counter);
}
};
filter = new IntentFilter();
filter.addAction("com.inc.count");
this.registerReceiver(changeCount, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(changeCount);
assignValuesOnDestroy();
System.out.println("**************************** onDestroy()");
}
public void assignValuesOnCreate() {
Switch s = findViewById(R.id.switchCounter);
if (getSwitchValueFromSP() == 1) s.setChecked(true);
else s.setChecked(false);
Intent f = new Intent();
f.setAction("send.counter.to.phonecounteractivity");
sendBroadcast(f);
}
public void assignValuesOnDestroy() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor edit = SP.edit();
Switch s = findViewById(R.id.switchCounter);
if (s.isChecked()) edit.putInt("switch", 1);
else edit.putInt("switch", 0);
edit.apply();
}
public int getSwitchValueFromSP() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
int isOn = SP.getInt("switch", 0);
return isOn;
}
}
Sample of the activity

Method did not work without warning in AndroidStudio

This app using a AndroidAnnotations.
I don't get any errors. I try implement loadVariable() in onCreate, but it is not imposible by Framework docs, because onCreate can't have a views. So question is how to show data right after launching application from SharedPreference? Additionaly, when i checked boxes, textView did not show numbers od checked boxes.
What i should do now ?
#EActivity(R.layout.activity_main2)
public class Main2Activity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int numberOfTrue;
#ViewById(R.id.tv1)
TextView tv1;
#ViewById(R.id.cb1)
CheckBox cb1;
#ViewById(R.id.cb2)
CheckBox cb2;
#ViewById(R.id.cb3)
CheckBox cb3;
#ViewById(R.id.cb4)
CheckBox cb4;
#AfterViews
void update() {
cb1.setChecked(getFromSP("cb1"));
cb2.setChecked(getFromSP("cb2"));
cb3.setChecked(getFromSP("cb3"));
cb4.setChecked(getFromSP("cb4"));
}
#Click
void b2() {
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
#AfterViews
void update2() {
loadVariable();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cb1:
saveInSp("cb1",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb2:
saveInSp("cb2",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb3:
saveInSp("cb3",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb4:
saveInSp("cb4",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
}
saveVariable(numberOfTrue);
loadVariable();
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private void saveVariable(int numberOfTrue){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key2", numberOfTrue);
editor.commit();
}
private void loadVariable(){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
int number = sharedPref.getInt("key2", 0);
tv1.setText(""+number);
numberOfTrue=number;
}
}

Call another Activity in Main Activity

sorry my question is may be very simple for all of you. But I am new and need solution for it. If you can help me for solve it.
I have one quote application which have function for check new quote from server in main activity, its checking with server on loading Main Activity that there new quotes available or not and if available its opening one popup window for go setting activity for download new quotes, and if user press setting button than its taking user to setting activity. I need some changes in it. I want automatic download new quotes from main activity without go setting activity. both activity are like below
Thanks
public class MainActivity extends Activity {
SharedPreferences mSharedPreferences;
//String qotdId;
private AdView mAdView;
private InterstitialAd mInterstitial;
public static boolean active;
DAO db;
String siteUrl, updatesUrl;
int lastAuthor, lastQuote;
private ConnectionDetector cd;
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
active = true;
}
#Override
protected void onStop() {
super.onStop();
active = false;
}
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
/* Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
Toast.makeText(MainActivity.this, "Please Push Download Button And Save Status in Your Mobile For Just One Time", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
*/
// Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
db = new DAO(this);
db.open();
cd = new ConnectionDetector(MainActivity.this);
siteUrl = getResources().getString(R.string.siteUrl);
updatesUrl = siteUrl + "site/get_updates/" + String.valueOf(lastAuthor) + "/" + String.valueOf(lastQuote);
if (cd.isConnectingToInternet()) {
// Internet Connection is not present
Intent checkUpdates = new Intent(MainActivity.this, CheckUpdatesService.class);
startService(checkUpdates);
}
// generateKeyHash();
final ImageButton quotes = (ImageButton) findViewById(R.id.quotes);
quotes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 1);
intent.putExtra("itemSelected", 0);
startActivity(intent);
}
});
final ImageButton authors = (ImageButton) findViewById(R.id.authors);
authors.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
AuthorsActivity.class);
startActivity(intent);
}
});
final ImageButton favorites = (ImageButton) findViewById(R.id.favorites);
favorites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 2);
startActivity(intent);
}
});
final ImageButton settings = (ImageButton) findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
}
});
}
}
And my other activity
public class SettingsActivity extends PreferenceActivity {
static final int TIME_DIALOG_ID = 999;
private AdView mAdView;
private InterstitialAd mInterstitial;
private static final String MY_PREFERENCES = "my_preferences";
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
}
#Override
protected void onStop() {
//unregisterReceiver(receiver);
super.onStop();
}
// ==========================================================================================================//
DAO db;
// Progress dialog
ProgressDialog pDialog;
PreferenceScreen preferenceScreen;
private static SharedPreferences mSharedPreferences;
UpdateClass update;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
Preference more, rate, about, check, share,status,background, progress = null;
PreferenceCategory socialsCategory;
private MyDownloadReceiver receiver;
// ==============================================================================
//////////////////// First Load /////////////////
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
//TWITTER_CONSUMER_KEY = getResources().getString(
// R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(
// R.string.TWITTER_CONSUMER_SECRET);
//TWITTER_CALLBACK_URL = "oauth://"
// + getApplicationContext().getPackageName()
// + ".SettingsActivity";
//uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
addPreferencesFromResource(R.layout.settings);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
check = (Preference) findPreference("check");
about = (Preference) findPreference("about");
more = (Preference) findPreference("more");
rate = (Preference) findPreference("rate");
status = (Preference) findPreference("status");
share = (Preference) findPreference("share");
background = (Preference) findPreference("background");
socialsCategory = (PreferenceCategory) findPreference("socials");
preferenceScreen = getPreferenceScreen();
check.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
update = new UpdateClass(SettingsActivity.this);
update.handleUpdates();
//if (mInterstitial.isLoaded()) {
// mInterstitial.show();
//}
return false;
}
});
// ==============================================================================
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsActivity.this,
AboutActivity.class);
startActivity(intent);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
return false;
}
});
// ==============================================================================
background
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.equals(true)) {
db.updateSetting("background", "1");
} else {
db.updateSetting("background", "0");
}
return true;
}
});
// ==============================================================================
// ==============================================================================
rate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindishayari2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
more.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String developerName = "karopass";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q="+ developerName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q="+ developerName)));
}
return true;
}
});
share.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "आज ही डाउनलोड करे हिंदी शायरी एप्लीकेशन और पाइए बेस्ट हिंदी शायरी.इस एप्लीकेशन में 3000 से भी ज्यादा बढ़िया हिंदी शायरी का कलेक्शन है जिसे आप पढने या शेर करने के लिए यूज कर सकते है !! आज ही डाउनलोड करे !! http://play.google.com/store/apps/details?id=com.karopass.hindishayari2016";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, " ");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
});
// ==============================================================================
status.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindi_status_2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
IntentFilter filter = new IntentFilter(MyDownloadReceiver.ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MyDownloadReceiver();
registerReceiver(receiver, filter);
}
void showProgressBar() {
progress = new MyProgressBarPreference(this);
preferenceScreen.addPreference(progress);
}
void setDownloadProgress(int percent) {
if (progress != null) {
((MyProgressBarPreference)progress).setProgress(percent);
((MyProgressBarPreference)progress).setLabel("Please wait... " +percent + "%"+" Downloading Done");
}
}
void hideProgressBar()
{
if (progress != null)
preferenceScreen.removePreference(progress);
}
public class MyDownloadReceiver extends BroadcastReceiver {
public static final String ACTION = "com.karopass.hindishayari2016.intent.action.DOWNLOAD";
public static final int INITIALIZE = 0x001;
public static final int DOWNLOAD = 0x002;
public static final int FINISH = 0x003;
public static final String EXTRA_STATUS = "status";
public static final String EXTRA_PERCENT = "percent";
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_STATUS, -1);
Log.d("DESOLF", "receive broadcast : " + status);
switch(status) {
case INITIALIZE:
showProgressBar();
break;
case DOWNLOAD:
int percent = intent.getIntExtra(MyDownloadReceiver.EXTRA_PERCENT, 0);
setDownloadProgress(percent);
break;
case FINISH:
hideProgressBar();
//Toast.makeText(SettingsActivity.this, "Downloaded successfully", Toast.LENGTH_LONG).show();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
break;
default:
}
}
}
public class MyProgressBarPreference extends Preference {
public MyProgressBarPreference(Context context) {
super(context);
}
public MyProgressBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyProgressBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private ImageView mStatusIcon;
private ProgressBar mProgressBar;
private TextView mStatusText ;
private int lastReqProgress=-1;
private int lastReqMax=-1;
private String lastLabel;
#Override
protected View onCreateView(ViewGroup parent) {
LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View myLayout=li.inflate(R.layout.download_progress, null, false);
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
mStatusIcon = (ImageView) myLayout.findViewById(R.id.status_icon);
mStatusIcon.startAnimation(anim);
mProgressBar=(ProgressBar) myLayout.findViewById(R.id.status_progress);
mStatusText=(TextView) myLayout.findViewById(R.id.status_text);
mStatusIcon.setImageResource(R.drawable.rotate);
mProgressBar.setProgress(0);
mStatusText.setText(0 + "%");
return myLayout;
}
public void setIcon(int resId) {
mStatusIcon.setImageResource(resId);
}
public void setProgress(int value){
if (mProgressBar!=null){
mProgressBar.setProgress(value);
} else {
lastReqProgress=value;
}
}
public void setMax(int value){
if (mProgressBar!=null){
int savedprogress=mProgressBar.getProgress();
mProgressBar.setMax(0);
mProgressBar.setMax(value);
mProgressBar.setProgress(savedprogress);
} else {
lastReqMax=value;
}
}
public void setLabel(String text){
if (lastLabel!=null){
mStatusText.setText(text);
} else {
lastLabel=text;
}
}
}
}
You can try this code:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
Don't forget to add your Second Activity in the AndroidManifest.xml:
<activity android:label="#string/app_name" android:name="SecondActivity"/>
Android Page

Categories