How to get an Android Switch status from another class? - java

i'm working with a RecyclerView wich has a Switch that lets the user organize the list from A to Z when the switch is on, and from Z to A when it is off, in order to implement the OnClick method i need to now the position of each element, but the element could be in two different positions (depending on the sorting chosen by the user) so in order to know where the element is, i need to know the status of the Switch from the class that implements the OnClick method.
This is my Switch-sorting implementation :
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
switchStatus.setText("Sorting alphabetically");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
}else{
switchStatus.setText("Sorting by popularity");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories rhs, Categories lhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
}
}
});
//check the current state before we display the screen
if(categoriesSortingSwitch.isChecked()){
switchStatus.setText("Sorting alphabetically");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
}
else {
switchStatus.setText("Sorting by popularity");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories rhs, Categories lhs) {
return lhs.title.compareTo(rhs.title);
}
});
}
}
//I CREATED THIS METHOD THINKING IN USING IT IN THE OTHER CLASS TO GET THE STATUS
public boolean getSwitchstatus(){
if(categoriesSortingSwitch.isChecked()){
return true;
}
else return false;
}
And this is the method of the other class where i need to get the status :
#Override
public void onClick(View v) {
final Intent intent;
int position = getAdapterPosition();
if (position==0){
if(/** find a way to see if it is on or off and if it is on do this**/){
intent = new Intent(context, nose.class);
context.startActivity(intent);
}
else/** if it is off**/{
}
}
}
In resume, i need to find a way to get the status of the switch so i can tell the position of the element.
Thanks very much.

Thanks to MkiiSoft advice this is what i did and works perfectly :
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
switchStatus.setText("Sorting alphabetically");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
//JUST ADDED THIS SHARED PREFERENCE WITH THE STRINGS ("it's","on") WHEN THE SWITCH IS ON
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("it's","on");
editor.apply();
}else{
switchStatus.setText("Sorting by popularity");
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories rhs, Categories lhs) {
return lhs.title.compareTo(rhs.title);
}
});
ca.notifyDataSetChanged();
//JUST ADDED THIS SHARED PREFERENCE WITH THE STRINGS ("it's","off") WHEN THE SWITCH IS OFF
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("it's", "off");
editor.apply();
}
}
});
Then in Class where i needed to now the status of the switch i simply compared the strings and based on the matching or missmatching of the strings oppened a different Activity, this way :
public void onClick(View v) {
final Intent intent;
int position = getAdapterPosition();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String onoff = preferences.getString("it's", "");
//IF IT IS ON DO THIS
if(onoff.equalsIgnoreCase("on"))
{
if (position==0){
intent = new Intent(context, nose.class);
context.startActivity(intent);
}
//IF IT IS OFF DO THIS
} else if (onoff.equalsIgnoreCase("off")){
if (position==0){
intent = new Intent(context, nose2.class);
context.startActivity(intent);
}
}
}

Related

How to display a message in MainActivity if there is no Internet?

If there is no Internet, display a certain xml in full screen when the application starts, that there is no Internet, and if there is, perform MainActivity.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MaterialSearchBar.OnSearchActionListener, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
#SuppressLint("StaticFieldLeak")
public static MaterialSearchBar searchBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private AdView mAdView;
private static List<String> listPermissionsNeeded;
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: setting things up");
StaticUtils.requestQueue = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Admob banner
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
mAdView.setVisibility(View.GONE);
}
});
//restoring recent searches list
StaticUtils.recentSearchesList = getArrayList(StaticUtils.KEY_LIST_PREFERENCCES);
if (StaticUtils.recentSearchesList==null){
StaticUtils.recentSearchesList = new ArrayList<>();
}
StaticUtils.savedImagesList = new ArrayList<>();
searchBar = findViewById(R.id.searchToolBar);
searchBar.setHint("Search Wallpapers");
searchBar.setOnSearchActionListener(this);
searchBar.hideSuggestionsList();
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
//sets home fragment open by default
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
playLogoAudio(); //to play the logo audio
searchEvents(); //advanced search events
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed: back button invoked.");
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void grantPermissionBottomSheet(){
View dialogView = getLayoutInflater().inflate(R.layout.layout_bottomsheet, null);
final BottomSheetDialog dialog = new BottomSheetDialog(this);
Button ok = dialogView.findViewById(R.id.bt_bottomsheet);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: bottomSheet button clicked.");
requestPermissions(MainActivity.this);
dialog.dismiss();
}
});
dialog.setContentView(dialogView);
dialog.show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d(TAG, "onNavigationItemSelected: navigation item pressed.");
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
} else if (id == R.id.nav_saved) {
NetworkUtils network = new NetworkUtils(this);
if(network.checkConnection(drawer)){ //if network connected
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,2);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"Saved");
startActivity(i);
}
}else if (id == R.id.nav_downloads) {
//downloaded images
if (permissionsGranted(this)) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID, 4); //4 for downloads section
i.putExtra(StaticUtils.KEY_SEARCH_DATA, "Downloads");
startActivity(i);
}else{
grantPermissionBottomSheet();
}
} else if (id == R.id.nav_share) {
//share the app intent
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey! look what I found from play store.\nDownload cool & amazing wallpapers for your device from this app, "+getResources().getString(R.string.app_name)+", among various categories.\n\nCheck this out:\n"+StaticUtils.playStoreUrlDefault+getPackageName()+"\nDownload now:)");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share app through..."));
} else if (id == R.id.nav_rate) {
//rate the app intent
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
}
} else if (id == R.id.nav_about) {
//about page
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,3); //3 for about fragment
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"About");
startActivity(i);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void playLogoAudio(){
Log.d(TAG, "playLogoAudio: playing logo audio");
View headerView = navigationView.getHeaderView(0);
ImageView drawerLogo = headerView.findViewById(R.id.imageLogo);
drawerLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.hello);
mediaPlayer.start();
}
});
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
#Override
public void onSearchStateChanged(boolean enabled) {
if (enabled){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
}else{
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
Log.d(TAG, "onSearchConfirmed: confirmed search: "+text);
Intent i = new Intent(this,SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,1);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,String.valueOf(text));
if(new NetworkUtils(getApplicationContext()).checkConnection(drawer)) { //start intent if network connected
StaticUtils.recentSearchesList.add(String.valueOf(text)); //adds the query to the recents list
if (StaticUtils.recentSearchesList.size()>20){
StaticUtils.recentSearchesList.remove(0);
}
SearchFragment.updateAdapter(this,StaticUtils.recentSearchesList);
searchBar.setText(""); //removes the search query
startActivity(i);
}
}
#Override
public void onButtonClicked(int buttonCode) {
Log.d(TAG, "onButtonClicked: search interface button clicked: "+buttonCode);
switch (buttonCode){
case MaterialSearchBar.BUTTON_NAVIGATION:
drawer.openDrawer(GravityCompat.START);
break;
case MaterialSearchBar.BUTTON_BACK:
searchBar.disableSearch();
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {}
public void saveArrayList(ArrayList<String> list, String key){
Log.d(TAG, "saveArrayList: saving recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
Log.d(TAG, "getArrayList: getting saved recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
#Override
protected void onPause() {
super.onPause();
//Saving arraylist when activity gets paused
saveArrayList(StaticUtils.recentSearchesList,StaticUtils.KEY_LIST_PREFERENCCES);
}
public void searchEvents(){
Log.d(TAG, "searchEvents: managing the search events");
searchBar.addTextChangeListener(new TextWatcher() {
ArrayList<String> tempList = new ArrayList<>();
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d(TAG, "beforeTextChanged: clearing the list");
if (!tempList.isEmpty()){
tempList.clear();
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d(TAG, "onTextChanged: changing search query");
for (String string : StaticUtils.recentSearchesList) {
if (s.length() > 0) {
if (string.matches("(?i)(" + s + ").*")) {
tempList.add(string);
SearchFragment.updateAdapter(getApplicationContext(), tempList);
}
}else{
SearchFragment.updateAdapter(getApplicationContext(), StaticUtils.recentSearchesList);
}
}
}
#Override
public void afterTextChanged(Editable s) {}
});
}
#Override
protected void onResume() {
super.onResume();
navigationView.setCheckedItem(R.id.nav_home);
if (!permissionsGranted(this)){ //checking and requesting permissions
grantPermissionBottomSheet();
}
}
public static boolean permissionsGranted(Context context) {
Log.d(TAG, "checkPermissions: checking if permissions granted.");
int result;
listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(context,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
//if all/some permissions not granted
return listPermissionsNeeded.isEmpty();
}
public static void requestPermissions(Activity activity){
Log.d(TAG, "requestPermissions: requesting permissions.");
ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), StaticUtils.MULTIPLE_PERMISSIONS);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: action when permission granted or denied");
if (requestCode == StaticUtils.MULTIPLE_PERMISSIONS) {
if (grantResults.length <= 0) {
// no permissions granted.
showPermissionDialog();
}
}
}
public void showPermissionDialog(){
Log.d(TAG, "showPermissionDialog: requesting permissions");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
builder.setMessage("You'll not be able to use this app properly without these permissions.");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//re-requesting permissions
requestPermissions(MainActivity.this);
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
I would suggest some kind of different flow.
Most apps have something called a "Splash screen" (usually with a logo, sometimes kind of a progress bar).
what you can do is create a splash activity, - if there is internet call your MainActiviy, otherwise call another activity NetworkErrorActivity with the XML you want.

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

Rate my app dialog when the user want to exit my app

I want to change the dialog of exit app with twi choices choice 1 = "rate" and choice 2 = "exit" now i can only show exit or stay dialog but i want to convert it to what i described here is the code :
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
and this the class code `
public class PicSelect extends SherlockActivity {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private Itemadapter imageAdapter;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picselct);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#c5d951")));
mAdView = (AdView) findViewById(R.id.adViewad);
mAdView.loadAd(new AdRequest.Builder().build());
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);
photoGrid = (GridView) findViewById(R.id.albumGrid);
Model.LoadModel();
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
imageAdapter=new Itemadapter(getApplicationContext(), R.layout.photo_item,ids,"CATIMAGE");
photoGrid.setAdapter(imageAdapter);
// get the view tree observer of the grid and set the height and numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
if (numColumns > 0) {
final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
photoGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Log.e("FolderName", Model.GetbyId(position+1).FolderName);
String FolderName=Model.GetbyId(position+1).FolderName;
String CategoryName=Model.GetbyId(position+1).Name;
Intent i=new Intent(PicSelect.this,PicItem.class);
i.putExtra("Folder", FolderName);
i.putExtra("Category", CategoryName);
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.rateapp:
final String appName = getPackageName();//your application package name i.e play store application url
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ appName)));
}
return true;
case R.id.moreapp:
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(getString(R.string.play_more_apps))));
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
}
`
finaly if anyone know how to style the text thank you for your help
.setNegativeButton("Rate App", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=[your package name]"));
startActivity(i);
}
})
This will give you a negative option that says Rate App that when clicked opens the market to your app.
Improve your app with this snippet in onBackPressed():
if(isTaskRoot()) {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
toast = Toast.makeText(this, getString(R.string.hinweisBeendeApp), Toast.LENGTH_SHORT);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}else {
super.onBackPressed();
}

How to restart same Activity?

If i have 10 EditText and the user enter only in 5 then i exit my app on click the onBackPressed Button without submit the EditText data which is entering , and then when i restart my app i want to same activity on start up.Thanks to appriceat.
public class Registration_Form extends Activity {
EditText et_CompanyName;
EditText et_EmployeeName;
EditText et_CompanyWebsite;
EditText et_ContactNumber;
EditText et_Email_Id;
Button btnSubmit;
DatabaseHelper databaseHelper;
SQLiteDatabase db;
RadioGroup radioGroup_FinancialYaer;
RadioButton radioButton_FinancialYaer;
String strFinancialYear;
String appWidgetId = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_details);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor edit = prefs.edit();
boolean alldataSaved=prefs.getBoolean("SecondRun",false);
et_CompanyName = (EditText) findViewById(R.id.editText_CompanyName);
et_EmployeeName = (EditText) findViewById(R.id.editText_EmployeeName);
et_CompanyWebsite = (EditText) findViewById(R.id.editText_CompanyWebSite);
et_ContactNumber = (EditText) findViewById(R.id.editText_ConatctNo);
et_Email_Id = (EditText) findViewById(R.id.editText_EmailId);
et_CompanyName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Company_Name"+appWidgetId,et_CompanyName.getText().toString());
edit.commit();
}
}
});
et_EmployeeName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Employee_Name"+appWidgetId,et_EmployeeName.getText().toString());
edit.commit();
}
}
});
et_CompanyWebsite.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Company_Website"+appWidgetId,et_CompanyWebsite.getText().toString());
edit.commit();
}
}
});
et_ContactNumber.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Contact_Number"+appWidgetId,et_ContactNumber.getText().toString());
edit.commit();
}
}
});
et_Email_Id.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Email_Id"+appWidgetId,et_Email_Id.getText().toString());
edit.commit();
}
}
});
SharedPreferences settings=getSharedPreferences("prefs",0);
boolean firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
if(alldataSaved == false)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("SecondRun",true);
editor.commit();
Log.e("Second"," Steps !!!!");
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
}
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
radioGroup_FinancialYaer = (RadioGroup)findViewById(R.id.radioGroupFinanncialYear);
btnSubmit = (Button) findViewById(R.id.buttonSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String stringEmail_Id = et_Email_Id.getText().toString()
.trim();
final String stringCompanyWebsite = et_CompanyWebsite.getText()
.toString().trim();
if ((et_CompanyName.getText().toString().isEmpty()))
{
et_CompanyName.setError("Field Can Not Be Empty !");
}
else if (!et_CompanyName.getText().toString().trim()
.matches("[a-zA-Z ]+"))
{
et_CompanyName.setError("Accept Alphabets Only.");
}
else if ((et_EmployeeName.getText().toString().isEmpty()))
{
et_EmployeeName.setError("Field Can Not Be Empty !");
}
else if (!et_EmployeeName.getText().toString().trim()
.matches("[a-zA-Z ]+"))
{
et_EmployeeName.setError("Accept Alphabets Only.");
}
else if ((et_CompanyWebsite.getText().toString().isEmpty()))
{
et_CompanyWebsite.setError("Field Can Not Be Empty !");
}
else if (!isValidUrl(stringCompanyWebsite))
{
et_CompanyWebsite.setError("Invalid URL");
}
else if ((et_ContactNumber.getText().toString().isEmpty()))
{
et_ContactNumber.setError("Field Can Not Be Empty !");
}
else if (!isValidEmail(stringEmail_Id))
{
et_Email_Id.setError("Invalid Email");
}
else
{
String stringCompanyName = et_CompanyName.getText()
.toString().trim();
String stringContactNumber = et_ContactNumber.getText()
.toString().trim();
String stringEmployeeName = et_EmployeeName.getText()
.toString().trim();
int selectedId = radioGroup_FinancialYaer.getCheckedRadioButtonId();
Log.e("selectedId "," = " + selectedId);
radioButton_FinancialYaer = (RadioButton) findViewById(selectedId);
strFinancialYear = radioButton_FinancialYaer.getText().toString().trim();
Log.e("strRadioButton "," = " + strFinancialYear);
databaseHelper.insertRegstrationDetails(stringCompanyName,
stringEmployeeName, stringCompanyWebsite,
stringContactNumber, stringEmail_Id, strFinancialYear);
System.out.println("Data Inserted Successfully !!! ");
Intent iSubmit = new Intent(Registration_Form.this,Staff_Employee_Details.class);
startActivity(iSubmit);
finish();
}
}
});
}
you can simply use this
Intent intent = getIntent();
finish();
startActivity(intent);
I hope thats work
You can use sharedPreference for this. you can save the value of each edittext in one sharedprefrerece (with unique key for each edittext and set values at the time of focus change. see example:)
EditText txtEdit= (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
//do job here when Edittext lose focus
//means save value here
}
});
and load these saved value at on create.
Hope you are getting some idea from this
Edit: This is for your condition
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
if(alldataSaved==false)
{
//stay in this activiy
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
}
That's not how Android works. You cannot "restore" the same Activity in that fashion. What you CAN however do is save out the EditText content, for example in the onPause() or onStop() function, save out the contents of the EditTexts as Strings, put them in a List, then serialize that List out into a file. In the onResume() or onStart() method, deserialize this data from the file.
An example for such serialization is shown here, but I'll also paste it here:
Put objects into bundle
Serialization:
private List<String> list = new ArrayList<String>();
#Override
public void onPause()
{
super.onPause();
FileOutputStream out = null;
try
{
out = openFileOutput("ModelBackup",Context.MODE_PRIVATE);
try
{
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(list);
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
catch(FileNotFoundException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(out != null) out.close();
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
}
Deserialization:
#Override
public void onResume()
{
super.onResume();
FileInputStream in = null;
try
{
in = openFileInput("ModelBackup");
ObjectInputStream oos = new ObjectInputStream(in);
try
{
list = (List<String>)oos.readObject();
}
catch(ClassNotFoundException e)
{
list = null;
}
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(in != null) in.close();
}
catch(IOException e) {}
}
}
If restarting an activity from a fragment, I would do it like so:
new Handler().post(new Runnable() {
#Override
public void run()
{
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().overridePendingTransition(0, 0);
getActivity().finish();
getActivity().overridePendingTransition(0, 0);
startActivity(intent);
}
});

In App Purchases Not Saving Shared Preferences

I have an android application similar to wheel of fortune where users have the option to purchase one consumable, $1000, and two entitlements, where they unlock two images as wheel styles. I am using the Amazon In-App Purchasing API. The user should be able to purchase as many consumables as they want but once they purchase the entitlements the unlocked image should be the only image that they see and they should no longer see the locked image. These in-app purchases work fine the first instance I initiate these purchases.
However, the consumable field will only update once and even though I can still go through the process of completing purchases for the consumable, the text view containing the score, or money, does not update other then that first initial purchase. Also the wheels return to the locked image rather then remaining as the unlocked image despite the fact that when I initiate the purchase for these entitlements I am told that I already own these items. Therefore I believe it may be something to do with my SharedPreferences. In short my purchases update my views once and then never again, however the backend code i.e the responses I receive from the Amazon client when completing purchases are correct. Can anyone see where I have made a mistake? Why does the textView containing the score update on the 1st purchase and never again from then on? Also how do I save the changes toe the wheel style so that when it reopens they no longer have the option to purchase the wheel? I have three classes and have included the code below. All and any help is greatly appreciated.
Game Class
public class Game extends Activity {
private ImageView wheel;
private int rand;
private int[] amounts = {100,650,-1,650,300,-1,800,250,-1,500};
private int score = 0;
private TextView scoreText;
private AnimatorSet set;
protected boolean animationDone = true;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
wheel = (ImageView) findViewById(R.id.imageView1);
scoreText = (TextView) findViewById(R.id.score);
score = prefs.getInt("score", 0);
scoreText.setText("$" + String.valueOf(score));
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("money") && prefs.getBoolean(key, false)) {
score += 1000;
scoreText.setText("$" + String.valueOf(score));
prefs.edit().putBoolean("money", false);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
#Override
protected void onPause() {
if(this.isFinishing())
{
prefs.edit().putInt("score", score).commit();
}
super.onPause();
}
#Override
protected void onStop() {
prefs.edit().putInt("score", score).commit();
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
String style = data.getStringExtra("wheel");
if(style.equals("camo"))
wheel.setImageResource(R.drawable.camowheel);
if(style.equals("gold"))
wheel.setImageResource(R.drawable.goldwheel);
if(style.equals("normal"))
wheel.setImageResource(R.drawable.wheel);
}
}
public void spinTheWheel(View v) {
if(animationDone) {
wheel.setRotation(0);
rand = (int) Math.round(2000 + Math.random()*360);
set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(wheel, View.ROTATION, rand));
set.setDuration(2000);
set.setInterpolator(new DecelerateInterpolator());
set.start();
animationDone = false;
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
calculateResult();
animationDone = true;
}
});
}
}
private void calculateResult() {
int angle = (int) wheel.getRotation();
angle %= 360;
angle = (int) Math.floor(angle/36);
if(amounts[angle] == -1) {
Intent intent = new Intent(this, GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
else {
score += amounts[angle];
scoreText.setText("$"+String.valueOf(score));
prefs.edit().putInt("score", 0).commit();
}
}
public void upgradeWheel(View v) {
Intent intent = new Intent(getApplicationContext(), ChangeWheel.class);
startActivityForResult(intent, 1);
}
public void endGame(View v) {
Intent intent = new Intent(getApplicationContext(), GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
public void addMoney(View v) {
PurchasingManager.initiatePurchaseRequest("money");
}
}
ChangeWheel Class
public class ChangeWheel extends Activity {
private Button buyCamoButton;
private Button buyGoldButton;
private ImageButton goldButton;
private ImageButton camoButton;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_wheel);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
buyCamoButton = (Button) findViewById(R.id.buyCamo);
buyGoldButton = (Button) findViewById(R.id.buyGold);
goldButton = (ImageButton) findViewById(R.id.goldButton);
camoButton = (ImageButton) findViewById(R.id.camoButton);
goldButton.setEnabled(false);
camoButton.setEnabled(false);
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("camo") && prefs.getBoolean(key, false)) {
camoButton.setImageResource(R.drawable.camowheel);
camoButton.setEnabled(true);
buyCamoButton.setVisibility(View.INVISIBLE);
}
else if(key.equals("gold") && prefs.getBoolean(key, false)) {
goldButton.setImageResource(R.drawable.goldwheel);
goldButton.setEnabled(true);
buyGoldButton.setVisibility(View.INVISIBLE);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
public void camoClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "camo");
setResult(RESULT_OK, intent);
finish();
}
public void goldClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "gold");
setResult(RESULT_OK, intent);
finish();
}
public void normalClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "normal");
setResult(RESULT_OK, intent);
finish();
}
public void buyCamo(View v) {
String req = PurchasingManager.initiatePurchaseRequest("camo");
prefs.edit().putString(req, "camo").commit();
}
public void buyGold(View v) {
String req = PurchasingManager.initiatePurchaseRequest("gold");
prefs.edit().putString(req, "gold").commit();
}
}
InAppObserver Class
public class InAppObserver extends BasePurchasingObserver {
private SharedPreferences prefs;
public InAppObserver(Activity caller) {
super(caller);
prefs = PreferenceManager.getDefaultSharedPreferences(caller.getApplicationContext());
}
#Override
public void onSdkAvailable(boolean isSandboxMode) {
PurchasingManager.initiatePurchaseUpdatesRequest(Offset.BEGINNING);
}
#Override
public void onPurchaseUpdatesResponse(PurchaseUpdatesResponse res) {
for(String sku : res.getRevokedSkus()) {
prefs.edit().putBoolean(sku, false).commit();
}
switch (res.getPurchaseUpdatesRequestStatus()) {
case SUCCESSFUL:
for(Receipt rec : res.getReceipts()) {
prefs.edit().putBoolean(rec.getSku(), true).commit();
}
break;
case FAILED:
// do something
break;
}
}
#Override
public void onPurchaseResponse(PurchaseResponse res) {
switch(res.getPurchaseRequestStatus()) {
case SUCCESSFUL:
String sku = res.getReceipt().getSku();
prefs.edit().putBoolean(sku, true).commit();
break;
case ALREADY_ENTITLED:
String req = res.getRequestId();
prefs.edit().putBoolean(prefs.getString(req, null), true).commit();
break;
case FAILED:
// do something
break;
case INVALID_SKU:
// do something
break;
}
}
}
It could be that you are not using the same editor.
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editors are being returned. Hence the
value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();
From... SharedPreferences not working across Activities

Categories