Refresh fragment listview on Activity back button press - android

I have a fragment which contains a listview of some items. On click of an item in the list view an Activity is started to view the details about the list view. There is a back button on the Activity which brings us back to the fragment page. Once the back button is pressed and the activity page closes I want the data to be refreshed in the fragment list view. I have tried onResume() method but it does not refresh the data.
Can someone please help me how to achieve this am pretty new at this.
public class FavCommittee extends Fragment {
public ArrayList<Committee> favCommitteeData = new ArrayList<>();
#Nullable
#Override
public void onResume(){
super.onResume();
final SharedPreferences pref = getContext().getSharedPreferences("MyFav", 0);
final SharedPreferences.Editor editor = pref.edit();
View rootView =getView();
Map<String,?> entries = pref.getAll();
final Set<String> keys = entries.keySet();
int count=0;
for (String key:keys) {
String val = pref.getString(key, null);
String[] store = val.split(":");
if (store[0].equals("committee"))
count=count+1;
}
for (int i=0;i<keys.size();i++) {
String val = pref.getString(Integer.toString(i), null);
if (val != null) {
String[] store = val.split(":");
if (store[0].equals("committee")) {
count = count - 1;
new GetAllCommittees(getContext(), rootView).execute(store[1], Integer.toString(count));
}
}
} final ListView yourListView = (ListView) rootView.findViewById(R.id.house_listview);
yourListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Committee obj = (Committee)yourListView.getItemAtPosition(position);
Intent intent = new Intent(FavCommittee.this.getActivity(), committee_info.class);
intent.putExtra("Committee",obj.getCommittee_id());
startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.house, container, false);
return rootView;
}

When you are transitioning between Fragments, call addToBackStack() as part of your FragmentTransaction:
FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag").commit();
If you require more detailed control (i.e. when some Fragments are visible, you want to suppress the back key) you can set an OnKeyListener on the parent view of your fragment:
//You need to add the following line for this solution to work,
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
return true;
}
return false;
}
} );

getSupportFragmentManager().beginTransaction().add(R.id.fragContainer, new FavCommittee (), FavCommittee .class.getName()).commit();
Try this code.
Put the code where u add your Fragment in Activity

Related

Non Recycler Fragment calling method on Recycler Adapter? Is this even possible?

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

Wrong ListView item is passed by the intent

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>>(){

Android listview clicking on item multiple times

I have a listview with several items. When clicking on an item, an Activity is opened. However, when I click fast several times on the item, the activity, asociated with it, is opened several times. How to open the item only once?
I use the following code:
private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyObject newsfeed = adapter.getItem(position);
onNewsfeedClick(newsfeed);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newsfeed, container, false);
...
listView = (ListView) view.findViewById(R.id.newsfeeds);
listView.setOnItemClickListener(newsfeedClickHandler);
listView.setAdapter(adapter);
...
return view;
}
private void onNewsfeedClick(MyObject newsfeed) {
Intent intent = createIntent(newsfeed);
startActivity(intent);
}
The correct way to prevent calls to the ListView items would be to (obviously) disable the OnItemClickListener:
private void onNewsfeedClick(MyObject newsfeed) {
listView.setOnItemClickListener(null);
Intent intent = createIntent(newsfeed);
startActivity(intent);
}
Re-set the listener at onResume, when this activity is visible again.
#Override
protected void onResume() {
super.onResume();
listView.setOnItemClickListener(newsfeedClickHandler);
}
Maintain a boolean value say isItemClicked and reset it when you return back to the listview.
private boolean isItemClicked;
private OnItemClickListener newsfeedClickHandler = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!isItemClicked) {
isItemClicked = true;
MyObject newsfeed = adapter.getItem(position);
onNewsfeedClick(newsfeed);
}
}
};
private void resetIsItemClicked() {
isItemClicked = false;
}
To prevent multiple clicks on ListView Items, add the following code in your listview click listener:
if (SystemClock.elapsedRealtime() - mLastClickTimeListViewItem < 1000){
return;
}

ListView not refreshed until user interaction

I have a ListView and a custom adapter. When the user changes the sort type from a spinner, I want to redraw the list with the new items. The problem is that the ListView is re-drawn only after I interact with it on the device (start scrolling for example).
if (update) {
mOfferList = (ArrayList<PositionSearchItem>) psr
.getPositionSearchItem();
mAdapter.clear();
mAdapter.addAll(mOfferList);
mAdapter.notifydataSetChanged()
mList.invalidate();
mList.invalidateViews();
}
I have also tried to fully reset a new instance of my adapter to the list, it is giving the same result except that the list becomes blank at first and appears on user interaction.
I'm using HoloEveryWhere maybe this is an important info.
EDIT : Here is some more code
#EFragment(R.layout.list_fragment_results)
public class ResultsListFragment extends Fragment {
#ViewById(R.id.search_results_list)
ListView mList;
#ViewById(R.id.search_result_list_spinner)
Spinner mSpinner;
MainActivity mActivity;
private String mTypedText;
private List<String> mSortType;
private ResultsListFragment mFrag;
private Bundle mOffersPageBundle;
private SearchResultsListAdapter mAdapter;
private ArrayList<PositionSearchItem> mOfferList;
#AfterViews
public void afterViews() {
mFrag = this;
mActivity = (MainActivity) getActivity();
mSortType = new ArrayList<String>();
mSortType.add(SearchResultSortType.SCORE_DESCENDING);
mOfferList = new ArrayList<PositionSearchItem>();
mOffersPageBundle = getArguments();
PositionSearchResponse psr = mOffersPageBundle.getParcelable("offers");
mTypedText = mOffersPageBundle.getString("typedText");
mOfferList = (ArrayList<PositionSearchItem>) psr.getPositionSearchItem();
mAdapter = new SearchResultsListAdapter(this,
android.R.layout.simple_list_item_1, mOfferList, mTypedText,
mSortType, mActivity.getLat(), mActivity.getLon());
mList.setAdapter(mAdapter);
this.setListeners();
}
private void setListeners() {
mSpinner.setOnItemSelectedListener(new org.holoeverywhere.widget.AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(
org.holoeverywhere.widget.AdapterView<?> parent, View view,
int pos, long id) {
Boolean update = false;
PositionSearchResponse psr = null;
switch (pos) {
case 0:
if (mSortType.get(0) != SearchResultSortType.SCORE_DESCENDING) {
mSortType.clear();
mSortType.add(SearchResultSortType.SCORE_DESCENDING);
psr = processSearch(mTypedText, mSortType, 0, mActivity);
update = true;
}
break;
case 1:
if (mSortType.get(0) != SearchResultSortType.DATE) {
mSortType.clear();
mSortType.add(SearchResultSortType.DATE);
psr = processSearch(mTypedText, mSortType, 0, mActivity);
update = true;
}
break;
default:
break;
}
if (update) {
mOffersPageBundle.putParcelable("offers", psr);
mOfferList = (ArrayList<PositionSearchItem>) psr
.getPositionSearchItem();
mAdapter.mIdMap.clear();
for (int i = 0; i < mOfferList.size(); ++i) {
mAdapter.mIdMap.put(mOfferList.get(i), i);
}
mOfferList = (ArrayList<PositionSearchItem>) psr
.getPositionSearchItem();
mAdapter.clear();
mAdapter.addAll(mOfferList);
mAdapter.notifydataSetChanged()
mList.invalidate();
mList.invalidateViews();
}
}
#Override
public void onNothingSelected(
org.holoeverywhere.widget.AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
EDIT : the getView method from custom adapter
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
this.v = convertView;
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
PositionSearchItem psr = getItem(pos);
v = vi.inflate(R.layout.result_list_item, parent, false);
v.setTag(pos);
// Inject text into view
((TextView) v.findViewById(R.id.result_title_textview))
.setText(getItem(pos).getTitle());
// Disable hardware acceleration for the view (it brakes dotted lines on
// some devices)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
v.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// reload list if scrolled to bottom
int page = 0;
if (pos > mLastViewed && pos == getCount() - 1) {
mLastViewed = pos;
ResultsListFragment frag = new ResultsListFragment_();
PositionSearchResponse newSearch = frag.processSearch(mTypedText, mSortType, mPage,
mActivity);
mPage = mPage + 12;
if(newSearch != null && newSearch.getPositionSearchItem() != null && newSearch.getPositionSearchItem().size() > 0){
for (int i = 0; i < newSearch.getPositionSearchItem().size(); ++i) {
mIdMap.put(newSearch.getPositionSearchItem().get(i), i);
}
this.addAll(newSearch.getPositionSearchItem());
}
}
return v;
}
Use
if (update) {
mAdapter.NotifyDataSetChanged();
}
this may solve your problem.
Try to set the adatpter again.Place the below code in all the places you wrote the code to update listview
mAdapter = new YourAdapter();
mList.setAdapet(mAdapter)
I hope you have created custom list view using adapter and model.
Now each time when you need to update your list view dynamically then you need to clear your previously created list view. Then after you need to fetch all new values and then update same over custom list view.
Hope it helps!

Using Intent with actions

Right. I have an action that needs to call another activity. As I understand this, I need to use Intents to do so if I want to parse values to this activity.
However, my code fails and im a little lost as to why.
My main activity:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
/*Menu item: String name, String menu ID*/
/*ToDo: Logic to fecth new menu structure from server*/
menuItem MI1 = new menuItem("menu item 1","1");
menuItem MI2 = new menuItem("menu item 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new menuAdapter(this, AMI));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
//Toast.makeText(Runner.this, AMI.get(position).getMenuID(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), showMenu.class);
myIntent.putExtra("parentID", AMI.get(position).getMenuID());
startActivityForResult(myIntent, 0);
}
});
The "Toast" works just fine, however when I call the showMenu class it crashes.
The showMenu class looks as follows:
public class showMenu extends Activity{
public String menuParent = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.submenu);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
menuParent = extras.getString("parentID");
}
/*ToDo: Logic to fecth new menu structure from server*/
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
menuItem MI1 = new menuItem("submenu 1","1");
menuItem MI2 = new menuItem("submenu 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new subMenuAdapter(this, AMI));
}
public class subMenuAdapter extends BaseAdapter {
private ArrayList<menuItem> MIL = new ArrayList<menuItem>();
public static final int ACTIVITY_CREATE = 10;
public subMenuAdapter(Context c, ArrayList<menuItem> AMI) {
MIL = AMI;
}
public int getCount() {
return MIL.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
v = (LinearLayout) li.inflate(R.layout.grid_item, null);
TextView tv = (TextView)v.findViewById(R.id.grid_text);
tv.setText(MIL.get(position).getMenuname());
} else {
v = convertView;
}
return v;
}
}
}
Any idea why it crashes?
I think you have to register your Intent in your AndroidManifest.xml
<activity
android:name="Package.Name.showMenu"
android:theme="#android:style/Theme.Light"></activity>
As both activities are from same application, there are some other ways as well to pass data between instead of intents. check the link below:
http://developer.android.com/resources/faq/framework.html#3
If you want to use only intents, can you please specify the error you are facing, so that someone can reply you correctly.
if you want to parse values to another activity,you must use startActivityForResult.This is called sub_activity.

Categories

Resources