I tried using an Inflater to check whether the Switch responsible for activating and deactivating night mode in my Settings activity is enabled or not. The MainActivity doesn't remember the night mode state after relaunching the app.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.activity_settings, null);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
view.findViewById(R.id.night_mode);
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.settings) {
Intent myintent = new Intent(MainActivity.this, Settings.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
Settings.java:
public class Settings extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(final Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.calculator) {
Intent myintent = new Intent (Settings.this, MainActivity.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
I'm not sure what the reason for this is.
Related
I know how to add items to RecyclerView and show them, but let's say I add some dynamic items to the RecyclerView like this image
Here After click save button, it creates three rows in the RecyclerView like below image, which I don't want it creates three rows.
Instead I want to create one row, and when I clicked in that row then shows the three items like this image.
AddChecklist class
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
dbHelper = new DbHelper(this);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView(){
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
CheckBox checkBox = checklistView.findViewById(R.id.check_box);
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
}
else
checklistHelper.setStatus("0");
dbHelper.insertChecklist(checklistHelper.getStatus(), etChecklistItem.getText().toString(), DateTime.date(), DateTime.time(), System.currentTimeMillis());
}
finish();
break;
}
return true;
}
}
Adapter class
public class ChecklistItems extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
String content;
String status;
boolean isEditChecklist = false;
private ChecklistAdapter checklistAdapter;
DbHelper dbHelper;
List<ChecklistHelper> checks;
int id;
ChecklistHelper checklistHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
checks = dbHelper.getChecklists();
checklistAdapter = new ChecklistAdapter(checks);
recyclerView.setAdapter(checklistAdapter);
}
public class ChecklistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private boolean isEnableDelete = false;
List<ChecklistHelper> checkList;
public ChecklistAdapter(List<ChecklistHelper> checkList) {
this.checkList = checkList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.checklist_layout_child, parent, false);
return new ChecklistChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChecklistChildViewHolder checklistChildViewHolder = (ChecklistChildViewHolder) holder;
checklistChildViewHolder.updateVisibility(isEnableDelete);
checklistChildViewHolder.checkBox.setText(checkList.get(position).getContent());
checklistChildViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String txt = checklistChildViewHolder.checkBox.getText().toString();
if (b)
checklistChildViewHolder.checkBox.setText(lineThrough(txt));
else
checklistChildViewHolder.checkBox.setText(txt);
}
});
checklistChildViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dbHelper.deleteChecklist(id);
finish();
}
});
}
#Override
public int getItemCount() {
return checkList.size();
}
public void updateItems(boolean isEnableDelete){
this.isEnableDelete = isEnableDelete;
notifyDataSetChanged();
}
public class ChecklistChildViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
ImageView delete, edit;
ChecklistChildViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkbox_child);
delete = itemView.findViewById(R.id.delete_child);
edit = itemView.findViewById(R.id.edit_child);
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
public void updateVisibility(boolean isEnableDelete){
if (isEnableDelete) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
else {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(this);
// long id = getIntent().getIntExtra("id", 0);
switch (item.getItemId()) {
case R.id.edit:
isEditChecklist = true;
checklistAdapter.updateItems(true);
invalidateOptionsMenu();
break;
case R.id.save:
Toast.makeText(getApplicationContext(), "saved ", Toast.LENGTH_SHORT).show();
checklistAdapter.updateItems(false);
isEditChecklist = false;
finish();
break;
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Checklist");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Continue ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbHelper.deleteChecklist(id);
// checklistAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "checklist deleted", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
break;
}
return true;
}
}
Please solve my error.I am unable to figure out.
When I click on submit button,my app crashes.Why?Let me know if you want any more input from my side.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
EditText txt1, txt2,txt3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.button);
txt1=findViewById(R.id.editTextTextPersonName);
txt2=findViewById(R.id.editTextTextEmailAddress2);
txt3=findViewById(R.id.editTextTextPassword);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogged=pref.getBoolean("key3",false);
if (islogged){
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = txt2.getText().toString();
String password = txt3.getText().toString();
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref.edit();
ed.putString("key1", email);
ed.putString("key2", password);
ed.putBoolean("key3",true);
ed.apply();
}
});
}
}
MainActivity2.java
public class MainActivity2 extends AppCompatActivity {
Button btn;
EditText txt1, txt2;
CheckBox keeplog;
Boolean b=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btn=findViewById(R.id.login);
txt1=findViewById(R.id.loginemail);
txt2=findViewById(R.id.loginpassword);
keeplog=findViewById(R.id.checkBox);
keeplog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
b=isChecked;
}
});
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogin=pref.getBoolean("key4",false);
if (islogin){
Intent i=new Intent(MainActivity2.this,HomeScreen.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
String email = pref.getString("key1", null);
String password = pref.getString("key2", null);
String email2 = txt1.getText().toString();
String password2 = txt2.getText().toString();
SharedPreferences pref2 = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref2.edit();
ed.putBoolean("key4",b);
ed.apply();
if (email.equals(email2) && password.equals(password2)) {
Intent i = new Intent(MainActivity2.this, HomeScreen.class);
startActivity(i);
finish();
}
}
});
HomeScreen.java
public class HomeScreen extends AppCompatActivity{
Button button1,button2;
EditText n;
ProgressDialog pd;
String Note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Toast.makeText(this, "Welcome Home", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.id1) {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
n = (EditText) dialogView.findViewById(R.id.edt_comment);
button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
dialogBuilder.setView(dialogView);
dialogBuilder.show();
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SAVETASK();
// dialogBuilder.dismiss();
}
});
} else if (item.getItemId() == R.id.id2) {
startActivity(new Intent(HomeScreen.this,MainActivity2.class));
}
return super.onOptionsItemSelected(item);
}
public void SAVETASK() {
Note = n.getText().toString();
//password = txt2.getText().toString();
class Savedata extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(HomeScreen.this);
pd.setTitle("Saving data");
pd.setMessage("Please Wailt");
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
Task task = new Task();
task.setNote(Note);
DatabaseClient.getInstance(getApplicationContext()).getAppDatabase().taskdao().insert(task);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.dismiss();
Toast.makeText(HomeScreen.this, "Data inserted", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(HomeScreen.this, MainActivity2.class);
// startActivity(intent);
}
}
Savedata savedata = new Savedata();
savedata.execute();
}
}
Task.java
#Entity
public class Task implements Serializable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "name")
private String Note;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return Note;
}
public void setNote(String note) {
Note = note;
}
}
TaskDao.java
#Dao
public interface TaskDao {
#Query("select * from task")
List<Task> getalldata();
#Insert
void insert(Task task);
#Update
void update(Task task);
#Delete
void Delete(Task task);
}
AppDatabase.java
public abstract class AppDatabase extends RoomDatabase {
public abstract TaskDao taskdao();
}
DatabaseClient.java
public class DatabaseClient {
private Context context;
private static DatabaseClient mInstance;
private AppDatabase appDatabase;
private DatabaseClient(Context mctx)
{
this.context=mctx;
appDatabase= Room.databaseBuilder(mctx,AppDatabase.class,"MYTODO").build();
}
public static synchronized DatabaseClient getInstance(Context context)
{
if(mInstance==null)
{
mInstance=new DatabaseClient(context);
}
return mInstance;
}
public AppDatabase getAppDatabase()
{
return appDatabase;
}
}
Logcat error:
com.example.sharedprefdemo E/WindowManager: android.view.WindowLeaked: Activity com.example.sharedprefdemo.HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:765)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:429)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:473)
at com.example.sharedprefdemo.HomeScreen$1Savedata.onPreExecute(HomeScreen.java:95)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:708)
at android.os.AsyncTask.execute(AsyncTask.java:655)
at com.example.sharedprefdemo.HomeScreen.SAVETASK(HomeScreen.java:117)
at com.example.sharedprefdemo.HomeScreen$2.onClick(HomeScreen.java:70)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
So when I click on submit button,my app crashes automatically.I dont know what is the reason.
Before showing dialog
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();//or cancel()
}
Try moving the dialog and its initialization from asyncthread
HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
answer to this error
I've been working on the Android SDK platform, and it is a bit unclear how to save an application's state. I'm creating a menu which has CheckBoxes. I do get the idea of SharedPreferences but I'm not able to get my head around the implementation of SharedPreferences in CheckBoxes.
I want those checkboxes (multiple checkboxes) stay checked/unchecked even if the user relaunches the app.
public class MainActivity extends AppCompatActivity {
protected WebView myWebView;
protected TextView text_selection;
protected TextView mOutputText;
public static final String TAG = "mytag";
protected SharedPreferences sharedPreferences;
protected SharedPreferences.Editor editor;
private final String PREFERENCE_FILE_KEY = "myAppPreference";
private Context context;
protected CheckBox animal, fisheries, dairy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
//sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
//Context context = getActivity();
//SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("animal", false);
editor.putBoolean("fisheries", false);
editor.putBoolean("dairy", false);
//editor.putBoolean("checkbox", checkbox.isChecked()));
editor.commit();
this.myWebView = (WebView) findViewById(R.id.webview);
this.text_selection = findViewById(R.id.text_selected);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("------");
//mOutputText = (TextView) findViewById(R.id.tv_output);
mOutputText = findViewById(R.id.textView);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if(task.isSuccessful()){
String token=task.getResult().getToken();
Log.d(TAG, "onComplete: Token: "+token);
mOutputText.setText("Token has been generated");
}else{
mOutputText.setText("Token failed");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
if (sharedPreferences.getBoolean("animal", false)) {
// findItem id function return the id of the menu
menu.findItem(R.id.animal).setChecked(true);
} else if (sharedPreferences.getBoolean("fisheries", false)) {
menu.findItem(R.id.fisheries).setChecked(true);
} else if (sharedPreferences.getBoolean("dairy", false)) {
menu.findItem(R.id.dairy).setChecked(true);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("animal", false);
} else {
item.setChecked(true);
editor.putBoolean("animal", true);
}
break;
case R.id.fisheries:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("fisheries", false);
} else {
item.setChecked(true);
editor.putBoolean("fisheries", true);
}
break;
case R.id.dairy:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("dairy", false);
} else {
item.setChecked(true);
editor.putBoolean("dairy", true);
}
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
}
Below example;
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
editor.putBoolean("dairy", isChecked);
editor.commit();
}
});
Replace the beginning stuff in your onCreate with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
animal.setChecked(getCheckboxStatus("animal"));
animal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("animal", isChecked);
}
}
);
fisheries.setChecked(getCheckboxStatus("fisheries"));
fisheries.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("fisheries", isChecked);
}
}
);
dairy.setChecked(getCheckboxStatus("dairy"));
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("dairy", isChecked);
}
}
);
// Your WebView and Firebase stuff
}
private void saveCheckBoxValue(String key, boolean isChecked) {
editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean getCheckboxStatus(String key) {
return sharedPreferences.getBoolean(key, false);
}
Change the onCreateOptionsMenu function to the following:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
menu.findItem(R.id.animal).setChecked(sharedPreferences.getBoolean("animal", false));
menu.findItem(R.id.fisheries).setChecked(sharedPreferences.getBoolean("fisheries", false));
menu.findItem(R.id.dairy).setChecked(sharedPreferences.getBoolean("dairy", false));
return true;
}
Change the onOptionsItemSelected function to:
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
editor.putBoolean("animal", item.isChecked());
break;
case R.id.fisheries:
editor.putBoolean("fisheries", item.isChecked());
break;
case R.id.dairy:
editor.putBoolean("dairy", item.isChecked());
break;
}
editor.apply();
return super.onOptionsItemSelected(item);
}
I want to send data from EditText in child activity to parent activity (MainActivity) and use it as a string parameter (URL) in other methods
Already I am able to send this using intent and extras, also I added textview in method to see if it works, but finally, this textview will be deleted, but I can't use it in other methods
public class MainActivity extends AppCompatActivity implements OnDataSendToActivity {
ImageView bg_state;
Button btn_rl;
TextView txt_network;
String url;
String my_url;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bg_state = findViewById(R.id.bg_status);
txt_network = findViewById(R.id.txt_network);
Toolbar toolbar= findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tv=findViewById(R.id.tV);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(isNetworkAvailable()){
bg_state.setImageResource(R.drawable.background);
txt_network.setText("");
}else{
bg_state.setImageResource(R.drawable.background_on);
txt_network.setText("Cound not connect to the server");
}
updateStatus();
handler.postDelayed(this, 2000);
}
}, 5000); //the time is in miliseconds
btn_rl = findViewById(R.id.sw_1);
btn_rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url_rl = my_url+"room_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});
String url_rl = url+"bed_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==R.id.conf){
Intent intent_conf = new Intent(MainActivity.this, Configuration.class);
startActivityForResult(intent_conf,1);
return false;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1){
if(resultCode==RESULT_OK){
url=data.getStringExtra("url");
my_url="http://"+url;
tv.setText(my_url);
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void sendData(String str) {
updateButtonStatus(str);
}
private void updateStatus(){
String url_rl = my_url+"status";
StatusTask task = new StatusTask(url_rl, this);
task.execute();
}
//Function for updating Button Status
private void updateButtonStatus(String jsonStrings){
try {
JSONObject json = new JSONObject(jsonStrings);
String room_light = json.getString("rl");
if(room_light.equals("1")){
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90off);
}else{
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90on);
}
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.power_off);
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
childactivity
public class Configuration extends AppCompatActivity {
public String new_url;
EditText ip_text;
Button sub_btn;
String a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
Toolbar tool = findViewById(R.id.toolbar);
setSupportActionBar(tool);
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
findViewById(R.id.wifi_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUrl("https://192.168.4.1");
}
});
ip_text = findViewById(R.id.ip_text);
sub_btn= findViewById(R.id.sub_btn);
sub_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Configuration.this,MainActivity.class);
new_url=ip_text.getText().toString();
i.putExtra("url",new_url);
setResult(RESULT_OK,i);
finish();
}
});
}
}
What I need is that if I write in Configuration class for example 192.168.xx.xx In mainactivity my_url will be my_url="https://192.168/ and it will be able to use in other methods as a parameter (for example in btn_rl.setOnClickListener).
The Reason is the interstitial ad is on wrong way.
Can someone tell me Is there a problem with my interstitial?
Where to put it?
My code from where interstitial is:
public class ActivityMain extends Activity implements OnItemClickListener,
onWelComeButtonClickListener, OnClickListener {
MatrixCursor cursor;
ActionBar actionBar;
DrawerLayout dLayout;
ListView channelListView;
ChannelCustomAdapter adapter;
ActionBarDrawerToggle toggle;
CharSequence title;
Bundle bundle;
Menu menu;
RelativeLayout rlDrawerOpen;
Typeface selectFonts;
TextView tFacebook, tRateus;
AdRequest fullScreenAdRequest;
InterstitialAd fullScreenAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializer();
dLayout.setDrawerListener(toggle);
channelListView.setOnItemClickListener(this);
tFacebook.setOnClickListener(this);
tRateus.setOnClickListener(this);
enableAd();
}
private void enableAd() {
// adding full screen add
fullScreenAdd = new InterstitialAd(this);
fullScreenAdd.setAdUnitId("a151b7d316a5c1d");
fullScreenAdRequest = new AdRequest.Builder().build();
fullScreenAdd.loadAd(fullScreenAdRequest);
fullScreenAdd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.i("FullScreenAdd", "Loaded successfully");
fullScreenAdd.show();
}
#Override
public void onAdFailedToLoad(int errorCode) {
Log.i("FullScreenAdd", "failed to Load");
}
});
}
private void initializer() {
actionBar = getActionBar();
selectFonts = (Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Bold.ttf"));
dLayout = (DrawerLayout) findViewById(R.id.dl_drawerLayout);
rlDrawerOpen = (RelativeLayout) findViewById(R.id.rl_drawer_open);
channelListView = (ListView) findViewById(R.id.lv_channel_List);
title = getResources().getString(R.string.app_name);
tFacebook = (TextView) findViewById(R.id.tvFacbook);
tRateus = (TextView) findViewById(R.id.tvRateUs);
adapter = new ChannelCustomAdapter(this, GlobalData.getInstance()
.getArrChannels());
channelListView.setAdapter(adapter);
toggle = new ActionBarDrawerToggle(this, dLayout, R.drawable.ic_drawer,
R.string.app_name, R.string.app_name) {
#Override
public void onDrawerOpened(View drawerView) {
setTitle("Select Channel");
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
setTitle(title);
invalidateOptionsMenu();
}
};
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
// use the query to search your data somehow
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG)
.show();
} else {
fragmentSelector();
}
}
private void fragmentSelector() {
bundle = getIntent().getBundleExtra("BUNDLE");
if (bundle == null) {
Fragment fr = new WelcomeFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
setTitle(title);
((WelcomeFragment) fr).setOnWelComeButtonClickListener(this);
} else {
selectItem(bundle.getInt("POS"));
setTitle(bundle.getString("NAME"));
}
}
public void selectItem(int position) {
Fragment fr = new RadioFragment();
bundle = new Bundle();
bundle.putString("URL",
GlobalData.getInstance().getArrChannels().get(position)
.getUrl());
bundle.putString("NAME",
GlobalData.getInstance().getArrChannels().get(position)
.getChannelName());
bundle.putInt("POS", position);
fr.setArguments(bundle);
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
title = GlobalData.getInstance().getArrChannels().get(position)
.getChannelName();
dLayout.closeDrawer(rlDrawerOpen);
}
#Override
public void setTitle(CharSequence title) {
actionBar.setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (getPositionfromString(query) != -1) {
Intent intent = new Intent(ActivityMain.this,
RadioService.class);
stopService(intent);
selectItem(getPositionfromString(query));
setTitle(query);
} else {
Toast.makeText(getApplicationContext(), "No channel found",
Toast.LENGTH_LONG).show();
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
String[] columnNames = {
"_id", "text"
};
cursor = new MatrixCursor(columnNames);
String[] temp = new String[2];
// int id = 0;
for (int i = 0; i < GlobalData.getInstance().getArrChannels()
.size(); i++) {
if (GlobalData.getInstance().getArrChannels().get(i)
.getChannelName().toLowerCase()
.contains(newText.toLowerCase())) {
temp[0] = Integer.toString(i);
temp[1] = GlobalData.getInstance().getArrChannels()
.get(i).getChannelName();
cursor.addRow(temp);
}
}
String[] from = {
"text"
};
int[] to = {
R.id.text
};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(
ActivityMain.this, R.layout.search_item, cursor, from,
to, SimpleCursorAdapter.NO_SELECTION);
searchView.setSuggestionsAdapter(cursorAdapter);
return true;
}
});
searchView.setOnSuggestionListener(new OnSuggestionListener() {
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
cursor.moveToPosition(position);
searchView.setQuery(cursor.getString(1), true);
return false;
}
});
return true;
}
private int getPositionfromString(String chn) {
for (int i = 0; i < GlobalData.getInstance().getArrChannels().size(); i++) {
if (chn.contentEquals(GlobalData.getInstance().getArrChannels()
.get(i).getChannelName())) {
return i;
}
}
return -1;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (toggle.onOptionsItemSelected(item)) return true;
if (item.getItemId() == R.id.search) return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.search).setVisible(!dLayout.isDrawerOpen(rlDrawerOpen));
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView <? > parent, View view, int position,
long id) {
Intent intent = new Intent(ActivityMain.this, RadioService.class);
stopService(intent);
selectItem(position);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onWelComeButtonClick() {
dLayout.openDrawer(rlDrawerOpen);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvFacbook:
Intent i = new Intent(ActivityMain.this, ShowFacebook.class);
startActivity(i);
break;
case R.id.tvRateUs:
String linkurl = "http://play.google.com/store/apps/details?id=com.global.danceradio";
if (linkurl != null) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_TEXT, linkurl);
shareIntent.setType("text/plain");
startActivity(shareIntent);
} else {
Toast.makeText(getApplicationContext(), "Sharing failed...",
Toast.LENGTH_LONG).show();
}
break;
}
}
}
Here, everything looks normal. But there is no the rest of the code. Maybe you create an activity every second.
I would recommend you to write in support of the admob and clarify the issues. Maybe you're lucky and they will unblock you.
https://support.google.com/admob/answer/6201362?hl=en
Check admob support. they updated new photos for better explanation.