Adapter doesn't response after popping an AleartDialog from another fragment - android

Hello guys I am for first time here so if there are some mistakes with my problem just notify me to correct my self. My problem is in the adapter I think. My application is with 3 fragment tabs. In each tab I have a ListView with some items. Also I have button in each tab that updates,deletes or adds items. I make that by popping up an AleartDialog for adding a new item or clicking on the item from the list to update it or delete it. So after I login in my application I can do what ever I want with that list. Its not a problem. I can rotate the screen and my list still updates. Changing the tabs its not a problem also. The problem comes when I go to other fragment I click on the button for adding or on some of the items for updating and the AleartDialog pops up. After that when I close it I return to the first tab. Trying to add an item doesn't update the list and I see the same items. Deleting the item from the list then throws exception IndexOutOfBounds because the item its not in the list. I think I use arrayAdapter.notifyDataSetChanged() properly. Here I will share some other code.
Like that I update my list. In the jsonObject is list the with the items.
private void fillList(Gson gson, String jsonObject) {
listWithNames.clear();
Type collectionType = new TypeToken<ArrayList<PersonalSaveDTO>>() {
}.getType();
personalSaveList = gson.fromJson(jsonObject, collectionType);
Log.wtf(TAG, "OT REQUEST: " + personalSaveList);
for (int i = 0; i < personalSaveList.size(); i++) {
listWithNames.add(personalSaveList.get(i).getName());
}
Log.wtf(TAG, "fillList: " + listWithNames);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
arrayAdapter.notifyDataSetChanged();
buttonEnable(true);
}
});
}
Like that I starts the fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View viewFragment = inflater.inflate(R.layout.user_fragment, container, false);
listViewUser = (ListView) viewFragment.findViewById(R.id.listViewForUser);
addItem = (Button) viewFragment.findViewById(R.id.buttonAddUserElements);
updateList = (Button) viewFragment.findViewById(R.id.refreshListUser);
updateList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
makeRequestForList(viewFragment);
}
});
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addElement(viewFragment);
}
});
configureArrayAdapter(viewFragment);
setListenerForUserList(viewFragment);
if (savedInstanceState != null) {
isRequestMade = savedInstanceState.getBoolean("isRequestMade");
listWithNames = savedInstanceState.getStringArrayList("listWithNames");
personalSaveList = savedInstanceState.getParcelableArrayList("personalSaveList");
arrayAdapter.addAll(listWithNames);
arrayAdapter.notifyDataSetChanged();
}
if (!isRequestMade) {
makeRequestForList(viewFragment);
isRequestMade = true;
}
return viewFragment;
}
And here is how I create the adapter.
private void configureArrayAdapter(View view) {
listWithNames = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(view.getContext(),
R.layout.list_personal_group_fragment, R.id.adapterFragmentPersonalGroups, listWithNames);
arrayAdapter.clear();
listViewUser.setAdapter(arrayAdapter);
}

Related

ArrayList strange behaviour after update its values

I have a tabhost with several tabs and each tab contain a certain number of operations which are listed in a listview. To populate that listview I use an ArrayList.
First time tabs are created evertything works fine. The issue comes when I try to filter the list by year. The process of filtering works fine as I can see the filtered list in debug and it's fine.
The issue is that after filtering, i recreate the tabs in order to fill all listviews again. To open tabs I use this code. It creates as many tabs as different currencies there are in the list:
public static void openFragments(FragmentTabHost tabHost, ArrayList<Posicion> positions, Class FragmentResumen, Class FragmentDetails ) {
//==========================================================================================
// This method open as many tabs as different currencies there are in positions list
//==========================================================================================
ArrayList<String> currencies = Currency.getDifferentCurrencies(positions);
tabHost.clearAllTabs();
for (int i = 0; i < currencies.size() + 1; i++) {
String tabName = "", tabSpec = "";
Class fragmentToOpen;
Bundle arg1 = new Bundle();
//A general tab is first created
if (i == 0)
{
tabName = "All";
tabSpec = "General";
arg1.putString("moneda", tabName);
arg1.putSerializable("posiciones", positions);
fragmentToOpen = FragmentResumen;
}
//The rest of tabs for currencies are created
else
{
tabName = currencies.get(i - 1);
tabSpec = "Tab" + (i - 1);
arg1.putString("moneda", tabName);
arg1.putSerializable("posiciones", positions);
fragmentToOpen = FragmentDetails;
}
tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(tabName), fragmentToOpen, arg1);
}
}
As I told before, this works fine always.
First time I need to create tabs I call it by using:
openFragments(tabHost, positions, FragmentResumenMedio.class, FragmentDetailsMedio.class);
Then I have a button that shows a DatePicker and when user selects a year I close the dialog and redraw tabs as follows:
ArrayList<Posicion> positionsFiltered = General.makeHardCopyOfArrayListPosition(positions);
for(Posicion posicion : positionsFiltered)
{
Boolean matchFilters = filterPositionsByYear(posicion, year + "");
if(matchFilters == false){
positions.remove(posicion);
}
}
General.openFragments(tabHost, positions, FragmentResumenMedio.class, FragmentDetailsMedio.class);
When I debug this last function I can see that positions have the correct value after filtering but when I click the new tab, it shows the list without filtering and I don't know how could I solve this issue.
Thanks a lot.
EDIT
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Initialize view and tabhost
View rootView = inflater.inflate(R.layout.fragment_medio, container, false);
tabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
tabHost.setup(getActivity(), getChildFragmentManager(), android.R.id.tabcontent);
return tabHost;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//onCreatedView is only called the first time so we must ensure that tabhost is not null before adding tabs
if(tabHost == null) {
tabHost = (FragmentTabHost) getView().findViewById(android.R.id.tabhost);
tabHost.setup(getActivity(), getChildFragmentManager(), android.R.id.tabcontent);
}
FloatingActionButton floatingActionButton = (FloatingActionButton) getView().findViewById(R.id.floatingButton);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
positions = new ArrayList<>(positionsFiltered);
createDialogWithoutDateField().show();
}
});
//Check if any update has been made since the last open
SharedPreferences prefs = getActivity().getPreferences(MODE_PRIVATE);
Boolean updateMedioRequired = prefs.getBoolean(updateOperationsMedioPlazo, true);
if (updateMedioRequired != null)
{
if (updateMedioRequired == true)
{
//Update variable that indicates if changes have been made or not
SharedPreferences.Editor editor = getActivity().getPreferences(MODE_PRIVATE).edit();
editor.putBoolean(updateOperationsMedioPlazo, false);
editor.apply();
//Check if there are previously stored operations
if (operations.size() > 0)
{
//Show a progressDialog as prices have to be downloaded from internet and this can be a time consumming task
progress = ProgressDialog.show(getActivity(), "Obteniendo precios",
"Un momento por favor...", true);
//Generate positions from operations list and wait for result in "onStockPriceResult". If there are no changes, positions variable has already values
if(positions.size() == 0) {
new Thread(new Runnable() {
#Override
public void run() {
positions = MedioPlazoCalculations.generatePositions(listener, getActivity(), operations);
}
}).start();
}
}
else
{
Toast.makeText(getActivity(), "Aún no se ha introducido ninguna operación", Toast.LENGTH_LONG).show();
}
}
else
{
//If no update needed, variable coming from MainActivity has positionList. Open as many new fragments as currencies there are in positionsList
General.openFragments(tabHost, positions, FragmentResumenMedio.class, FragmentDetailsMedio.class);
}
}
}
EDIT 2:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
{
if(getActivity()!=null)
{
Bundle bundle = this.getArguments();
positions = (ArrayList<Posicion>) bundle.getSerializable("posiciones");
moneda = (String) bundle.getString("moneda");
}
}
}
Edit 3: If I place the commented instruction, filtering does not work. If I remove it, filtering works but I cant filter again because the value of the list has the filtered version not the original one
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
positions = new ArrayList<>(positionsFiltered);
createDialogWithoutDateField().show();
}
});

What is the difference between listViewAdapter.clear() and list.clear()?

Okay, I think I have understood it, but I just want to make sure of it. I have got a ListViewAdapter that contains a List.What I wanna do is search thinks in the database and show in a ListView. This piece of code adds an item to my listView.
list.addAll(sqh.DisplayRecords(sqdb));
listViewAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
listview.setAdapter(listViewAdapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listViewAdapter.clear();
list.clear();
list.addAll(sqh.DisplayRecords(sqdb));
list.add("another one");
}
});
Whit this other piece of code, only clearing the listviewAdapter and adding another item to the list, just, adds the last item, instead of all the items of the list, which should be there.
list.addAll(sqh.DisplayRecords(sqdb));
listViewAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1,list);
listview.setAdapter(listViewAdapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listViewAdapter.clear();
list.add("another one");
}
});
Well, I think I understood it while I was writing this. The third one and the first one are pretty the same.
list.addAll(sqh.DisplayRecords(sqdb));
listViewAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1,list);
listview.setAdapter(listViewAdapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listViewAdapter.clear();
list.addAll(sqh.DisplayRecords(sqdb));
list.add("another one");
}
});
The listViewAdapter.clear(); would be clearing the list of the adapter, right? Why, when I do just list.clear(), the list view is not cleared?
When you calling list.clear();, you'are removing all of the elements from the list. The list will be empty after this call returns. But your Adapter view isn't change yet. You need to call adapter.notifyDataSetChanged() to refresh the adapter.
In the other case, when you calling listViewAdapter.clear();, the list will be cleared first then the notifyDataSetChanged() called.
You can see the details in ArrayAdapter.clear() source code:
/**
* Remove all elements from the list.
*/
public void clear() {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.clear();
} else {
mObjects.clear();
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}
listViewAdapter.clear()
void clear ()
Remove all elements from the list.
And list.clear();
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
If you use in this , it was the same .It used to Removes all of the elements from this list .

RecyclerView not refreshing after rotating the device with an open DialogFragment

I have a RecyclerView inside a AppCompatActivity. Item insertions and changes are shown and animated correctly after rotating the device.
The problem happens when you:
Tap on an item in the RecyclerView.
A DialogFragment opens prompting if you want to the delete the item.
Rotate the device.
Confirm the deletion in the dialog.
Check the array list. The item has been deleted.
The RecyclerView still shows the item.
Tried using notifyDataSetChanged instead of notifyItemRemoved but didn't work either because the item is still being shown in the RecyclerView.
This is happening with any version of Android.
Simplified code of how the process is being handled:
public class MyAppCompatActivity extends AppCompatActivity {
int positionOfDeletedItem;
MyObjectRecyclerViewAdapter adapter;
ArrayList<MyObject> someTestData;
MyItemDeletionHandler deletionHandlerRemover;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity_layout);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
positionOfDeletedItem = 1;
deletionHandlerRemover = new MyItemDeletionHandler(this);
someTestData = new ArrayList<MyObject>(3);
someTestData.add(new MyObject("A"));
someTestData.add(new MyObject("B"));
someTestData.add(new MyObject("C"));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyObjectRecyclerViewAdapter(new MyAdapterOnClickEvent.OnItemClick() {
#Override
public void onClick(int posicion, int idViaje, View view) {
String tag = "Some tag value";
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(tag);
if(prev != null)
ft.remove(prev);
ft.addToBackStack(null);
DialogFragment newFragment = MyDeletionConfirmationDialog.newInstance(deletionHandlerRemover);
newFragment.show(ft, tag);
}
}, someTestData);
recyclerView.setAdapter(adapter);
}
private final static class MyItemDeletionHandler extends Handler {
private final WeakReference<MyAppCompatActivity> theActivity;
private MyItemDeletionHandler(MyAppCompatActivity act) {
theActivity = new WeakReference<MyAppCompatActivity>(act);
}
#Override
public void handleMessage(Message msg) {
MyAppCompatActivity activity = theActivity.get();
if(activity != null) {
if(msg.what == 1) {
activity.deleteTheItem();
}
}
}
}
public void deleteTheItem() {
someTestData.remove(positionOfDeletedItem);
adapter.notifyItemRemoved(positionOfDeletedItem);
}
}
public class MyDeletionConfirmationDialog extends DialogFragment {
private Message handlerMessage;
public static MyDeletionConfirmationDialog newInstance(Handler callbackHandler) {
MyDeletionConfirmationDialog myDialog = new MyDeletionConfirmationDialog();
Bundle args = new Bundle();
args.putParcelable("handlerMessage", callbackHandler.obtainMessage(1, true));
myDialog.setArguments(args);
return myDialog;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handlerMessage = getArguments().getParcelable("handlerMessage");
}
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("Some message");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final Message toSend = Message.obtain(handlerMessage);
toSend.sendToTarget();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = alertDialogBuilder.create();
dialog.setCanceledOnTouchOutside(true);
return dialog;
}
}
How can I get the RecyclerView to work correctly?
Edit 1:
I have other RecyclerViews in which this works correctly. The only difference is those are inside Fragments instead of AppCompatActivity. I am suspecting that this has something to do with the events onDetachedFromWindow and onAttachedToWindow of the RecyclerView.
Edit 2:
If the dialog is closed (step 4) and opened again it works as expected.
Edit 3:
If the RecyclerView is extracted as a Fragment the problem disappears and works as intended. It is impossible to have the use case described above working correctly in conjunction with AppCompatActivity instead of a Fragment.
I was facing a similar problem with RecyclerView.
When I swiped left to delete an item and then rotate the screen, the item was removed from my dataset but the screen wasn't refreshing like it normaly does when we do the same action without rotating. It seems the adaptar.notifyItemRemoved() wasn't refreshing the screen at all.
I'm using the Nemanja Kovacevic source code as starting point, but I did some changes on it (like adding item click, edit with a dialog, database support, etc).
So I read this post which gave me a hint about what could be going wrong.
It seems the adapter.notify was still pointing to the previous adapter referece before rotation. Every time we rotate a new adapter is created at the Activity:OnCreate
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
AddAlertDialog.OnAlertSavedListener,
AlertListAdapter.OnItemDeletedListener {
static ListAdapter mListAdapter;
RecyclerView mRecyclerView;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mRecyclerView = (RecyclerView) findViewById(R.id.mainListView);
mDB = new DatabaseTable(this);
// Reading all alerts
ArrayList<Alert> alerts = mDB.getAllAlerts();
if (mListAdapter == null)
mListAdapter = new ListAdapter(this, alerts);
}
}
Maybe it is not ideal (creating static objects is not a good idea), but it solved the problem.
I hope it may help you too.

How to access values defined in AsyncTask from an activity

I have code like this
#Override
public void onCreate(Bundle savedInstanceState) {
addItemsOnSpinnerOrgaLevel();
btn_getReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//How can i access map and list defined in orgaLevelTask(AsyncTask)???
Like
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
// Both are defined in AsyncTask ??
}); //end of anonymous class
} //end of onCreate()
public void addItemsOnSpinnerOrgaLevel() {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of addItemsOnSpinnerOrgaLevel()
In AsyncTask onPostExecute() Method i have
#Override
protected void onPostExecute(ArrayList<OrgaLevel> result) {
super.onPostExecute(result);
if (result != null) {
addItemsOnSpinnerOrgaLevel(result);
}
dialog.dismiss();
} //end of onPostExecute()
public void addItemsOnSpinnerOrgaLevel(ArrayList<OrgaLevel> result) {
orgaLevelElementslist = new ArrayList<String>();
orgaLevelElementslist.add("All");
orgaLevelMap = new HashMap<String, Integer>();
orgaLevelMap.put("All", 0);
for (int i=0; i<result.size(); i++) {
OrgaLevel orgaLevelRecord = (OrgaLevel) result.get(i);
String key = orgaLevelRecord.getOrgaName();
String value = orgaLevelRecord.getOrgaCode();
orgaLevelMap.put(key, Integer.parseInt(value));
orgaLevelElementslist.add(key);
} //end of for()
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(accountReportActivity, android.R.layout.simple_spinner_item, orgaLevelElementslist);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_orgaLevel.setAdapter(dataAdapter);
setSpinnerOrgaLevelListener();
} //end of addItemsOnSpinnerOrgaLevel()
private void setSpinnerOrgaLevelListener() {
spinner_orgaLevel.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
subOrgaLevelTask = new SubOrgaLevelTask(accountReportActivity, spinner_branch, orgaCode);
subOrgaLevelTask.execute();
} //end of onItemSelected()
}); //end of anonymous class
} //end of setSpinnerOrgaLevelListener()
In the subOrgaLevelTask i also have the same hash map as in this class. You can see that what i am trying to do is, put a key value in spinner. So when my btn_getReport button get click then i get the value of the selected item. Like if All is slected then i get 0 and so on. This key value thing is working. The problem is when btn_getReport get click then how can i get the value of the selected item. Because i am filling items in a background thread(In OrgaLevelTask and SubOrgaLevelTask) and my button is in Activity. So how can i do that when button get click, then i get the values from the map defined in OrgaLevelTask and SubOrgaLevelTask ?
Thanks
well, make them public in orgaLevelTask, and simply access them. orgaLevelTask should be a variable in you activity class. Have you tried it? any errors?
You must make sure orgaLevelTask members will be accessed in thread safe manner

putExtra from List into SMS body

I'm trying to put the contents of List mCartList; into a the sms_body below, eg: Cheeseburger, Hamburger, Fries (so it can be sent through sms). I can pass a string so I know it works. I'm not a programmer at all and it's been a month of me doing trial & error.
Below the activity calls the contents of mCartList into a List so they can be removed. Tell me whatever else you need to help me solve this. Thank you in advance.
private ProductAdapter mProductAdapter;
// This List into the order button below
private List<Product> mCartList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCart();
// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product selectedProduct = mCartList.get(position);
if(selectedProduct.selected == true)
selectedProduct.selected = false;
else
selectedProduct.selected = true;
mProductAdapter.notifyDataSetInvalidated();
}
});
Button orderButton = (Button) findViewById(R.id.orderButton);
orderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("smsto:1234567890");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
// The above List<Product> mCartList ia displayed in the window of the app
intent.putExtra("sms_body", "mCartList"); // I want the results of List<Product> mCartList to go here - I can not just insert the variable I just get errors and can't compile
startActivity(intent);
}
});
Button removeButton = (Button) findViewById(R.id.ButtonRemoveFromCart);
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Loop through and remove all the products that are selected
// Loop backwards so that the remove works correctly
for(int i=mCartList.size()-1; i>=0; i--) {
if(mCartList.get(i).selected) {
mCartList.remove(i);
}
}
mProductAdapter.notifyDataSetChanged();
}
});
}
Here is how this works. It's a 4 tab list with different items in each tab, 3 of which or products. Customer clicks on the item and they see a description, click add to cart, then your back at the menu. The 4th tab is a the order of what was just selected that is to populate the sms body. I have been able to pass a variable with the text "Hello World". I'm figuring the result of List mCartList can populate the sms body. I'm assuming the List can not just be inserted into the body of a forn without being converter. Let me know if you need anymore info. I'm not a programmer, I have seen similar but nothing that doesn't work without writing other files I got from a tutorial. Thank you in advance.
If all the products are added to your mCartList, it's just a matter of concatenating the String output of the Products together as follows:
orderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("smsto:1234567890");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
StringBuilder builder = new StringBuilder();
for(Product p : mCartList){
builder.append(p.toString());
builder.append('\n');
}
intent.putExtra("sms_body", builder.toString());
startActivity(intent);
}
});
make sure your Product has a toString() method defined as follows (example Product guess):
public class Product{
String productName;
public String toString(){
return productName;
}
}

Categories

Resources