I have four fragments in a tab layout. In one of the fragments, I am displaying 10 notes in a listview. In addition to that, I am giving the user the option to add new notes using a dialog box. So, on adding a new note, the listview gets refreshed to show the new note as well but when I switch to another tab and then get back to my original tab, the new note is not displayed in the listview. How to solve this problem?
This is my java code:
public class NoteFragment extends Fragment {
ListView lv_notes;
Button btn_newNote;
ArrayList<NotesModel> notesModelArrayList;
private static NotesAdapter notesAdapter;
NotesModel newNote;
public NoteFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_note, container, false);
lv_notes = (ListView)rootView.findViewById(R.id.lv_notes);
btn_newNote = (Button)rootView.findViewById(R.id.btn_newNote);
notesModelArrayList = new ArrayList<>();
for (int i = 1; i <= 10; i++){
notesModelArrayList.add(new NotesModel("Note " + i,"24/05/2017"));
}
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
btn_newNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater newNoteInflater = LayoutInflater.from(getContext());
View newNoteView = newNoteInflater.inflate(R.layout.noteprompt,null);
final AlertDialog.Builder noteDialogBuilder = new AlertDialog.Builder(getContext());
noteDialogBuilder.setView(newNoteView);
final EditText et_newNote = (EditText)newNoteView.findViewById(R.id.et_newNote);
noteDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
newNote = new NotesModel(et_newNote.getText().toString(),LogFragment.day_d + "/" + (LogFragment.month_d + 1) + "/" + LogFragment.year_d);
notesModelArrayList.add(newNote);
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog newNoteDialog = noteDialogBuilder.create();
newNoteDialog.show();
}
});
return rootView;
}
}
Your problem is caused by the fragment lifecycle. In case that it is destroyed, the new instance of the fragment will not keep the updated list, but the original one. To fix this, you have to save the array:
Save the data when fragment is about to be destroyed:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("notesList", notesModelArrayList);
}
And retrieve/create the data when fragment is created:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
notesModelArrayList = savedInstanceState.getParcelableArrayList("notesList");
} else {
for (int i = 1; i <= 10; i++){
notesModelArrayList.add(new NotesModel("Note " + i,"24/05/2017"));
}
}
}
Beside this, I have 2 things to mention: you should implement Parcelable in the NotesModel class to be able to save them and, this will only work if you don't close the app. If you want a persistent solution, please consider using SharedPreferences.
EDIT - forgot to mention that you should remove the following lines from onCreateView:
notesModelArrayList = new ArrayList<>();
for (int i = 1; i <= 10; i++){
notesModelArrayList.add(new NotesModel("Note " + i,"24/05/2017"));
}
Instead of these 2 lines
notesAdapter = new NotesAdapter(notesModelArrayList, getContext());
lv_notes.setAdapter(notesAdapter);
try calling notesAdapter.notifyDatasetChanged(); inside setPositiveButton onclick.
Related
I'm adding items to a list in a Recyclerview Adapter via an input dialog. when a user enters a value in a textfield and clicks on submit button, I want the entered value to be added to a list which is declared public in a fragment such that if I go to the fragment and click on showListSize button, I should see the size of the list(in fragment) being greater than 0;
Adding an item to the list in RecyclerView works but the size cannot exceed 1. What could I be doing wrong.
Here is a sample code:
//Adapter, constructor and variables declaration
//on create viewholder
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
List<Item2> valuesList = new ArrayList<Item2>(child.get(groupname));
childSize = valuesList.size();
Log.i("List size", String.valueOf(childSize));
if (childSize > 0){
//final String childText = (String) getChild(groupPosition,position);
final Item2 item = valuesList.get(position);
holder.name.setText(item.getItemName());
//holder.itemImage.setImageResource(Integer.parseInt(item.getImageUrl()));
holder.price.setText(String.valueOf(item.getPrice()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.select_quantity);
Button button_submit = dialog.findViewById(R.id.btn_submit);
final EditText edQuantity = dialog.findViewById(R.id.txt_quantity);
edQuantity.setText("0");
button_submit.setOnClickListener(new View.OnClickListener() {
float totalPrice = 0;
#Override
public void onClick(View view) {
String quantity = edQuantity.getText().toString();
totalPrice = Float.parseFloat(quantity) * Float.parseFloat(item.getPrice());
myLocal.add(new CartItem(quantity, item.getItemName(), item.getPrice(),String.valueOf(totalPrice)));
AllProducts myProducts = new AllProducts(); //this is the fragment
myProducts.theSelected.add(new CartItem(quantity,item.getItemName(), item.getPrice(),String.valueOf(totalPrice)));
Log.i("size(Recycler)",String.valueOf(myProducts.theSelected.size())); //this is ok returns 1
dialog.dismiss();
}
});
dialog.show();
AllProducts fragment
public List<CartItem> theSelected = new ArrayList<CartItem>();//list declaration
btnShowListSize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("list(AllProducts)", String.valueOf(theSelected.size()));//returns 0
}
});
I defined a global ArrayList like this
private List<Items> selectedItems = new ArrayList<>();
Then a method to add items, still in global class
public void addItems(Item item) {
this.selectedItems.add(item);
}
Then in a class somewhere in the project:
final Globals myGlobals = Globals.getInstance();
Item myItem = new Item("var1", "var2", "var3");
myGlobals.addItems(myItem);
Sincere apologies for no code, I'm leaving for a wedding and it was either post code or explain my situation.
I've searched Stack and see many posts for Recycler Adapter to Fragment (that created the adapter) interfaces.
A minor few for Fragment(created the adapter) to Adapter posts but they are not nearly as clear.
My situation is this:
On Main Activity, when App is running:
1) Fragment Lyrics (created the REcycler ADapter that is set into a Lyric Recycler View)
2) Fragment Microphone ( speech recognition microphone functionality and XML icon).
What I want to happen is:
user activates Microphone and speaks, that resulting data is passed to the ADAPTER java file and activates a method on the ADAPTER, causing a visual change to RecyclerView Viewholder on the screen.
Yes, I know this is probably bad architecture. It's for a school project, I'm learning, and I've run out of time.
* What I can do so far *
I have activated the pre-made OnClick listerner for the Adapter (when a user clicks on a View) and OnScroll for the RecyclerView (user scrolls, it fires a method in the Adapter that causes the current View to change).
I have made interface for Passing Speech data from Microphone Fragment, through the Main Activity, to the Lyrics Fragment.
On Main, I simply create an instance of the Lyrics Fragment, then call a custom method on Lyrics Fragment that takes the speech data. Something like this.
LyricsFragment.TakeSpeechData(speech data);
* What my plans was...*
When the speech data arrives on Lyrics Fragment, I thought I could just write something like:
MyRecyclerAdapter.SomeMethodOnAdapter (speech data);
I would be home free at this point.
It doesn't work
No go. I get a null pointer exception here. The MyRecyclerAdapter part of the method call is null. I've looked that up and not sure how to fix it.
I'm assuming I'm referencing the original Adapter that was created when the Fragment layed down the RecyclerView and set everything. It's the same global variable for the Adapter on Fragment Lyrics and I'm assuming it "lives on".
I'm sure I'm missing on fundamental Java principles but i don't know what.
I've spent hours and hours on this trying , reading, researching. I'm totally stuck. Please help.
EDIT: Here is my code for VerseFragment (I'm referring to it as "Lyrics" Fragment in my post). Note this Fragment is loaded, created, and functional with recyclerView on screen. Before the user uses the micrphone fragment, which is also on screen, this has already been created.
public class VersesList extends Fragment {
#BindView(R.id.versesRecycleView) RecyclerView versesRecycleView;
#BindView(R.id.songNameTextView) TextView songName;
#BindView(R.id.artistTextView)TextView artistName;
private SharedPreferences mSharedPreferences;
LinearLayoutManager llm;
List verseList;
List finalModVerseList;
public VerseAdapter verseAdapter;
// temporary
private SharedPreferences.Editor editor;
public VersesList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_verses_list, container, false);
ButterKnife.bind(this, view);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
editor=mSharedPreferences.edit();
displayArtistAndSongName();
lyricsToVerseList();
setVersesIntoRecyclerView();
setVersesScrollListener();
//temp
storeAllVerseLevels();
return view;
}
public static VersesList newInstance(String lyrics){
VersesList versesListFragment = new VersesList();
Bundle args = new Bundle();
args.putString("lyrics", lyrics);
versesListFragment.setArguments(args);
return versesListFragment;
}
public void lyricsToVerseList(){
String lyrics = getArguments().getString("lyrics", "");
verseList = new ArrayList<String>();
finalModVerseList = new ArrayList<String>();
verseList= Arrays.asList(lyrics.split("\n"));
int endOfFinalList=verseList.indexOf("...");
for (int i = 0; i < endOfFinalList; i++) {
if(!verseList.get(i).toString().equals("")){
String addThisVerse = verseList.get(i).toString();
//check on length of verse, if too short add next, check again
int numberOfWords = addThisVerse.split(" ").length;
while (numberOfWords < 10 && i < endOfFinalList) {
i++;
addThisVerse += " " + verseList.get(i).toString();
numberOfWords = addThisVerse.split(" ").length;
}
finalModVerseList.add(addThisVerse);
}
}
}
public void displayArtistAndSongName(){
String song = '"'+mSharedPreferences.getString(SONG_NAME, null)+'"';
String artist = "by "+mSharedPreferences.getString(ARTIST_NAME, null);
songName.setText(song);
artistName.setText(artist);
}
public void setVersesIntoRecyclerView(){
verseAdapter = new VerseAdapter(finalModVerseList, (MainActivity)getActivity(), versesRecycleView);
versesRecycleView.setAdapter(verseAdapter);
llm = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL, false);
versesRecycleView.setLayoutManager(llm);
PagerSnapHelper helper = new PagerSnapHelper();
helper.attachToRecyclerView(versesRecycleView);
}
private void storeLevel(int indexNumber) {
editor.putInt(String.valueOf(indexNumber), 1).apply();
}
private void storeAllVerseLevels(){
for (int i=0; i< finalModVerseList.size();i++){
storeLevel(i);
}
for (int j=0; j< finalModVerseList.size();j++){
String level = String.valueOf(mSharedPreferences.getInt(String.valueOf(j), -1));
Log.d("In Shared Preferences ", "Verse "+j+" Level "+level);
}
}
public void checkSpeech(String text){
List<String> temp = new ArrayList<>();
temp.add("test");
VerseAdapter adapter = new VerseAdapter(temp, (MainActivity)getActivity(), versesRecycleView);
try {
adapter.resetVerse();
}catch (NullPointerException e){
Log.d("Null", e.toString());
}
}
public void setVersesScrollListener(){
versesRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == 0) {
verseAdapter.resetVerse();
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
}
}
When you are calling the method from your adapter, is MyRecyclerAdapter an instance or the class? To call someMethodOnAdpater(speechData), you must use an instance . Xia is using an instance.
If you need to call an adapter method from within the fragment in which it was created, you can store it in a variable like this.
MyRecyclerAdapter adapter;
#Override
public View onCreateView(...) {
...
adapter = new MyRecyclerAdapter();
myRecyclerView.setAdapter(adapter);
...
}
public void takeSpeechData(String data) {
adapter.someMethodAdapter(data);
}
Edit:
I'm not sure why the same adapter used by your recyclerview is null after being set. Calling an adapter from is definitely possible (I tested a basic example). The code in my example doesn't differ from what you said you had previously, though. I have upvoted your question for visibility.
**Edit: Add Mic Fragment, it has the interface **
package com.blueoxgym.javainthedark.Fragments;
/**
* A simple {#link Fragment} subclass.
*/
public class MicFragment extends Fragment implements View.OnClickListener {
#BindView(R.id.progressBarMic)
ProgressBar micLevels;
#BindView(R.id.btn_mic)
ImageButton btnMicrophone;
private SpeechRecognizer speech = null;
private Intent recognizerIntent;
public final static String TAG = "In speech mode";
public FragmentManager fragmentManager;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private String trackName;
private String artistName;
private CallMainLoadVerseFragment loadVerseFragment;
private CheckSpeech checkSpeechOnVerse;
public MicFragment() {
// Required empty public constructor
}
public static MicFragment newInstance (){
MicFragment micFragment = new MicFragment();
return micFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_mic, container, false);
ButterKnife.bind(this, view);
this.loadVerseFragment = (CallMainLoadVerseFragment) getActivity();
this.checkSpeechOnVerse = (CheckSpeech) getActivity();
btnMicrophone.setOnClickListener(this);
fragmentManager = getFragmentManager();
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSharedPreferences.edit();
return view;
}
#Override
public void onClick(View v) {
if (v == btnMicrophone) {
startSpeechToText();
}
}
class listener implements RecognitionListener {
...
#Override
public void onResults(Bundle results) {
String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String text = data.get(0).toLowerCase().replace("by","");
Fragment currentFragment = fragmentManager.findFragmentById(R.id.content_frame);
if (currentFragment.toString().contains("LyricSearch")){
searchForSong(text);
} else if (currentFragment.toString().contains("VersesList")){
-----------> Here it is called checkSpeechOnVerse.checkingSpeech(text);
}
}
}
public void startSpeechToText(){
btnMicrophone.setBackgroundResource(R.drawable.circle_green);
speech=SpeechRecognizer.createSpeechRecognizer(getContext());
speech.setRecognitionListener(new listener());
recognizerIntent= new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en-US");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getActivity().getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
speech.startListening(recognizerIntent);
}
...
...
public interface CheckSpeech {
void checkingSpeech (String text);
}
}
MainActivity, implements CheckSpeech Interface
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MicFragment.CallMainLoadVerseFragment, MicFragment.CheckSpeech {
....
...
#Override
public void checkingSpeech(String text) {
VersesList versesList = new VersesList();
--------> Now, I'm pass data from Main to VersesList Fragment(it has the original Adapter)
versesList.checkSpeech(text);
}
VersesList Fragment, where I try to call Adapter
public class VersesList extends Fragment {
....
private VerseAdapter verseAdapter;
setVersesIntoRecyclerView();
....
<---ADAPTER IS MADE AND SET HERE----.
public void setVersesIntoRecyclerView(){
verseAdapter = new VerseAdapter(finalModVerseList, (MainActivity)getActivity(), versesRecycleView);
versesRecycleView.setAdapter(verseAdapter);
llm = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL, false);
versesRecycleView.setLayoutManager(llm);
PagerSnapHelper helper = new PagerSnapHelper();
helper.attachToRecyclerView(versesRecycleView);
}
public void checkSpeech(String text){
-------> NPE NPE
versesAdapter.someMethodOnAdapter(text);
}
public void setVersesScrollListener(){
versesRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == 0) {
BUT THIS WORKS!!! No NPE. --------> verseAdapter.resetVerse();
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// VerseAdapter.VerseViewHolder view = versesRecycleView.findViewHolderForAdapterPosition(llm.findFirstVisibleItemPosition());
}
});
}
If you need to call an adapter method from within the fragment in which it was created, you can store it in a variable within that fragment.
MyRecyclerAdapter adapter;
#Override
public View onCreateView(...) {
...
adapter = new MyRecyclerAdapter();
myRecyclerView.setAdapter(adapter);
...
}
public void takeSpeechData(String data) {
adapter.someMethodAdapter(data);
}
Then you can call that method directly from another fragment. (link to accessing fragments)
VersesList versesList = (VersesList) getActivity().getSupportFragmentManager.findFragmentById(containerId);
versesList.takeSpeechData("data");
gif of example
In my application I have dynamic vertical boom menu. However menu is being opened only if user clicks boom menu button and I want to show it immidiately after activity is created. I searched for solution this this issue and found few but none of them worked. Heres my onCreate method :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_new_pik, container, false);
ButterKnife.bind(this,view);
EventBus.getDefault().register(this);
Category category1 = new Category();
Category category2 = new Category();
Category category3 = new Category();
Category category4 = new Category();
Category category5 = new Category();
categories = new ArrayList<>();
categories.add(category1);
categories.add(category2);
categories.add(category3);
categories.add(category4);
categories.add(category5);
adapter = new CategoryAdapter(categories,getActivity().getApplicationContext());
mScrollView.setAdapter(adapter);
mScrollView.scrollToPosition(2);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mScrollView.findViewHolderForAdapterPosition(2).itemView.callOnClick();
}
},1);
mScrollView.setItemTransformer(new ScaleTransformer.Builder()
.setMaxScale(1.05f)
.setMinScale(0.8f)
.setPivotX(Pivot.X.CENTER) // CENTER is a default one
.setPivotY(Pivot.Y.BOTTOM) // CENTER is a default one
.build();
return view;
}
This is my onBindViewHolder :
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Category category = channelList.get(position);
holder.menuButton.clearBuilders();
holder.menuButton.setButtonEnum(ButtonEnum.SimpleCircle);
holder.menuButton.setPiecePlaceEnum(PiecePlaceEnum.DOT_6_3);
holder.menuButton.setButtonPlaceEnum(ButtonPlaceEnum.SC_6_3);
holder.menuButton.setDotRadius(0);
holder.menuButton.setBackground(mContext.getResources().getDrawable(R.drawable.category_empty_icon));
holder.menuButton.setNormalColor(mContext.getResources().getColor(R.color.transparent));
holder.menuButton.setShadowEffect(false);
for (int i = 0; i < holder.menuButton.getButtonPlaceEnum().buttonNumber(); i++) {
holder.menuButton.addBuilder(new SimpleCircleButton.Builder()
.normalColor(mContext.getResources().getColor(R.color.white))
.normalImageRes(R.drawable.logo_splash_screen)
.listener(new OnBMClickListener() {
#Override
public void onBoomButtonClick(int index) {
mContext.startActivity(new Intent(mContext.getApplicationContext(), AddPikActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}));
}
}
Any help please ?
From a list, the user can click and item and a fragment will inflate showing the data for the clicked item, where the user also can edit that data and click save to save the edited data.
But from the screen that contains the list is also an add button if the user wants to create a new object.
When the user clicks on an item from the list, a newInstance(..); is called
and in the Fragments onCreateView(); I initilize all variables for that clicked item in the different views. But that is not working well because I keep getting:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on a null object reference
newInstance is called from the RecyclerView Adapter onClick():
public static CreateTrainingFragment newInstance(ItemModel itemModel) {
bundle = new Bundle();
bundle.putInt(SB_DURATION, itemModel.getDuration());
bundle.putInt(SB_DISTANCE, itemModel.getDistance());
CreateTrainingFragment createTrainingFragment = new CreateTrainingFragment();
createTrainingFragment.setArguments(bundle);
return createTrainingFragment;
}
Here I use getArguments(); and feed the arguments into Views:
Would the default 0 variable not automatically be inserted into my sbduration.setProgress(); if the argument dont exist?
private void initArgumentsData() {
sbduration.setProgress(getArguments().getInt(SB_DURATION, 0));
sbDistance.setProgress(getArguments().getInt(SB_DISTANCE, 0));
txtduration.setText(getArguments().getInt(SB_DURATION, 0) + " min");
txtDistance.setText(getArguments().getInt(SB_DISTANCE, 0) + " km");
}
Here is how my Views is created and where I use InitArgumentData();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.createtraining_layout, container, false);
sbduration = (SeekBar) v.findViewById(R.id.seekbar_time);
sbDistance = (SeekBar) v.findViewById(R.id.seekbar_distance);
txtduration = (TextView) v.findViewById(R.id.time_value);
txtDistance = (TextView) v.findViewById(R.id.distance_value);
sbduration.setMax(100);
sbDistance.setMax(50);
initArgumentsData();
}
From RecyclerView I start a new fragment instance like this:
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ItemModel itemModel = realm.getDefaultInstance().where(ItemModel.class).equalTo("timestamp",list.get(getAdapterPosition()).getTimestamp()).findFirst();
CreateTrainingFragment createTrainingFragment = CreateTrainingFragment.newInstance(itemModel, true);
fragmentManager.beginTransaction().replace(R.id.navdrawer_maincontainer,createTrainingFragment).addToBackStack(null).commit();
}
});
From the add button the Fragment is started like this:
addbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.navdrawer_maincontainer,new CreateTrainingFragment()).addToBackStack(null).commit();
}
});
getFragmentManager().beginTransaction().replace(R.id.navdrawer_maincontainer,new CreateTrainingFragment()).addToBackStack(null).commit();
Here, you're using new CreateTrainingFragment(). Hence, you're not getting the bundle since there is no bundle attach to it. You should call the newInstance method first to get the an object of CreateTrainingFragment and then put it on replace.
ItemModel itemModel = realm.getDefaultInstance().where(ItemModel.class).equalTo("timestamp",list.get(getAdapterPosition()).getTimestamp()).findFirst();
CreateTrainingFragment createTrainingFragment = CreateTrainingFragment.newInstance(itemModel, true);
getFragmentManager().beginTransaction().replace(R.id.navdrawer_maincontainer, createTrainingFragment).addToBackStack(null).commit();
How about you just check if the arguments exist?
private void initArgumentsData() {
Bundle args = getArguments();
int duration = 0;
int distance = 0;
if (args != null) {
duration = args.getInt(SB_DURATION, 0);
distance = args.getInt(SB_DISTANCE, 0);
}
sbduration.setProgress(duration);
sbDistance.setProgress(distance);
txtduration.setText(duration + " min");
txtDistance.setText(distance + " km");
}
Even if you did call newInstance on the Fragment, you still would need to provide a new ItemModel to that method.
I am using BackendLess backend service, but my prob is (i guess) more to android/java. So even if u are not familiar with BackendLess, i guess u can help, if u know of course :)
I have there a Fragment that calls and opens a DialogFragment with a ListView.
Using there an iterator to retrieve the data. It brings each column from the data table as an Array.
I set an onClickedItemListener that when item is clicked, it send the value to a TextView in the Fragment it was called from.
The data comes in the wrong order - didnt get how to do a sortBy, that connects to the bigger prob i have there -
There is a column there named "PropertyTypes". It holds 4 strings, which are coming out in the opposite order that i need. I want the "A" first, and get:
"D"
"C"
"B"
"A"
ok, so far no big deal, i guess can be sorted out with a sortBy that i just dont know how to do.
But... what happens is that it sends the wrong value to the TextView, meaning, for example, when i press "C" it set "A" on the TextView and so on, and, when i press the last one, in this case "A", the app is crashing...
What the hell is going on there?? :))
Here is the code -
The DialogFragment code:
public class OptionDialogFragment extends DialogFragment implements
AdapterView.OnItemClickListener {
ListView mylist;
TextView chosenProperty;
TextView presentListItem;
ArrayAdapter adapter;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//mylist.addHeaderView(inflater.inflate(R.layout.option_dialog_header, null, false));
View view = inflater.inflate(R.layout.option_dialog_content, null, false);
mylist = (ListView) view.findViewById(R.id.list);
View headerView = inflater.inflate(R.layout.option_dialog_header, mylist, false);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
mylist.addHeaderView(headerView);
View footerView = inflater.inflate(R.layout.option_dialog_footer, mylist, false);
footerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
mylist.addFooterView(footerView);
chosenProperty = (TextView) view.findViewById(R.id.chosenProperty);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ArrayList<String> propertyTypes = new ArrayList<String>();
final ArrayList<Integer> numOfRoomies = new ArrayList<Integer>();
Backendless.Data.of(DialogOptions.class).find(new AsyncCallback<BackendlessCollection<DialogOptions>>() {
#Override
public void handleResponse(final BackendlessCollection<DialogOptions> dialogOptions) {
final Iterator<DialogOptions> iterator = dialogOptions.getCurrentPage().iterator();
while (iterator.hasNext()) {
DialogOptions dialogOptionsObject = iterator.next();
propertyTypes.add(dialogOptionsObject.getPropertyTypes());
// numOfRoomies.add( dialogOptionsObject.getNumOfRoomies() );
}
adapter = new ArrayAdapter<String>(getActivity(), R.layout.dialog_option_list_item, R.id.presentListItem, propertyTypes);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String chosenItem = propertyTypes.get(position);
Intent intent = new Intent();
intent.putExtra("chosenItem", chosenItem);
getTargetFragment().onActivityResult(
getTargetRequestCode(), Activity.RESULT_OK, intent);
dismiss();
}
});
}
#Override
public void handleFault(BackendlessFault fault) {
// TODO: make sure to log the exception, just in case
}
});
}
}
This is the Relevant code in the Fragment that calls the DialogFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.find_a_place, container, false);
chosenProperty = (TextView) view.findViewById(R.id.chosenProperty);
return view;
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
final LinearLayout propertTypes = (LinearLayout)view.findViewById(R.id.propertyTypes);
propertTypes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(getActivity(), "OptionDialog");
}
});
}
private void showDialog(FragmentActivity activity, String optionDialog) {
android.support.v4.app.FragmentManager manager = getFragmentManager();
DialogFragment dialog = new OptionDialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(manager, "OptionDialog");
dialog.setCancelable(true);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
if(data!=null){
// set value to your TextView
chosenProperty.setText(data.getStringExtra("chosenItem"));
}
}
break;
}
}
Thanks a lot in advance for any answer!!
Reference :-
https://backendless.com/feature-47-loading-data-objects-from-server-with-sorting/
To Sort while retrieving Object use :-
QueryOptions queryOptions = new QueryOptions();
queryOptions.addSortByOption( "created ASC" );
dataQuery.setQueryOptions( queryOptions );
Use Query as below:-
// fetch restaurants
Backendless.Data.of( Restaurant.class ).find( dataQuery, new AsyncCallback<BackendlessCollection<Restaurant>>(){