How to save listview item checked - java

I'm using a listview to display grocery items with checkmark using android.R.layout.simple_list_item_checked. The problem is when i check an item and go to the previous page and comeback to the list my item is not checked anymore..i would like to use something else than sharedpreference is that possible and how can i do that?
I try to use SparseBooleanArray but it didnt work i probably use it wrong.
Since i use the previous phone button and after i click on the button that call my list activity i should use something in my onCreate method but i'm not sure what and how?
I also try to use oninstanceResore method like some people suggest me but i dont thin it what i'm looking for let say im on the activity 2 which is my item list with some item checked i decide to go back do something else using the phone previous button and then come back to the activity 2 using the button in my apps ...i want my item to still be checked. Can someone help me on how to do this i will be very grateful…
public class FruitList_Activity extends AppCompatActivity {
private ListView fruitsList;
private ArrayAdapter<String> adapterFruit;
private Button btn_Delete;
private Button btn_SelectAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_fruit_list_);
fruitsList = findViewById(R.id.list_Fruits);
fruitsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btn_Delete = findViewById (R.id.btn_delete);
CreateActivity.itemsFruit = FileHelper.readData(this);
adapterFruit = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, CreateActivity.itemsFruit);
fruitsList.setAdapter(adapterFruit);
/*Remove items*/
btn_Delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SparseBooleanArray checkedItemPositions = fruitsList.getCheckedItemPositions();
int itemCount = fruitsList.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
fruitsList.setItemChecked(i,true);
adapterFruit.remove(CreateActivity.itemsFruit.get(i));
FileHelper.writeData(CreateActivity.itemsFruit, FruitList_Activity.this );
}
}
adapterFruit.notifyDataSetChanged();
}
});
}
}
Can you guide me on how i can do that i'm just starting with java so please explain me so i can understand. thanks!

You need to create a Bundle with the information of the list, and before calling the second activity, you'll set the data inside that bundle, and when you came back to the main activity just check the bundle and if is different at null is because you need to load the data.
I Hope this cal help you :D
this is saved Instance()
also, this cal help you when you have onConfigurationChanged()

Save your adapterFruit using onSaveInstanceState
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("adapter",(Serializable) adapterFruit);
}
The onRestoreInstance executes when you go back to the activity
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(saveInstanceState != null){
adapterFruit = (ArrayAdapter<Adapter> )savedInstanceState.getSerializable("adapter");
}
}
Hope it helps.

you can do like this
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.checkBox.isChecked()==true) {
holder.checkBox.setChecked(true);
model_image.get(position).setSelected(true);
}
else
{
holder.checkBox.setChecked(false);
model_image.get(position).setSelected(false);
}
}
});

Related

Calling the Refresh() method which is in the main activity from another activity [duplicate]

This question already has answers here:
How to refresh listview in fragment when onbackpressed()
(4 answers)
Closed 1 year ago.
I'm developing an android app using java, but I have the problem below.
I have the main activity where there is a button "add" and a listview. When I click the add button, it will open another activity where I can add items to the listview. After adding this item, when I click the back button from the second activity, I want that the Refresh() method from the main activity to be executed to add this item directly to the listview in the main activity. I can't find a way to solve it. I tried to make this method as static but lot of errors appear, and the all the app is stopped. Also I tried to create new instance of the main activity in the onBackPressed() method of the second activity, but the app has also stopped. Anyone can help me to solve this problem?
Thank you.
Read this: https://developer.android.com/training/basics/intents/result then add a call to your refresh method in your MainActivity after you get a result back indicating that the second activity is done.
I believe that the following working example shows how you can accomplish what you want :-
MainActivity (the initial activity) :-
public class MainActivity extends AppCompatActivity {
public static final int ACTIVITY1_REQUEST_CODE = 999;
public static final String EXTRA_MYARRAY = "extra_myarray";
private Button next;
private ListView listView;
ArrayAdapter<String> adapter;
ArrayList<String> myarray = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = this.findViewById(R.id.next);
listView = this.findViewById(R.id.listview);
// Prepare the Button's onClickListener to start the other activity
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(),Activity2.class);
// prepare to pass the data to the other activity
i.putExtra(EXTRA_MYARRAY,myarray);
// Start the other activity
startActivityForResult(i,ACTIVITY1_REQUEST_CODE);
}
});
// Prepare the data
myarray.add("a");
myarray.add("b");
myarray.add("c");
// Output data to the log (to show what happens)
refresh(myarray,"INITIAL", false);
}
// Prepare to receive and handle the modified data when returning from other activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTIVITY1_REQUEST_CODE && resultCode == RESULT_OK) {
myarray.clear();
for(String s: data.getStringArrayListExtra(EXTRA_MYARRAY)) {
myarray.add(s);
}
refresh(data.getStringArrayListExtra(EXTRA_MYARRAY),"RESUMED",true);
}
}
/**
* Refresh
* #param modifiedData The modified data to be applied (see modify) as an ArrayList<String>
* #param tagExtra String used to indicate where the refresh was called from
* #param modify flag to indicate whether or not to rebuild the data
* if coming from the this activity then clear and add would
* empty the array and add nothing
*/
private void refresh(ArrayList<String> modifiedData, String tagExtra, boolean modify) {
if (modify) myarray.clear();
for(String s: modifiedData) {
if (modify) myarray.add(s);
Log.d("MA_" + tagExtra,"Value is " + s);
}
refreshListView();
}
private void refreshListView() {
if (adapter == null) {
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,myarray);
listView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
Activity2 the invoked/2nd activity (which modifies the list and returns that modified list to the parent when the button is clicked) :-
public class Activity2 extends AppCompatActivity {
private Button finish;
private ArrayList<String> myarray = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
finish = this.findViewById(R.id.finish);
// Prepare the Button's onCLickListener
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
// Prepare to return the data
i.putExtra(MainActivity.EXTRA_MYARRAY,myarray);
// Indicate that all is OK
setResult(RESULT_OK,i);
// Finish this activity and thus pass control back to the parent activity
finish();
}
});
// Modify the data
myarray = this.getIntent().getStringArrayListExtra(MainActivity.EXTRA_MYARRAY);
myarray.add("d");
}
}
Comments should explain the code
Note this method does use the deprecated (startActivityForResult) so you may wish to consider looking at Getting a result from an activity
Result
When run the App displays :-
Clicking the NEXT button takes you to the 2nd Activity :-
Clicking the FINISH button (the activity adds a new element) returns to the MainActivity which is now :-
i.e. the new element is displayed accordingly in the ListView

How to Visible/Invisible using OnClickListener?

I am working on FAQ page I don't want to use Expandable list view and stuff.
So I set 2 TextViews(1 for Question and 1 for Answer) and made one clickable.
The above image shows when the first textview mfaq is clicked it sets second one mAns to visible.
The below code works well to Set the mAns textview visible:
public class faq extends AppCompatActivity {
TextView mfaq,mAns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faq);
mfaq=findViewById(R.id.faq);
mAns=findViewById(R.id.ans);
mfaq.setOnClickListener(new View.OnClickListener() {
int counter=0; //setting counter to count onclick
#Override
public void onClick(View view) {
++counter; //incrementing counter first click
if(counter==1){
mAns.setVisibility(View.VISIBLE);
}
//this sets mAns visible , but when i click on it again i want it to hide the text view
counter=0; //resetting the counter
}
});
}
}
So I want to set the visibilty to gone when the textview is clicked again(Should function like Click-visible,ClickAgain-Invisible,Repeat).
Note-I am a beginner please try to explain me what the code is doing so I learn more :)
Thanks.
If I understand well you wanna hide/show your textview each time you click on the other text?
mfaq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mAns.getVisibility() == View.VISIBLE){
mAns.setVisibility(View.GONE);
}
else
mAns.setVisibility(View.VISIBLE);
}
});

SavedIntanceState.getBoolean() is making my app crash (i think)

My Goal:
So I need help putting a boolean primitives into a bundle and retrieving it from the bundle when there is a screen orientation change in Android. I am using that boolean value in a conditional statement that helps decide if 2 Button views (mTrueButton, mFalseButton) should be enabled or not. What i have so far is causing the app to shut down (aka crash) when there is a screen rotation. I think I am not retrieving or writing my boolean from my bundle or into my bundle correctly, and it is causing the app to crash.
How The App Should Works:
When a user touches the mTrueButton or mFalseButton button to answer a question, both buttons become disabled so the user is not allowed to answer again. I want those buttons to keep being disabled when the user answers and then rotates the screen.**
I know that when a user rotates their Android device, onDestroy() is called because runtime configuration changes take place, causing the app to be relaunched without having knowledge of it's previous state, (unless store my necessary data onto a bundle and pass it onto my onCreate method).
These are SOME global variables in my activity class
private int index = 0;
priavate Button mTrueButton,mFalseButton;
private static final String KEY_INDEX = "index";
private static final String BTTN_ENABLED = "bttnEnabled";
private boolean trueFalseButtonsEnabled = true;
These are SOME statements in my onCreate() method of the same activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if(savedInstanceState != null) {
index = savedInstanceState.getInt(KEY_INDEX, 0);
changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true));
}
mTrueButton = (Button)findViewById(R.id.true_button);
mFalseButton = (Button)findViewById(R.id.false_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
changeButtonEnableStatus(false);
}
});
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
changeButtonEnableStatus(false);
}
});
}
These are SOME methods in the same activity class but not in my onCreate()
private void changeButtonEnableStatus(boolean bool){
trueFalseButtonsEnabled = bool;
mTrueButton.setEnabled(bool);
mFalseButton.setEnabled(bool);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG,"onSavedInstanceState() called");
savedInstanceState.putInt(KEY_INDEX,index);
savedInstanceState.putBoolean(BTTN_ENABLED, trueFalseButtonsEnabled);
}
Note that:
index = savedInstanceState.getInt(KEY_INDEX, 0);
works properly. It is setting global variable "index" to equal to the int primitive what was stored in into keywork "KEY_INDEX".
However I don't think: changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true)); is working properly. My app seems to crash when I include that statement and run the app, and then rotate the device.

Attempt to write to null array android studio

I've created a simple 'app' to put values from text to an array and it doesn't seem to work.. I don't know why..
public class Register extends AppCompatActivity {
String[] data = new String[2];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
gotoReg();
}
public void gotoReg() {
Button register = (Button) findViewById(R.id.Submit);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
data[0] = "ss";
data[1] = "dd";
}
}
);
}
}
From this code I get the error :
java.lang.NullPointerException: Attempt to write to null array
I did almost the same code in another app and it worked.. seems really wierd to me...
Nevermind, thanks everyone, just re-opened Android studio and everything worked fine.
Wasted on it several hours ughh
Just put your code to get button reference after setContent view then,you can assign the values.
And you have checked the id of button?
Try to add
data = new String[2];
to your gotoReg() method, before setting the onClick listener.

Refresh adapter in a Fragment after DialogFragment dbflow insert

I have an activity that has 3 fragments on it with Tabs, one of them is called "TaskFragment".
In my main Activity i only load the fragments.
In TaskFragment i have a RecyclerView that is working fine and is showing the items as intended.
The problem comes, when i insert data using a DialogFragment, because it does insert data (i am using DbFlow ORM), but it does not (of course) refresh the adapter since it is in the TaskFragment fragment inside the DetailMainActivity activity as i said.
I have tried to use onResume() and onPause() in order to refresh the adapter, but they are never called since the activity does not get paused or in onresume for a DialogFragment.
I have tried aswell to use an interface, but it does not work and i have searched all over stackoverflow and google with no luck.
I leave here some of my code for you to understand better:
DetailMainActivity.java
Here in the onClick interface i show the DialogFragment to the user to input the information.
FragmentManager fm = getSupportFragmentManager();
AddSimpleTask sptask = new AddSimpleTask();
sptask.show(fm, "tag");
TaskFragment.java
In this fragment i have my RecyclerView
private void setupRecyclerView() {
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (DetailMainActivity.FAB_Status) {
DetailMainActivity.hideFAB();
DetailMainActivity.FAB_Status = false;
}
return false;
}
});
}
private void setupAdapter() {
adapter = new DetailMainTaskAdapter(simpleTaskList, this);
}
AddSimpleTask
And this is my DialogFragment. I have set a setOnShowListener() in order to avoid the DialogFragment to get dismiss early.
#Override
public void onShow(DialogInterface dialogInterface) {
final AlertDialog dialog =(AlertDialog) getDialog();
if (dialog != null){
Button positiveButton = dialog.getButton(Dialog.BUTTON_POSITIVE);
Button negativeButton = dialog.getButton(Dialog.BUTTON_NEGATIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEditTextName.getText().toString().trim().isEmpty() ||
mEditTextContent.getText().toString().trim().isEmpty() ) {
if (mEditTextName.getText().toString().trim().isEmpty()) {
mEditTextName.setError("Can not be empty");
}
if (mEditTextContent.getText().toString().trim().isEmpty()) {
mEditTextContent.setError("Can not be empty");
}
}else {
presenter.beingInsertion(mEditTextName.getText().toString().trim(), mEditTextContent.getText().toString().trim()
, foreignId);
}
}
});
negativeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
}
}
If the insert is successfully achieved the onInsertSuccess method is called (i am using MVP)
#Override
public void onInsertSuccess() {
Snackbar.make(getActivity().findViewById(R.id.containerMainDetail), "Actividad agregada", Snackbar.LENGTH_SHORT).show();
dismiss();
}
I have called adapter.notifyDataSetChanged() in many places, and i also tried with a custom interface, but i can not make this work.
Sorry for the long post, but thanks in advance for your help.
There are some errors in your statement but I'll get to that later. notifyDataSetChanged() only notifies the adapter that the underlying list (or array) has changed. The implication is that you first need to requery your database and obtain the new list before calling notifyDataSetChanged() on the adapter else there is no point as the underlying list will still be the same and it will not update the adapter.
The correct way of calling this will be through your custom listener interface and not in the onPause()/onResume() callbacks as there is the possibility that the user does not enter a value and hence you will unnecessarily be querying the database. In your custom listener interface implementation, first update the list with the new data from the DB and then notify the adapter.
Which leads to the error in assumption that onPause()/onResume() callbacks do not happen when your Activity is covered by a DialogFragment - this is incorrect. The moment the activity view is even partially covered, the onPause() callback is triggered.

Categories

Resources