Please have a look at the below code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class InputFragment extends Fragment {
private SeekBar daysAsCustomerSeek;
private View view;
//Following variables will save the application state and load back
//on resume
private final String DAYS_AS_CUSTOMER_VALUE_HOLDER = "days as customer value";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Intializing instance variables
view = inflater.inflate(R.layout.input, container,false);
daysAsCustomerSeek = (SeekBar)view.findViewById(R.id.days_as_customer_seekbar);
//Set default max values
daysAsCustomerSeek.setMax(210);
return view;
}
//This method will save the instances
#Override
public void onSaveInstanceState(Bundle savedInstanceStateBundle)
{
savedInstanceStateBundle.putInt(DAYS_AS_CUSTOMER_VALUE_HOLDER, daysAsCustomerSeek.getProgress());
}
//This method will restore the instances
#Override
public void onActivityCreated(Bundle savedInstanceStateBundle)
{
super.onActivityCreated(savedInstanceStateBundle);
if(savedInstanceStateBundle!=null)
{
daysAsCustomerSeek.setProgress(savedInstanceStateBundle.getInt(DAYS_AS_CUSTOMER_VALUE_HOLDER));
}
}
}
The problem is when I turn the device or navigate back to this fragment, non of its states were saved! Instead, everything was recreated! Why is this? Why this code is not showing the state?
Add:
super.onSaveInstanceState(savedInstanceStateBundle);
in onSaveInstanceState method.
someFragment.setRetainInstance(true);
Related
I have an android app where I display a form with some Checkboxes.I want to query firestore on the basis of checked checkboxes. I'm unable to get the array/arraylist of checked checkboxes. For testing purposes I've added a textview . If my test works I want to set the text of textview using members of newly populated array/arraylist.
When I check any checkbox and click on the button,my app crashes. Suppose I checked box4. The condition
(item4.isChecked) should be true and hence item4 must be added to my arraylist whose size is now not equal to zero
if(item4.isChecked()){
testingArrayList.add("item4");
}
Why am I getting the error that length of array is zero?
Here is my code:
package com.example.XX;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldPath;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class todayQuestionFragment extends Fragment {
FirebaseFirestore db = FirebaseFirestore.getInstance();
CheckBox item1;
CheckBox item2;
CheckBox item3;
CheckBox item4;
CheckBox item5;
CheckBox item6;
CheckBox item7;
CheckBox item8;
CheckBox item9;
CheckBox item10;
Button button;
ProgressBar progressBar;
TextView textView;//just for testing
public todayQuestionFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_today_question, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
item1=view.findViewById(R.id.checkBox_item1);
item2=view.findViewById(R.id.checkBox_item2);
item3=view.findViewById(R.id.checkBox_item3);
item4=view.findViewById(R.id.checkBox_item4);
item5=view.findViewById(R.id.checkBox_item5);
item6=view.findViewById(R.id.checkBox_item6);
item7=view.findViewById(R.id.checkBox_item7);
item8=view.findViewById(R.id.checkBox_item8);
item9=view.findViewById(R.id.checkBox_item9);
item10=view.findViewById(R.id.checkBox_item10);
textView=view.findViewById(R.id.testingCheckBox);
Button button=view.findViewById(R.id.toMainQueryButton);
final NavController navController= Navigation.findNavController(view);
final ArrayList<String> testingArrayList = new ArrayList<String>();
if(item1.isChecked()){
testingArrayList.add("item1");
}
if(item2.isChecked()){
testingArrayList.add("item2");
}if(item3.isChecked()){
testingArrayList.add("item3");
}if(item4.isChecked()){
testingArrayList.add("item4");
}
if(item5.isChecked()){
testingArrayList.add("item5");
}
if(item6.isChecked()){
testingArrayList.add("item6");
}
if(item7.isChecked()){
testingArrayList.add("item7");
}if(item8.isChecked()){
testingArrayList.add("item8");
}if(item9.isChecked()){
testingArrayList.add("item9");
}
if(item10.isChecked()){
testingArrayList.add("item10");
}
final String[] testArray = new String[testingArrayList.size()];
for(int j =0;j<testingArrayList.size();j++){
testArray[j] = testingArrayList.get(j);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(testArray[0]);
}
});
}
}
Logcat:
2020-06-12 14:48:10.772 4622-4622/com.example.XX E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.XX, PID: 4622
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.XX.todayQuestionFragment$1.onClick(todayQuestionFragment.java:140)
at android.view.View.performClick(View.java:7201)
at android.view.View.performClickInternal(View.java:7170)
at android.view.View.access$3500(View.java:806)
at android.view.View$PerformClick.run(View.java:27582)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7710)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Found my error. All my logic with if conditions and arraylist/array needs to be added INSIDE the onClickListener of my button
I am trying to create edittext using Java in bottom fragment class based on input that is to be passed from top fragment. But when I type
Button add_submit = new Button(this);
I get error for the this for parameter. However I can use this code in MainActivity.java.
Why is this so? What is causing the error and how to fix it?
The following are the complete code for the class
package com.test.gpacalc;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class AddActivityBottom extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_add_bottom,container,false);
return view;
}
public void createAddInput(String number_of_subjects){
Button add_submit = new Button(this);
}
}
Button constructor requires context as an argument. Fragment doesn't implement it, activity does. try new Button(getActivity())
I'm a total noob at android studio, and I have a (to me) weird problem. I have inserted a button in my XML document:
<Button
android:layout_width="match_parent"
android:layout_height="127dp"
android:text="SUM"
android:id="#+id/button"
android:layout_row="15"
android:layout_column="0" />
And in the java code I would like a to make it do something when i click on it. However in code (I know there is way too many import):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
R.id.button.onCliclistener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent action) {
DO THIS WHEN CLICKED ON
}
});
}
BUT it says: Cannot resolve method() and Cannot resolve symbol, to the onCliclistener and ActionListener. And it says: unused import statement, to thier imports. It's probably a stupid question, but what am I doing wrong?
Nicolaj
Try making reference to your button in your onCreate method and then create an onClick method.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TestActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btn = (Button) findViewById(R.id.button); //Reference to the button
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
DO THIS WHEN CLICKED ON
}
}
I expect it will be helpful for you!
i want to toggle the background music on and off using settings , which is an activity and it can be launched by pressing the menu button through the main activity and selecting settings. the problem I am facing now is that when i tick the background music checkbox , upon clicking save and returning to the main activity , my music stops playing. how to i make sure that the music keeps playing after going back to the main activity? And when i stop the app and relaunch the activity , i want the settings to remain the way they were selected (using sharedpreferences). Can anyone take a look at my codes and see what I am doing wrong?
my MainActivity.java
package sp.com;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import android.app.TabActivity;
import android.widget.TabHost;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.media.MediaPlayer;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
public class MainActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.setting:
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
}
My settings.java
package sp.com;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.View.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
public class Settings extends Activity implements OnClickListener {
CheckBox Backmusic;
Button button1;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.xml.preferences);
Backmusic = (CheckBox) findViewById(R.id.backmusic);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
loadSavedPreferences();
}
private void loadSavedPreferences(){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value",false);
if (checkBoxValue){
Backmusic.setChecked(true);
} else {
Backmusic.setChecked(false);
}
}
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
#Override
public void onClick(View v){
savePreferences("CheckBox_Value",Backmusic.isChecked());
if (Backmusic.isChecked()){
mp = MediaPlayer.create(getBaseContext(), R.raw.sound);
mp.start();
} else {
mp.stop();
finish();
}
}
#Override
protected void onStop() {
super.onStop();
mp.stop();
finish();
}
}
Thanks in advance.
So right now you are just playing the music within your Settings activity. In fact you are calling mp.stop() in onStop(). That's why when it closes the music stops.
You should also put code in your MainActivity in onCreate() and onResume() to read from sharedpreferences and if the background music is true, play music. That could look something like this:
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
boolean backgroundMusic = sp.getBoolean("CheckBox_Value",false);
if (backgroundMusic)
{
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.sound);
mp.start();
}
else
{
mp.stop();
}
Note that you'll now want to write to SharedPreferences in Settings using getApplicationContext() instead of this. That way the preferences will be saved across the entire application and not just one activity.
I tried to have a view of an ActionBarActivity opening after hitting a spinner button.
There are two items on my spinner, the second one runs fine, but when I tried to access the Categorias item the app throws me a NullPointerException inside the DrawerActivity class. I don't actually know where the problem is. Another ActionBarActivity extension class that I have runs perfectly.
I'm new to Android/Java development.
The Spinner Fragment
import inmostla.ligatangamanga.pruebaintegrar.navigationdrawer.NavigationDrawerActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerFragment extends Fragment {
private static Spinner spinner;
private int selected;
private View mView;
static void setSpinnerContent( View view ){
spinner = (Spinner) view.findViewById(R.id.spinner1);
return ;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_spinner, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
/**
* Maneja las acciones seleccionadas del Spinner
*/
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
selected = spinner.getSelectedItemPosition();
switch(selected){
case 1:
Intent categorias = new Intent( );
categorias.setClass( getActivity() , NavigationDrawerActivity.class );
startActivity(categorias);
break;
case 2:
Intent convenios = new Intent();
convenios.setClass(getActivity(), ConveniosFragment.class);
startActivity(convenios);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
return view;
}
}
The Navigation Drawer Activity extends a ActionBarActivity
package inmostla.ligatangamanga.pruebaintegrar.navigationdrawer;
import inmostla.ligatangamanga.pruebaintegrar.navigationdrawer.NavigationDrawerFragment;
import inmostla.ligatangamanga.pruebaintegrar.R;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class NavigationDrawerActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}...
Maybe that's because getActivity() returns null. Try overriding onAttach() and keep Activity reference as a field in your class. Use this reference instead of getActivity() when you needed a reference to context or activity.