I've tried many other threads and articles but I just can't find the right stuff that I am looking for.
So I have a MainActivity and a SettingsActivity both are java classes. In my main activity there is a button when pressed, increases the count by +1, and shows it on a TextView, it also makes the device vibrate on every increment/Every button press. I want to make a switchpreference in SettingsActivity which if kept off/false, turns off the vibration on button press and if kept on/true, turns on the vibration on button press.
I don't know how to retrieve the state of SwitchPreferenceCompat(ON OR OFF) from SettingsActivity and use it in the MainActivity, so if the user turns the switch off in setting activity, the vibration should stop on button press which is in MainActivity.
I have already used Shared Preferences in MainActivity for saving the current count/number when App is closed and resumes from the same count when reopened.
MainAcitivity
package com.saad.tapcounter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView ;
int Start;
TextView txt;
Button btnU,btnT,btnR;
Switch sw,sw2;
private ConstraintLayout Clayout;
Vibrator vibe;
Boolean switchPref;
SharedPreferences sharedPreferences;
private static long back_pressed;
private Vibrator Vibrator;
//Double Tap Exit
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
//Inflater for Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
//Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.menui1:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbarid);
setSupportActionBar(toolbar);
MobileAds.initialize(this, "-APPID-");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
vibe =(Vibrator)getSystemService(VIBRATOR_SERVICE);
Clayout = findViewById(R.id.MainLayout);
btnT = findViewById(R.id.tapbtn);
btnR = findViewById(R.id.resetbtn);
btnU = findViewById(R.id.undobtn);
sw = findViewById(R.id.swch);
sw2 = findViewById(R.id.darkswch);
txt = findViewById(R.id.txtv);
txt.setTextColor(Color.BLACK);
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
loadData();
setData();
incrementbtn();
undobtn();
resetbtn();
switchbtn();
themeswitch();
}
public void loadData(){
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
}
private void setData(){
Start = sharedPreferences.getInt("0",0);
if(Start==0){
txt.setText("0");
}
else{
txt.setText(Integer.toString(Start));
}
}
public void incrementbtn(){
btnT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incvibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start += 1;
txt.setText(Integer.toString(Start));
txtresize();
} else {
Start += 1;
txt.setText(Integer.toString(Start));
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void undobtn(){
btnU.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
undovibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start -= 1;
txt.setText(Integer.toString(Start));
}
else{
return;
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void resetbtn(){
btnR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetvibe();
Start = 0;
txt.setText(Integer.toString(Start));
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void switchbtn(){
sw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw.isChecked()) {
btnR.setEnabled(false);
btnT.setEnabled(false);
btnU.setEnabled(false);
txt.setTextColor(Color.RED);
}
else{
btnR.setEnabled(true);
btnT.setEnabled(true);
btnU.setEnabled(true);
if(sw2.isChecked()){
txt.setTextColor(Color.WHITE);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void themeswitch(){
sw2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw2.isChecked()){
Clayout.setBackgroundColor(Color.DKGRAY);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.WHITE);
}
}
else{
Clayout.setBackgroundColor(Color.WHITE);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void txtresize(){
if(Start > 1000 && Start < 10000){
txt.setTextSize(80);
}
else if (Start > 10000 && Start < 100000){
txt.setTextSize(60);
}
else if (Start > 100000){
txt.setTextSize(40);
}
else{
return;
}
}
StringBuilder info = new StringBuilder();
public void undovibe(){
vibe.vibrate(100);
}
public void resetvibe(){
vibe.vibrate(150);
}
public void incvibe(){
vibe.vibrate(40);
}
}//Real one
SettingActivity (created it from NEW > SettingActivity)
I did try some stuff by myself in here but it crashed my app.
package com.saad.tapcounter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
root_preference.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory app:title="Settings"
app:iconSpaceReserved="false">
<SwitchPreferenceCompat
app:key="Switchsett1"
app:title="Vibration"
app:summaryOff="Turn Vibration On"
app:summaryOn="Turn Vibration Off"
app:iconSpaceReserved="false"
app:defaultValue="true"
/>
<SwitchPreferenceCompat
app:key="Switchset2"
app:iconSpaceReserved="false"
app:summaryOff="#string/attachment_summary_off"
app:summaryOn="#string/attachment_summary_on"
app:title="#string/attachment_title" />
</PreferenceCategory>
</PreferenceScreen>
I don't know how to retrieve the state of switch(ON OR OFF) from SettingsActivity
To get the value of SwitchPreferenceCompat from shared preference, then you need to retrieve it as a Boolean
Now the key of your first SwitchPreferenceCompat is Switchsett1, so to retrieve the value of this:
public class MainActivity extends AppCompatActivity {
Boolean switchPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
switchPref = prefs.getBoolean("Switchsett1", false);
Toast.makeText(this, String.valueOf(switchPref), Toast.LENGTH_SHORT).show(); // shows true if the SwitchPreferenceCompat is ON, and false if OFF.
Now the Toast in the above script shows true if the SwitchPreferenceCompat is ON, and false if it's OFF.
You can do the same for Switchset2 SwitchPreferenceCompat
Related
I am developing an app that I use in DarkMode theme that I put a Switch to on and off darkMode and I save it inside a boolian whitch means darkMode get true or false (boolean isDarkMode =false;)
it work well and I use SharedPreferences to save this true or false value to use it in another activitys .
it work but ...
when I close app and run app again the value of SharedPreferences is not saved and it goes back to first value of boolian
(thank u)
SettingActivity.java (to set boolian true or false)
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class SettingActivity extends AppCompatActivity {
Switch mySwitch;
boolean isDarkMode =false;
private static final String DARKMODE = "login";
#Override
protected void onCreate(Bundle savedInstanceState) {
myboolian();
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darkTheme);
isDarkMode =true;
} else {
setTheme(R.style.AppTheme);
isDarkMode =false;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Toast.makeText(this, ""+ isDarkMode, Toast.LENGTH_SHORT).show();
mySwitch = findViewById(R.id.switch1);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
mySwitch.setChecked(true);
}
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
isDarkMode =true;
restartApp();
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
isDarkMode =false;
restartApp();
}
}
});
Button buttonGoMain=findViewById(R.id.btn_go_MainAct);
buttonGoMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SettingActivity.this,MainActivity.class));
}
});
}
public void restartApp() {
Intent intentRestartApp = new Intent(getApplicationContext(), SettingActivity.class);
startActivity(intentRestartApp);
finish();
}
public void myboolian(){
isDarkMode =!isDarkMode; //change isDarkMode from false to true by this
SharedPreferences sharedPreferences =getSharedPreferences(DARKMODE,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("ISDARKMODE", isDarkMode);
editor.apply();
}
}
and MainActivity.java
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String DARKMODE = "login";
boolean isDarkMode = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
getData();
if (isDarkMode){
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darkTheme);
isDarkMode =true;
} else {
setTheme(R.style.AppTheme);
isDarkMode =false;
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button_go_to_setting_activity);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SettingActivity.class));
}
});
}
private void getData() {
SharedPreferences sharedPreferences = getSharedPreferences(DARKMODE, MODE_PRIVATE);
isDarkMode = sharedPreferences.getBoolean("ISDARKMODE", false);
}
}
In your checkedChangedListener you set darkMode to true and false respectively.
And in your myboolian method is the only place where your write the variable.
This method is only called from your onCreate and nowhere else. In addition to that, this method always sets darkMode = !darkMode, swapping the value.
You have to call myboolian in the onCheckedChanged and remove the darkMode = !darkMode or you will always reset to the value before.
thanks to #Grisgram for help
I solowed this problam by some changes and andrestanding mure about
settingActivity.java
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class SettingActivity extends AppCompatActivity {
public static Switch mySwitch;
boolean isDarkMode =false;
private static final String DARKMODE = "dark";
#Override
protected void onCreate(Bundle savedInstanceState) {
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darkTheme);
isDarkMode=true;
} else {
setTheme(R.style.AppTheme);
isDarkMode=false;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Toast.makeText(this, ""+ isDarkMode, Toast.LENGTH_SHORT).show();
mySwitch = findViewById(R.id.switch1);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
mySwitch.setChecked(true);
}
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
isDarkMode=true;
myboolian();
restartApp();
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
isDarkMode=false;
myboolian();
restartApp();
}
}
});
myboolian();
Button buttonGoMain=findViewById(R.id.btn_go_MainAct);
buttonGoMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SettingActivity.this,MainActivity.class));
}
});
}
public void restartApp() {
Intent intentRestartApp = new Intent(getApplicationContext(), SettingActivity.class);
startActivity(intentRestartApp);
finish();
}
public void myboolian(){
// isDarkMode =!isDarkMode; //change isDarkMode from false to true by this
SharedPreferences sharedPreferences =getSharedPreferences(DARKMODE,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("ISDARKMODE", isDarkMode);
editor.apply();
}
}
and main activity
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String DARKMODE = "dark";
boolean isDarkMode ;
#Override
protected void onCreate(Bundle savedInstanceState) {
getData();
Toast.makeText(this, "is datk ?"+isDarkMode, Toast.LENGTH_SHORT).show();
if (isDarkMode){
setTheme(R.style.darkTheme);
}else {setTheme(R.style.AppTheme);}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button_go_to_setting_activity);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SettingActivity.class));
}
});
}
private void getData() {
SharedPreferences sharedPreferences = getSharedPreferences(DARKMODE, MODE_PRIVATE);
isDarkMode = sharedPreferences.getBoolean("ISDARKMODE", false);
}
}
Hello I have an application android, and I contact you having a problem. My application is a streaming application with a large number of works, the problem is that to load all works the load is really long, that's why I contact you I would like to use an infinite scroll but despite all Github projects i dont understand having low java base if you could tell me or place and how the necessary code thanks
This is my activity code :
package com.solodroid.androidnewsappdemo.activities;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.solodroid.androidnewsappdemo.Config;
import com.solodroid.androidnewsappdemo.R;
import com.solodroid.androidnewsappdemo.firebase.Analytics;
import com.solodroid.androidnewsappdemo.fragments.FragmentAbout;
import com.solodroid.androidnewsappdemo.fragments.FragmentFavorite;
import com.solodroid.androidnewsappdemo.fragments.TabFragment;
import com.startapp.android.publish.Ad;
import com.startapp.android.publish.AdEventListener;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
private AdView adView;
private StartAppAd startAppAd = new StartAppAd(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StartAppSDK.init(this, getResources().getString(R.string.startapp_app_id), false);
setContentView(R.layout.activity_main);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
} else {
Log.d("MainActivity", "Working in Normal Mode, RTL Mode is Disabled");
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
firebaseAnalytics();
loadAdMobBannerAd();
loadStartAppWhenAppLaunch();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//setTitle(menuItem.getTitle());
if (menuItem.getItemId() == R.id.drawer_home) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
}
if (menuItem.getItemId() == R.id.drawer_favorite) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentFavorite()).commit();
}
if (menuItem.getItemId() == R.id.drawer_rate) {
final String appName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
}
}
if (menuItem.getItemId() == R.id.drawer_more) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
}
if (menuItem.getItemId() == R.id.drawer_about) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentAbout()).commit();
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
loadStartAppOnBackPressed();
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
protected void onPause() {
adViewOnPause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
adViewOnResume();
}
#Override
protected void onDestroy() {
adViewOnDestroy();
super.onDestroy();
}
private void firebaseAnalytics() {
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, getResources().getString(R.string.analytics_item_id_1));
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, getResources().getString(R.string.analytics_item_name_1));
Analytics.getFirebaseAnalytics().logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
Analytics.getFirebaseAnalytics().setAnalyticsCollectionEnabled(true);
Analytics.getFirebaseAnalytics().setMinimumSessionDuration(5000);
Analytics.getFirebaseAnalytics().setSessionTimeoutDuration(1000000);
}
private void loadStartAppWhenAppLaunch() {
if (Config.ENABLE_STARTAPP_ADS) {
startAppAd.loadAd(new AdEventListener() {
#Override
public void onReceiveAd(Ad arg0) {
startAppAd.showAd();
startAppAd.loadAd();
}
#Override
public void onFailedToReceiveAd(Ad arg0) {
}
});
} else {
Log.d("MainActivity", "StartApp When App Launch is Disabled");
}
}
private void loadStartAppOnBackPressed() {
if (Config.ENABLE_STARTAPP_ADS) {
StartAppAd.onBackPressed(this);
} else {
Log.d("MainActivity", "StartApp onBackPressed is Disabled");
}
}
private void loadAdMobBannerAd() {
if (Config.ENABLE_ADMOB_ADS) {
adView = (AdView) findViewById(R.id.adView);
adView.loadAd(new AdRequest.Builder().build());
adView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
adView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
adView.setVisibility(View.VISIBLE);
}
});
Log.d("MainActivity", "AdMob Banner is Enabled");
} else {
Log.d("MainActivity", "AdMob Banner is Disabled");
}
}
private void adViewOnPause() {
if (Config.ENABLE_ADMOB_ADS) {
adView.pause();
} else {
Log.d("MainActivity", "adView onPause is Disabled");
}
}
private void adViewOnResume() {
if (Config.ENABLE_ADMOB_ADS) {
adView.resume();
} else {
Log.d("MainActivity", "adView onResume is Disabled");
}
}
private void adViewOnDestroy() {
if (Config.ENABLE_ADMOB_ADS) {
adView.destroy();
} else {
Log.d("MainActivity", "adView onDestroy is Disabled");
}
}
}
and this is my adapter code :
package com.solodroid.androidnewsappdemo.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.solodroid.androidnewsappdemo.Config;
import com.solodroid.androidnewsappdemo.R;
import com.solodroid.androidnewsappdemo.activities.ActivityNewsDetail;
import com.solodroid.androidnewsappdemo.json.JsonConfig;
import com.solodroid.androidnewsappdemo.models.ItemNewsList;
import com.squareup.picasso.Picasso;
import java.util.List;
public class AdapterNewsRecent extends RecyclerView.Adapter<AdapterNewsRecent.ViewHolder> {
private Context context;
private List<ItemNewsList> arrayItemNewsList;
ItemNewsList itemNewsList;
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView title;
public TextView date;
public LinearLayout linearLayout;
public ViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.news_title);
date = (TextView) view.findViewById(R.id.news_date);
image = (ImageView) view.findViewById(R.id.news_image);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
if (Config.ENABLE_DATE_DISPLAY) {
date.setVisibility(View.VISIBLE);
} else {
date.setVisibility(View.GONE);
}
}
}
public AdapterNewsRecent(Context context, List<ItemNewsList> arrayItemNewsList) {
this.context = context;
this.arrayItemNewsList = arrayItemNewsList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.lsv_item_news_list, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
itemNewsList = arrayItemNewsList.get(position);
Typeface font1 = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
Typeface font2 = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
holder.title.setTypeface(font1);
holder.date.setTypeface(font2);
holder.title.setText(itemNewsList.getNewsHeading());
holder.date.setText(itemNewsList.getNewsDate());
Picasso.with(context).load(Config.SERVER_URL + "/upload/" +
itemNewsList.getNewsImage()).placeholder(R.drawable.ic_thumbnail).into(holder.image);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemNewsList = arrayItemNewsList.get(position);
int pos = Integer.parseInt(itemNewsList.getCatId());
Intent intent = new Intent(context, ActivityNewsDetail.class);
intent.putExtra("POSITION", pos);
JsonConfig.NEWS_ITEMID = itemNewsList.getCatId();
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return arrayItemNewsList.size();
}
}
I also have an API in php :
<?php
include_once ('includes/variables.php');
$connect->set_charset('utf8');
if(isset($_GET['cat_id']))
{
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid=n.cat_id and c.cid='".$_GET['cat_id']."' ORDER BY n.news_heading ASC";
$resouter = mysqli_query($connect, $query);
}
else if(isset($_GET['nid']))
{
$id = $_GET['nid'];
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid = n.cat_id && n.nid = '$id'";
$resouter = mysqli_query($connect, $query);
}
else if(isset($_GET['latest_news']))
{
$limit = $_GET['latest_news'];
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid=n.cat_id ORDER BY n.news_heading ASC";
$resouter = mysqli_query($connect, $query);
}
else
{
$query = "SELECT * FROM tbl_news_category ORDER BY cid DESC";
$resouter = mysqli_query($connect, $query);
}
$set = array();
$total_records = mysqli_num_rows($resouter);
if($total_records >= 1){
while ($link = mysqli_fetch_array($resouter, MYSQLI_ASSOC)){
$set['NewsApp'][] = $link;
}
}
echo $val= str_replace('\\/', '/', json_encode($set));
?>
My problem is on the "else if(isset($_GET['latest_news']))"
Thanks for help
did you try the EndlessRecyclerOnScrollListener ?
You can found it here : https://gist.github.com/ssinss/e06f12ef66c51252563e
This way you could implement paging and you will not load all your stuff the first time you launch your activity.
You have to define a Step. It will be the number of items you will load per page. You will define it, backend (php API) and frontend (Android App).
Backend
You have to add a new parameter on your php API like this :
isset($_GET['page'])
Then your SQL query will look like this :
$page = $_GET['page'];
$step = 5;
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid=n.cat_id and c.cid='".$_GET['cat_id']."' ORDER BY n.news_heading ASC LIMIT ".(($page - 1) * $step) . "," . $step;
Android App
Get the EndlessRecyclerOnScollListener.
Add a private int current_page to your class.
Add a Scroll Listener on your RecyclerView like this :
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(
new LinearLayoutManager(getActivity())) {
#Override
public void onLoadMore() {
CallPhpApi(cat_id, current_page);
}
});
In the CallPhpApi, just call your php API with your new parameter page.
Get your objects from your request and add them to you arrayItemNewsList. Then notify your adapter that dataset changed by calling :
mAdapter.notifyDataSetChanged();
Hope it will help.
I have a problem with admob ads.
The banner ad seems to work fine but the Interstitial is not loading.
I have tried various solutions, generating different ad unit id's and trying admob test ids.
QuoteActivity.java
package com.axdev.thequotesgarden;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
public class QuoteActivity extends ActionBarActivity implements
TextToSpeech.OnInitListener {
private int ID;
private String mode,fav,text;
private Quote qte;
private DataBaseHandler db;
private ArrayList<Quote> myList = new ArrayList<Quote>();
private TextView textAuth,textQuote;
private ImageView imgIcon;
private ImageButton btnNext,btnPrevious;
private TextToSpeech tts;
private RoundImage roundedImage;
private AdView adView;
private InterstitialAd interstitial;
SharedPreferences sharedPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
db = new DataBaseHandler(this);
textAuth = (TextView) findViewById(R.id.textAuth);
textQuote = (TextView) findViewById(R.id.textQuote);
imgIcon = (ImageView) findViewById(R.id.imgcon);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnPrevious = (ImageButton) findViewById(R.id.btn_prev);
Typeface fontQuote = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Light.ttf");
Typeface fontAuth = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Italic.ttf");
textQuote.setTypeface(fontQuote);
textQuote.setTextSize(18);
textAuth.setTypeface(fontAuth);
ID = getIntent().getExtras().getInt("id");
mode = getIntent().getExtras().getString("mode");
if(mode.equals("qteday")){
qte = db.getQuote(ID);
btnNext.setVisibility(View.GONE);
btnPrevious.setVisibility(View.GONE);
}
else {
myList = (ArrayList<Quote>) getIntent().getSerializableExtra("array");
qte = myList.get(ID);}
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID < (myList.size() - 1)) {
ID++;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID > 0) {
ID--;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
fav = qte.getFav();
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuote);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
if(mode.equals("qteday")){
tts = new TextToSpeech(this, this);
speakOut();
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getResources().getString(R.string.interstitial_ad_unit_id));
AdRequest adRequest2 = new AdRequest.Builder().build();
interstitial.loadAd(adRequest2);
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayInterstitial();
}
});
}
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void checkPicure(){
boolean isExist = false;
InputStream imageStream = null;
try {
imageStream = getAssets().open("authors/"+qte.getFileName()+".jpg");
isExist =true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isExist != false){
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
roundedImage = new RoundImage(theImage);
imgIcon.setImageDrawable(roundedImage );
}
else {
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.mipmap.author);
roundedImage = new RoundImage(bm);
imgIcon.setImageDrawable(roundedImage);
}
}
public void doShare() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Quote");
intent.putExtra(Intent.EXTRA_TEXT,
qte.getQuote() + " - " + qte.getName());
QuoteActivity.this.startActivity(Intent.createChooser(intent,
getResources().getString(R.string.share)));
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Locale loc = new Locale("en", "UK");
tts.setLanguage(loc);
tts.setSpeechRate((float) 0.8);
speakOut();
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean speaker = sharedPrefs.getBoolean("prefSpeaker", true);
if (speaker.equals(true)) {
text = qte.getQuote() + "\n" + qte.getName();
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
else {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quote, menu);
if (fav.equals("0")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.not_fav);
}
if (fav.equals("1")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.fav);
}
;
return true;
}
#TargetApi(11)
private void copyToClipBoard(String qte) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(qte);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("text", qte);
clipboard.setPrimaryClip(clip);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
case R.id.action_share:
doShare();
break;
case R.id.copy:
String text = qte.getQuote() + "- " + qte.getName();
copyToClipBoard(text);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.copy_msg),
Toast.LENGTH_LONG).show();
break;
case R.id.action_favorite:
if (qte.getFav().equals("0")) {
qte.setFav("1");
db.updateQuote(qte);
item.setIcon(R.mipmap.fav);
} else if (qte.getFav().equals("1")) {
qte.setFav("0");
db.updateQuote(qte);
item.setIcon(R.mipmap.not_fav);
}
}
return true;
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
QuotesActivity.java
package com.axdev.thequotesgarden;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import java.util.ArrayList;
import java.util.List;
public class QuotesActivity extends ActionBarActivity {
private ArrayList<Quote> imageArry = new ArrayList<Quote>();
private QuotesListAdapter adapter;
private String Activitytype;
private DataBaseHandler db;
private ListView dataList;
private int count;
private ImageView noQuotes;
private AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
db = new DataBaseHandler(this);
noQuotes = (ImageView)findViewById(R.id.NoQuotes);
adapter = new QuotesListAdapter(this, R.layout.quote_items, imageArry);
dataList = (ListView) findViewById(R.id.quotesList);
Button btnLoadMore = new Button(this);
btnLoadMore.setBackgroundResource(R.drawable.btn_green);
btnLoadMore.setText(getResources().getText(R.string.btn_LoadMore));
btnLoadMore.setTextColor(0xffffffff);
Activitytype = getIntent().getExtras().getString("mode");
if (Activitytype.equals("isCategory")) {
String categoryValue = getIntent().getExtras()
.getString("category");
List<Quote> contacts = db.getQuotesByCategory(categoryValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
}
if (Activitytype.equals("isAuthor")) {
String authorValue = getIntent().getExtras().getString("name");
List<Quote> contacts = db.getQuotesByAuthor(authorValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
}
if (Activitytype.equals("isFavorite")) {
actionBar.setTitle(getResources().getText(R.string.title_activity_favorites));
List<Quote> contacts = db.getFavorites();
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
if (imageArry.isEmpty()){
noQuotes.setVisibility(View.VISIBLE);
}
}
if (Activitytype.equals("allQuotes")) {
List<Quote> contacts = db.getAllQuotes(" LIMIT 50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
dataList.addFooterView(btnLoadMore);
}
dataList.setAdapter(adapter);
dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
Intent i = new Intent(getApplicationContext(),
QuoteActivity.class);
Quote srr = imageArry.get(position);
i.putExtra("id",position);
i.putExtra("array", imageArry);
i.putExtra("mode", "");
startActivity(i);
}
});
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new loadMoreListView().execute();
}
});
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuotes);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Before starting background task
// Show Progress Dialog etc,.
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
count += 50;
List<Quote> contacts = db.getAllQuotes(" LIMIT "+count+ ",50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
int currentPosition = dataList.getFirstVisiblePosition();
adapter = new QuotesListAdapter(QuotesActivity.this, R.layout.quote_items, imageArry);
dataList.setSelectionFromTop(currentPosition + 1, 0);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
}
}
#Override
public void onBackPressed()
{
finish();
super.onBackPressed(); // optional depending on your needs
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quotes, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
}
return true;
}
}
The simplest answer is that mode is not equal to "qteday"
if(mode.equals("qteday")){
Unless that is true, the interstitial will never be loaded.
May I ask why my onResume() DialogInterface keeps looping non stop? I have reference the onResume() from this website: http://pulse7.net/android/android-delete-sms-message-from-inbox-in-android/
#Override
protected void onResume() {
super.onResume(); int i=0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if(i==0) {
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMain_txt.this);
builder.setMessage("This app is not set as your default messaging app. Do you want to set it as default?")
.setCancelable(false)
.setTitle("Alert!")
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#TargetApi(19)
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);
dialog.dismiss();
}
});
builder.show();
i++;}
}
}
But when I add this part of the code, the DialogInterface for "setPositiveButton" keeps looping non-stop. I am trying to set my application to become the default message application, so I will be able to delete messages. As now it is not set to become the default application, I am unable to delete any messages successfully. Any help will be deeply appreciated. Thanks in advance.
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.provider.Telephony;
import com.example.apple.qs.Activity.db.Constant;
import com.example.apple.qs.Activity.db.DatabaseHandler_txt;
import com.example.apple.qs.Activity.fragment.ContactFragment;
import com.example.apple.qs.Activity.fragment.FragmentAdapter;
import com.example.apple.qs.Activity.fragment.MessageFragment;
import com.example.apple.qs.Activity.db.model.Message;
import com.example.apple.qs.Activity.db.Store.ContactStore;
import com.example.apple.qs.Activity.db.Store.MessageStore;
import java.util.ArrayList;
import com.example.apple.qs.Activity.R;
import java.util.List;
public class ActivityMain_txt extends AppCompatActivity {
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar toolbar;
private DrawerLayout drawerLayout;
public static MessageFragment f_message;
private ContactFragment f_contact;
public FloatingActionButton fab;
private Toolbar searchToolbar;
private boolean isSearch = false;
private ViewPager viewPager;
private DatabaseHandler_txt db;
public ContactStore contacsStore;
public MessageStore messageStore;
public static List<Message> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_txt);
setupDrawerLayout();
db = new DatabaseHandler_txt(getApplicationContext());
toolbar = (Toolbar) findViewById(R.id.toolbar_viewpager);
searchToolbar = (Toolbar) findViewById(R.id.toolbar_search);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ActivityNewMessage_txt.class);
startActivity(i);
}
});
//initToolbar();
prepareActionBar(toolbar);
contacsStore = new ContactStore(getApplicationContext());
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
closeSearch();
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0) {
fab.show();
} else {
fab.hide();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// for system bar in lollipop
Window window = this.getWindow();
if (Constant.getAPIVerison() >= 5.0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
}
}
private void setupViewPager(ViewPager viewPager) {
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
if (f_message == null) {
f_message = new MessageFragment();
}
if (f_contact == null) {
f_contact = new ContactFragment();
}
adapter.addFragment(f_message, "MESSAGE");
adapter.addFragment(f_contact, "CONTACT");
viewPager.setAdapter(adapter);
}
private void prepareActionBar(Toolbar toolbar) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(getResources().getColor(isSearch ? android.R.color.darker_gray : R.color.colorPrimary));
}
if (!isSearch) {
settingDrawer();
}
}
private void settingDrawer() {
mDrawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close ) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(mDrawerToggle);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.nav_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
actionDrawerMenu(menuItem.getItemId());
return true;
}
});
}
private void actionDrawerMenu(int itemId) {
switch (itemId) {
case R.id.nav_notif:
Intent i = new Intent(getApplicationContext(), ActivityNotificationSettings_txt.class);
startActivity(i);
break;
case R.id.nav_rate:
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
break;
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About");
builder.setMessage(getString(R.string.about_text));
builder.setNeutralButton("OK", null);
builder.show();
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (!isSearch) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(isSearch ? R.menu.menu_search_toolbar_txt : R.menu.menu_main_txt, menu);
if (isSearch) {
//Toast.makeText(getApplicationContext(), "Search " + isSearch, Toast.LENGTH_SHORT).show();
final SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setIconified(false);
if (viewPager.getCurrentItem() == 0) {
search.setQueryHint("Search message...");
} else {
search.setQueryHint("Search contact...");
}
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter(s);
} else {
f_contact.mAdapter.getFilter().filter(s);
}
return true;
}
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
closeSearch();
return true;
}
});
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search: {
isSearch = true;
searchToolbar.setVisibility(View.VISIBLE);
prepareActionBar(searchToolbar);
supportInvalidateOptionsMenu();
return true;
}
case android.R.id.home:
closeSearch();
return true;
case R.id.action_refresh: {
if(viewPager.getCurrentItem()==0){
new RefreshMessage().execute("");
}else{
new RefreshContact().execute("");
}
}
default:
return super.onOptionsItemSelected(item);
}
}
private void closeSearch() {
if (isSearch) {
isSearch = false;
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter("");
} else {
f_contact.mAdapter.getFilter().filter("");
}
prepareActionBar(toolbar);
searchToolbar.setVisibility(View.GONE);
supportInvalidateOptionsMenu();
}
}
private ChangeObserver changeObserver;
// wil update only when there a change
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
try{
if(!loadRunning) {
loadRunning = true;
changeLoad = new ChangeLoad();
changeLoad.execute("");
}
}catch (Exception e){
}
}
}
private ChangeLoad changeLoad;
private boolean loadRunning = false;
private class ChangeLoad extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
messageStore.update();
return null;
}
#Override
protected void onPostExecute(String s) {
loadRunning = false;
messageList = messageStore.getAllconversation();
f_message.bindView();
super.onPostExecute(s);
}
}
public class RefreshMessage extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_message.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(100);
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_message.onStopRefreshLoading();
super.onPostExecute(s);
}
}
private class RefreshContact extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_contact.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(10);
db.truncateDB();
contacsStore = new ContactStore(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_contact.onStopRefreshLoading();
super.onPostExecute(s);
}
}
String myPackageName= getPackageName();
#Override
protected void onResume() {
super.onResume(); int i=0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if(i==0) {
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMain_txt.this);
builder.setMessage("This app is not set as your default messaging app. Do you want to set it as default?")
.setCancelable(false)
.setTitle("Alert!")
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#TargetApi(19)
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);
dialog.dismiss();
}
});
builder.show();
i++;}
}
}
}
}
You are using the variable i as a flag, but whenever you open your app the value of i will be 0 again. You should store your flag in a persistent database. Either use SQLite to set i or use any other method like create a file when the user says yes to your question and then check if the file exists or not. If you don't understand what I've told you, I can send you some code snippets.
OK, I assume you are using i as a flag to check if user has set your app as default or not, so I suggest you to use SharedPreferences to store the value of i so that later on you can check the value of i in a better manner. Add the following code in your onResume function:
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
Instead of i++ use:
editor.putInt(i, 1);
editor.commit();
And to check if i==0 use:
int check =sharedprferences.getInt(i);
if(check == 0) {...........}
I'm a beginner on Android and this is the first I'm creating an app named GeoQuiz which basically has a few questions and the user has to click true/false or request the answer with the cheat button.I'm getting this one line of error related with a non-static an a static context in line 138,what am I doing wrong? I'm trying that every time i click on the button cheat, it open the other window that is under a different .xml file and in an another java class
package com.example.fusion.geoquiz;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
import android.content.Intent;
import android.content.Intent;
import java.util.*;
import static com.example.fusion.geoquiz.R.string.correct_toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private ProgressBar mProgress;
private Button mCheatButton;
private int mProgressStatus = 0;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private int checker = 0;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
private void disablePrev(){
if(mCurrentIndex== 0){
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(false);
}
else{
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(true);
}
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
checker++;
if(checker >0) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
//mProgressStatus=checker;
//mProgress.setProgress(mProgressStatus);
disablePrev();
}
} else {
messageResId = R.string.incorrect_toast;
checker = 0;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
disablePrev();
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
updateQuestion();
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(false);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
disablePrev();
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurrentIndex != 0){
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mQuestionTextView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
}
});
disablePrev();
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quiz, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the class for the cheat class and cheatButton
package com.example.fusion.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
/**
* Created by fusion on 1/21/2015.
*/
public class cheatActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
}
}
Replace
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
with
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
See the docs for more details..
Not sure what you're doing there, but you need to reference the other activity class. Simply calling startActivity is enough, because it will be implicitly called from QuizActivity.this.
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
To save you from future errors choose one activity class that you will be using either Activity or ActionBarActivity. The latter is from the support package.