How do I know the state of the ToggleButton from another activity?
i have class
public class MainScreen extends Activity{
protected ToggleButton tgbutton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
tgbutton = (ToggleButton)findViewById(R.id.advice);
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
tgbutton.setChecked(sharedPreferences.getBoolean("toggleButton", false));
}
public void oneClick(View v) {
if(tgbutton.isChecked() == false) { playSound(mSound); }
else { pauseSound(mSound); }
}
}
and
public class SmallprintA extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smallprint_a);
OnClickListener SendOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(tgbutton.isChecked() == true){ playSound(mEmpty); }
else { playSound(mEmpty); }
}
};
}
I need in the class SmallprintA determine the state of the ToggleButton tgbutton. This is possible without class inheritance?
I did tgbutton is static
public class MainScreen extends Activity{
protected static ToggleButton tgbutton; // STATIC
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
tgbutton = (ToggleButton)findViewById(R.id.advice);
}
public void oneClick(View v) {
if(tgbutton.isChecked() == false) { playSound(mSound); }
else { pauseSound(mSound); }
}
}
and
public class SmallprintA extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smallprint_a);
OnClickListener SendOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(MainScreen.tgbutton.isChecked() == true){ playSound(mEmpty); }
else { playSound(mEmpty); }
}
};
}
Related
I created a day/night mode switch system in my app. Currently, I use a PreferenceFragmentCompat + SharedPreference to display and save the switch selection.
This is my code:
public class PreferencesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
PreferencesFragment preferencesFragment = new PreferencesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.preferences_container, preferencesFragment).commit();
}
public static class PreferencesFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (isAdded()) {
if (sharedPreferences.getBoolean(getString(R.string.KEY_PREF_NIGHT_MODE), false)) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
}
}
On top of that, I use the following code in the OnCreate method of my main Activity:
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int mode = sharedPreferences.getBoolean(getString(R.string.KEY_PREF_NIGHT_MODE), false) ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO;
if (AppCompatDelegate.getDefaultNightMode() != mode)
AppCompatDelegate.setDefaultNightMode(mode);
The problem is that when I activate the dark mode and I restart the application, it will launch then restart in the onCreate. Isn't there a more optimal way to implement this system?
you could create BaseActivity where you set the night mode
abstract class BaseActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
}
and then extend all your Activites from BaseActivity
public class PreferencesActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
}
then your night mode would be set in every activity before setContentView and no relaunch would be occured
UPDATE
change
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
to
#Override
public void onStart() {
super.onStart();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
onStart is called before view is visible
UPDATE 2
here is the singleton to access SharedPreferences
public class SharedManager {
private static SharedManager instance;
private final SharedPreferences preferences;
private SharedManager() {
preferences = MyApplication.getAppContext().getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
}
public static SharedManager getInstance() {
if (instance == null) {
synchronized (SharedManager.class) {
if (instance == null) {
instance = new SharedManager();
}
}
}
return instance;
}
public SharedPreferences getPreferences() {
return preferences;
}
}
with call SharedManager.getInstance().getPreferences() you can get access to Preferences
I have listed the code below, What i am trying to achieve is the int i to be updated from a dialog box (dialog2). I then want to check in the main activity if it has changed and if it has changed then call a method. How would i do this?
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int i = 0;
Dialog1 dialog1 = new Dialog1(this, i);
dialog1.show();
}
//Want to call this method whenever I is modified
private void iModified(){
}
}
Dialog 1 Class (This dialog just passes it to dialog2)
public class Dialog1 extends Dialog{
int integerI;
Button button;
public Dialog1(final Activity activity, final int i){
super(activity);
setContentView(R.layout.dialog1);
integerI = i;
button = findViewById(R.id.dialog1Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog2 dialog2 = new Dialog2(activity ,integerI);
dialog2.show();
closeDialog();
}
});
}
private void closeDialog(){
this.dismiss();
}
}
Dialog 2: This is where the integer is going to be changed and then i want it to be sent to the main activity and checked if it has changed and if so then replace the old integer with the new one.
public class Dialog2 extends Dialog {
int newI;
Button button;
public Dialog2(Activity activity, int i) {
super(activity);
setContentView(R.layout.dialog2);
newI= i + 12345;
button = findViewById(R.id.dialog2Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
close();
}
});
}
private void close(){
this.dismiss();
}
}
You can use interface.
your activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int i = 0;
Dialog1 dialog1 = new Dialog1(this, i, new ModifiedListener() {
#Override
public void notify(int i) {
iModified();
}
});
dialog1.show();
}
//Want to call this method whenever I is modified
private void iModified(){
}
}
your dialog1:
public class Dialog1 extends Dialog {
int integerI;
Button button;
public Dialog1(final Activity activity, final int i, final ModifiedListener listener) {
super(activity);
setContentView(R.layout.dialog1);
integerI = i;
button = findViewById(R.id.dialog1Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog2 dialog2 = new Dialog2(activity, integerI);
dialog2.show();
closeDialog();
}
});
}
private void closeDialog() {
this.dismiss();
}
}
your dialog 2:
public class Dialog2 extends Dialog {
int newI;
Button button;
public Dialog2(Activity activity, int i, final ModifiedListener listener) {
super(activity);
setContentView(R.layout.dialog2);
newI = i + 12345;
//when you modify int you have to call
listener.notify(newI);
button = findViewById(R.id.dialog2Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
close();
}
});
}
private void close() {
this.dismiss();
}
}
define interface similar to class:
public interface ModifiedListener {
public void notify(int i);
}
I use loader to do task in back ground in method loadInBackground i added for loop to print log in logcat 50 time , so when i click the button start print log in logcat
but when i click the button i don't have any action and i don't have ant error , what is problem ?
mainActicity
public class MainActivity extends AppCompatActivity implements android.app.LoaderManager.LoaderCallbacks<String> {
TextView textView;
android.app.LoaderManager loaderManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loaderManager=getLoaderManager();
textView=findViewById(R.id.tv_result);
if (loaderManager.getLoader(0) ==null){
loaderManager.initLoader(0,null,this);
}
}
public void StartMysynstack (View view){
loaderManager.initLoader(0,null,this);
}
#Override
public android.content.Loader<String> onCreateLoader(int i, Bundle bundle) {
return new Myloader(this);
}
#Override
public void onLoadFinished(android.content.Loader<String> loader, String s) {
textView.setText(s);
}
#Override
public void onLoaderReset(android.content.Loader<String> loader) {
}
}
my loader
public class Myloader extends AsyncTaskLoader<String> {
int i;
public Myloader(Context context) {
super(context);
}
#Override
public String loadInBackground() {
for( i=0;i<=100;i++){
try {
Thread.sleep(50);
Log.d("waad","loadInBackground"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task result";
}
}
you can try calling it manually.
getLoaderManager().initLoader(0, null, this).forceLoad();
so according to your code you can make following changes.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loaderManager=getLoaderManager();
textView=findViewById(R.id.tv_result);
if (loaderManager.getLoader(0) ==null){
loaderManager.initLoader(0,null,this).forceLoad();;
}
}
I have an AppCompatPreferenceActivity.java. But it shows an error in this
public class SettingsActivity extends AppCompatPreferenceActivity
It says it couldn't resolve 'AppCompatPreferenceActivity'.
And it seems like I am the only one with this problem. Any idea?
Error:(21, 39) error: cannot find symbol class AppCompatPreferenceActivity
AppCompatPreferenceActivity does not existing in google support libary,
you should create a class with same name and use this source:
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
I have the following fragment.The problem is that every time I launch this the app crashes with the following exception : attempt to invoke virtual method android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext() on a null object reference. From what I understand getActivity is called correctly, however the FragmentActivityTesting does not return any context, I'm not sure why this is the case:
public class FragmentATesting extends Fragment {
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a,container,false);
}
#Override
public void onActivityCreated(Bundle SavedInstanceState){
super.onActivityCreated(SavedInstanceState);
}
#Override
public void onStart() {
super.onStart();
final SessionManager session = new SessionManager(getActivity().getApplicationContext());
TextView username = (TextView) getView().findViewById(R.id.username_info_txt);
HashMap<String,String> userString = session.getUserDetails();
String usernamee = userString.get("username");
username.setText(usernamee);
vote(usernamee);
}
#Override
public void onResume() {
super.onResume();
final SessionManager session = new SessionManager(getActivity().getApplicationContext());
TextView username = (TextView) getView().findViewById(R.id.username_info_txt);
HashMap<String,String> userString = session.getUserDetails();
String usernamee = userString.get("username");
username.setText(usernamee);
vote(usernamee);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void vote(final String userId) {
class UploadImage extends AsyncTask<String, Void, String> {
RequestHandler rh = new RequestHandler();
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("username",userId);
String result = rh.sendPostRequest(SL_URL2, data);
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSONObject jsonObject = null;
String likess = "";
try {
jsonObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
try {
likess = jsonObject.getString("amount");
} catch (JSONException e) {
e.printStackTrace();
}
TextView amount = (TextView) getView().findViewById(R.id.likes_info_txt);
amount.setText(likess + " Likes");
}}
UploadImage ui = new UploadImage();
ui.execute();
}`
It is inside my ViewPager defined as follows:
public class FragmentActivityTesting extends FragmentActivity {
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_activity_testing);
viewPager = (ViewPager) findViewById(R.id.pic_pager);
setStatusBarColor();
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
viewPager.setCurrentItem(1);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("CLOSE_ALL");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
#TargetApi(21)
public void setStatusBarColor() {
Window window = this.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Integer.valueOf(android.os.Build.VERSION.SDK) >= 21) {
window.setStatusBarColor(this.getResources().getColor(R.color.green));
}
}}
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position ==0) {
fragment = new FragmentATesting();
}
else if (position == 1) {
fragment = new FragmentBTesting();
}
else if (position == 2) {
fragment = new FragmentCTesting();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}