Menu button lags a long time when pressed - android

I have a problem with a menu button called "Refresh" that lags for a long time when pressed. Basically, I'm running an async task that downloads xml from a web page and processes it and then finally updates the current list view. Is there some way to prevent this lag or refactor my code to make it more efficient?
Here is my activity where the refresh problem happens:
public class RouteView extends ListActivity implements ActivityUpdater {
private static ArrayList<String> mRouteNames;
private final String TAG = getClass().getName();
private TextView mTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.route_view);
ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, lv, false);
lv.addHeaderView(header, null, false);
mTv = (TextView) findViewById(R.id.refresh_status);
long start = System.nanoTime();
fetchFeed();
Log.i("MagicBusV2", "Time: " + (System.nanoTime() - start));
}
#Override
protected void onResume() {
super.onResume();
fetchFeed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, Constants.REFRESH_MENU_ID, 0, R.string.refresh).setIcon(R.drawable.refresh);
return result;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case Constants.REFRESH_MENU_ID:
long start = System.nanoTime();
fetchFeed();
Log.i("MagicBusV2", "Refresh time: " + (System.nanoTime() - start));
break;
}
return result;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i(TAG, "id: " + (int) id);
Log.i(TAG, "num_routes: " + mRouteNames.size());
String routeName = mRouteNames.get((int) id);
Intent intent = new Intent(this, StopView.class);
intent.putExtra(Constants.ROUTE_NAME, routeName);
intent.putExtra(Constants.STOP_VIEW_TYPE, Constants.STOPS_ROUTE);
startActivity(intent);
}
public void refreshUI() {
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mRouteNames));
getListView().setTextFilterEnabled(true); // allows users to type to filter results, need to inform them of this some way
mTv.setText("Refreshed!");
}
public static void setRouteNames(ArrayList<String> route_names) {
mRouteNames = route_names;
}
private void fetchFeed() {
mTv.setText("Refreshing...");
new RefreshFeedTask(this).execute("null");
}
And here is my AsyncTask code:
public class RefreshFeedTask extends AsyncTask<String, Integer, Void> {
private ArrayList<Route> routes;
private TimeFeed feed;
private ActivityUpdater updater;
private Context mCtx;
public RefreshFeedTask(Context ctx) {
mCtx = ctx;
updater = (ActivityUpdater) mCtx;
routes = new ArrayList<Route>();
try {
feed = new TimeFeed();
} catch (MBusDataException e) {
e.printStackTrace();
}
}
protected Void doInBackground(String... route_name) {
routes = feed.getRoutes();
int num_routes = routes.size();
if(route_name[0].equals("null")) {
ArrayList<String> route_names_list = new ArrayList<String>(num_routes);
for (int i = 0; i < num_routes; i++) {
route_names_list.add(routes.get(i).getName());
}
RouteView.setRouteNames(route_names_list);
} else if(route_name[0].equals("all_stops")) {
ArrayList<Stop> stops = new ArrayList<Stop>();
for (Route route : routes) {
for (Stop stop : route.getStops()) {
if(!stops.contains(stop)) {
stops.add(stop);
}
}
}
StopView.setStops(stops);
} else if(route_name.length > 1) {
Route route = feed.getRouteWithName(route_name[0]);
StopDetailsView.setStop(route.getStopWithName(route_name[1]));
} else if(route_name[0].equals("favorites")) {
ArrayList<Stop> fav_stops = new ArrayList<Stop>();
ArrayList<Favorite> allFavs = FavoritesStore.getInstance(mCtx).getAllFavorites();
for (Favorite fav : allFavs) {
Route route = feed.getRouteWithName(fav.getRouteName());
if (route != null) {
Stop stop = route.getStopWithName(fav.getStopName());
if (stop != null) {
fav_stops.add(stop);
}
}
}
StopView.setStops(fav_stops);
} else {
StopView.setStops(feed.getRouteWithName(route_name[0]).getStops());
}
return null;
}
protected void onPostExecute(Void ignore) {
updater.refreshUI();
}
Thanks for any help you can give. I apologize if I posted too much code; I wasn't sure how much was needed to find potential problems.

Look at the constructor of the TimeFeed class. Since you said, that you are downloading and parsing stuff, and I believe that you are perhaps doing those things in the constructor, it will obviously take some time to execute that statement.

Related

How to pass data from activity to fragment class?

I created a new project tabbed view. I want three layout on my main screen 1st home 2nd category 3rd favorite. I have code of Home activity which is fragment activity the code is here
public class HomeFragment extends android.support.v4.app.Fragment {
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
and I have another activity which is video playlist. I want to show the playlist activity in my home fragment page but I am too confused and new to Android I don't have idea what to do.
The code of video playlist is here. How can I call this code in my homeFragment class? I tried too many ways but got too confused.
Code is here which I want to implement in my home section
public ProgressBar nextBar;
List<String> next_title;
List title;
List vid;
List<String> next_vid;
ArrayList<Videos> videos=new ArrayList<Videos>();
Videos video;
ArrayList<Videos> toclear=new ArrayList<Videos>();
List<Videos> fav = new ArrayList<Videos>();
InterstitialAd mInterstitialAd;
ListView listview;
Toolbar toolbar,favourite;
int menu_id;
LinearLayout layout, no_fav;
private HttpHandler parserVideo;
String nextPageToken;
String apiKey = "AIzaSyDD73ZAzcR6bXa1qOv8YZY3fFmNwfTPs48";
String url;
Main_activity_adapter search;
Main_activity_adapter adapter;
String url_home= "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=15&playlistId=PLQGGrzFoybiOks7f2BReNzNwkRw3cN6RB&key="+apiKey+"";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_sec);
nextBar = (ProgressBar) findViewById(R.id.nextProgress);
layout = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
url = url_home;
listview = (ListView) findViewById(R.id.listview);
no_fav = (LinearLayout)findViewById(R.id.no_favourit);
no_fav.setVisibility(View.GONE);
parserVideo = new HttpHandler();
getVideosPlaylist videosplaylist = new getVideosPlaylist();
videosplaylist.execute();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listview.setOnScrollListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
final String toolbar_name = toolbar.getTitle().toString();
MenuItemCompat.setOnActionExpandListener(myActionMenuItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
updateList();
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (!s.isEmpty()) {
setSearch();
search.getFilter().filter(s);
}
return false;
}
});
return true;
}// end of toolbar control
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void updateList(){
adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
JSONObject jp_obj;
JSONArray jar_array;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
String toolbar_check = toolbar.getTitle().toString();
switch(view.getId()){
case R.id.listview:
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if(toolbar_check!="Favourites") {
OnScrollList onscroll = new OnScrollList();
onscroll.execute();
}
}
}
}
class getVideosPlaylist extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
jp_obj = parserVideo.getJsonFromYoutube(url);
try {
if (jp_obj.has("nextPageToken")) {
nextPageToken = jp_obj.getString("nextPageToken");
}
jar_array = new JSONArray(jp_obj.getString("items"));
if(jp_obj != null) {
JSONObject c = jar_array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
title = new ArrayList<String>(jar_array.length());
vid = new ArrayList<>(jar_array.length());
for (int j = 0; j < jar_array.length(); j++) {
c = jar_array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\\['\\]", ""));
String link = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
video = new Videos(str, link);
videos.add(video);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPreExecute() {
layout.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
updateList();
layout.setVisibility(View.GONE);
cancel(true);
super.onPostExecute(s);
}
}
class OnScrollList extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
if (nextPageToken!=null){
String nextPage = "&pageToken="+nextPageToken+"";
JSONObject next = parserVideo.getJsonFromYoutube(url+nextPage);
try {
JSONArray array = new JSONArray(next.getString("items"));
if (next != null) {
JSONObject c = array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
next_title = new ArrayList<String>(array.length());
next_vid = new ArrayList<String>((array.length()));
for (int j = 0; j < array.length(); j++) {
c = array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\'", ""));
next_title.add(str);
String nextLink = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
next_vid.add(nextLink);
video = new Videos(str, nextLink);
toclear.add(video);
}
}
}if (next.has("nextPageToken")){
nextPageToken = next.getString("nextPageToken");
}else if(!next.has("nextPageToken")){
nextPageToken = null;}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPostExecute(String s) {
videos.addAll(toclear);
adapter.notifyDataSetChanged();
nextBar.setVisibility(View.GONE);
toclear.clear();
cancel(true);
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
nextBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
public void setSearch()
{
search = new Main_activity_adapter(Videos_activity.this, videos, true);
listview.setAdapter(search);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos)search.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
public void favouritList(){
Main_activity_adapter favourit_adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(favourit_adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
Define variable like public static String test=""; in Activity then in Fragment get it like String test1=ActivityName.test; now you have value of test into test1
First of all, you need to understand that Activity contains fragments, not vice versa. So one way to make your idea come true is to make your activity contain three fragments:
1)Home
2)Category
3)Favorite
To send data from activity to fragment usually use Bundle object.
Then create the instance of the fragment and put bundle there by setArguments(yourBundle) method.
It is the main idea, if you want details then read official documentation and use search on SOF.
use a Bundle:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("yourArg","yourType"); //this could be String, int, float,etc
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.yourContainer,fragment).commit();
and in your Fragment's onCreateView:
Bundle bundle = getArguments();

Android ListView Back Button

I've made a listview and when i click an item, it filters and it shows items that filtered by what i clicked. We can think it is like a treeview.
My question is when i come last item "how can i go back one step in this listview ?". When i click device's back button it returns main activity but i want only returning back in this listview.
OsbItemsListActivity.java
public class OsbItemsListActivity extends AppCompatActivity {
private ListView sobItemsListView;
private Activity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_osb_items_list);
mContext = this;
Intent intent = getIntent();
if(null != intent){
sobItemsListView = (ListView)findViewById(R.id.activity_osb_items_list_view);
SobItemsAdapter sobItemsAdapter = new SobItemsAdapter(mContext);
sobItemsListView.setAdapter(sobItemsAdapter);
sobItemsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedItem = (String) parent.getAdapter().getItem(position);
Toast.makeText(mContext, "SOB : " + clickedItem, Toast.LENGTH_SHORT).show();
((SobItemsAdapter)parent.getAdapter()).setNextFilter(clickedItem);
((SobItemsAdapter) parent.getAdapter()).notifyDataSetChanged();
}
});
}
else {
Toast.makeText(mContext, "Listelenecek Veri Yok", Toast.LENGTH_SHORT).show();
}
}
}
And my SobItemsAdapter.java
public class SobItemsAdapter extends BaseAdapter {
public enum STEPS{ SOB, STREET, CONNECTIONARTICLE, INSTALLATION }
Activity mActivity;
List<OsbDownloadItem> osbDownloadItemList;
List<String> visualRows = new ArrayList<String>();
HashMap<String, List<OsbDownloadItem>> map;
STEPS filterStep;
public SobItemsAdapter(Activity activity){
mActivity = activity;
filterStep = STEPS.SOB;
osbDownloadItemList = SharedData.osbDownloadItemList;
setNextFilter("");
}
private void modifyVisualRows(HashMap<String, List<OsbDownloadItem>> _map){
visualRows.clear();
for(String item : _map.keySet()){
visualRows.add(item);
}
}
#Override
public int getCount() {
return visualRows.size();
}
#Override
public String getItem(int position) {
return visualRows.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = mActivity.getLayoutInflater();
View view = inflater.inflate(R.layout.activity_osb_items_row, parent, false);
if(null != view){
((TextView)view.findViewById(R.id.osb_items_sob)).setText(visualRows.get(position));
}
return view;
}
public void setNextFilter(String value){
switch (filterStep){
case SOB:
map = DataFilter.getSobs(osbDownloadItemList);
filterStep = STEPS.STREET;
break;
case STREET:
map = DataFilter.getStreetsBySob(map.get(value));
filterStep = STEPS.CONNECTIONARTICLE;
break;
case CONNECTIONARTICLE:
map = DataFilter.getConnectionArticlesByStreet(map.get(value));
filterStep = STEPS.INSTALLATION;
break;
case INSTALLATION:
map = DataFilter.getInstalliationsByConnectionArticle(map.get(value));
break;
}
modifyVisualRows(map);
}
}
Put this below code in your activity
#Override
public void onBackPressed()
{
if(checkBackPress)
{
checkBackPress =false;
sobItemsAdapter.setNextFilter(STEPS.SOB);
sobItemsAdapter.notifyDataSetChanged();
}
super.onBackPressed();
}
Create one boolean field public boolean checkBackPress=false; in your activity. Set this checkBackPress as true once item clicked on your item click event(checkBackPress=true) and set checkBackPress as false in backpressed

Having trouble restoring state on listview

I have an app that allows the user to select an option and a certain list is displayed in a listview. I'm having issues with getting it to save and restore state. I have a list_mode that gets set depending on which option the user selects. so far I have it saving the state of the adapter but restoring it is causing an issue ( I know it's saving because when I examine customAdapter.onRestoreInstanceState(savedInstanceState) in the onCreate it's showing the right items based on selection but I'm having a hard time restoring it to the list view. It will crash on restore. It crashes on getAllItems.clear and .addAll. I have even hard coded this to one of the lists but it didn't work either. When I comment that line out then it crashes in the main activity. I'm a noob when it comes to Java and Android and am still learning. I do not know how close or how far off I am. Can anyone provide insight on what I'm doing wrong and how I can get it to work? Thanks
List Adapter:
public class ListAdapter extends BaseAdapter {
private static final String KEY_ADAPTER_STATE = "ListAdapter.KEY_ADAPTER_STATE";
public enum ListMode {
IMAGES_AND_TEXT,
IMAGES_ONLY,
TEXT_ONLY
}
private ListMode mListMode = ListMode.IMAGES_AND_TEXT;
private ArrayList<Item> mItems;
private ArrayList<Item> mImages;
private ArrayList<Item> mTexts;
#Override
public int getCount() {
switch (mListMode) {
case IMAGES_AND_TEXT:
return mItems == null ? 0 : mItems.size();
case IMAGES_ONLY:
return mImages == null ? 0 : mImages.size();
case TEXT_ONLY:
return mTexts == null ? 0 : mTexts.size();
}
return 0;
}
#Override
public Item getItem(int position) {
switch (mListMode) {
case IMAGES_AND_TEXT:
return mItems == null ? null : mItems.get(position);
case IMAGES_ONLY:
return mImages == null ? null : mImages.get(position);
case TEXT_ONLY:
return mTexts == null ? null : mTexts.get(position);
}
return null;
}
public ArrayList getAllItems() {
switch (mListMode) {
case IMAGES_AND_TEXT:
return mItems;
case IMAGES_ONLY:
return mImages;
case TEXT_ONLY:
return mTexts;
}
return null;
}
#Override
public long getItemId(int position) {
return position; // not really used
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = null;
TextView tn = null;
ImageView img = null;
if (convertView == null) {
LayoutInflater vi;
vi = LayoutInflater.from(parent.getContext());
v = vi.inflate(R.layout.list, null);
} else {
v=convertView;
}
Item p = getItem(position);
tn = (TextView) v.findViewById(R.id.tvText);
img = (ImageView) v.findViewById(R.id.thumbnail);
if (p.getmType().equals("image")) {
img.setVisibility(View.VISIBLE);
Picasso.with(parent.getContext()).load(p.getmData()).error((R.drawable.placeholder_error)).placeholder(R.drawable.placeholder).resize(90,0).into(img);
tn.setText("ID: " + p.getmID()+"\nTYPE: " + p.getmType() +"\nDate: " + p.getmDate()+ "\nImage URL: " + p.getmData());
} else {
img.setVisibility(View.GONE);
tn.setText("ID: " + p.getmID()+"\nTYPE: " + p.getmType() +"\nDate: " + p.getmDate()+ "\nText Data: " + p.getmData());
}
return v;
}
public void setListMode(ListMode listMode) {
mListMode = listMode;
notifyDataSetChanged();
}
public void setItems(JSONArray jsonArray) throws JSONException {
mItems = new ArrayList<>();
mImages = new ArrayList<>();
mTexts = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
Item item = new Item((JSONObject) jsonArray.get(i));
mItems.add(item);
if (item.getmType().equals("image")) {
mImages.add(item);
}
if (item.getmType().equals("text")) {
mTexts.add(item);
}
}
notifyDataSetChanged();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList("list_items", getAllItems());
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey("list_items")) {
//ArrayList<Item> objects = savedInstanceState.getParcelableArrayList(KEY_ADAPTER_STATE);
//getAllItems().clear();
//getAllItems().addAll(objects);
//mImages.clear();
//mImages.addAll(objects);
}
}
}
Main Activity:
myListView = (ListView) findViewById(R.id.listViewID);
customAdapter = new ListAdapter();
if(savedInstanceState!=null) {
//When I put a breakpoint here I see it's getting the correct list
customAdapter.onRestoreInstanceState(savedInstanceState);
}
if (savedInstanceState != null && savedInstanceState.containsKey("list_items")) {
//When I remove the .clear and .addAll it then crashes on this line
myListView.onRestoreInstanceState(savedInstanceState.getParcelable("list_items"));
myListView.setAdapter(customAdapter);
}
else{
if (isNetworkAvailable()) {
getData theJsonData = new getData();
theJsonData.execute();
}
else{
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_SHORT).show();
tvNoInet.setVisibility(View.VISIBLE);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//Not sure what I should put here or if what I have is right
customAdapter.onSaveInstanceState(savedInstanceState);
}
//This is the code that sets the list_mode when the user selects an option
if (id == R.id.all) {
item.setChecked(true);
customAdapter.setListMode(ListAdapter.ListMode.IMAGES_AND_TEXT);
myListView.setSelectionAfterHeaderView();
return true;
}
if (id == R.id.images) {
item.setChecked(true);
customAdapter.setListMode(ListAdapter.ListMode.IMAGES_ONLY);
myListView.setSelectionAfterHeaderView();
return true;
}
if (id == R.id.text) {
item.setChecked(true);
customAdapter.setListMode(ListAdapter.ListMode.TEXT_ONLY);
myListView.setSelectionAfterHeaderView();
return true;
}
And my Item class:
public class Item implements Parcelable{
private String mID;
private String mType;
private String mDate;
private String mData;
public Item(String mID,String mType, String mDate, String mData) {
this.mType = mType;
this.mID = mID;
this.mDate = mDate;
this.mData = mData;
}
public Item(JSONObject jsonItem) throws JSONException {
String itemID=null;
String itemType=null;
String itemDate=null;
String itemData=null;
if (jsonItem.has("id")) {
itemID=jsonItem.getString("id");
}
if (jsonItem.has("type")) {
itemType=jsonItem.getString("type");
}
if (jsonItem.has("date")){
itemDate=jsonItem.getString("date");
}
if (jsonItem.has("data")){
itemData=jsonItem.getString("data");
}
this.mID=itemID;
this.mType=itemType;
this.mDate=itemDate;
this.mData=itemData;
}
protected Item(Parcel in) {
String[] data = new String[4];
in.readStringArray(data);
this.mID = data[0];
this.mType = data[1];
this.mDate = data[2];
this.mData = data[3];
}
public static final Creator<Item> CREATOR = new Creator<Item>() {
#Override
public Item createFromParcel(Parcel in) {
return new Item(in);
}
#Override
public Item[] newArray(int size) {
return new Item[size];
}
};
public String getmID() {
return mID;
}
public String getmType() {
return mType;
}
public String getmDate() {
return mDate;
}
public String getmData() {
return mData;
}
#Override
public String toString() {
return "{" +
"ID='" + mID + '\'' +
", Type='" + mType + '\'' +
", Date='" + mDate + '\'' +
", Data='" + mData + '\'' +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
String[] data = new String[4];
data[0] = mID;
data[1] = mType;
data[2] = mDate;
data[3] = mData;
dest.writeStringArray(data);
}
}
UPDATE: This is what the code looks like now. When I select a certain list and then rotate the screen it's working. It's staying on the currently selected list. Now the issue is when they select a new list after the device has been rotated the listview is completely blank
if(savedInstanceState!=null) {
customAdapter.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey(KEY_LIST_VIEW_STATE)) {
myListView.onRestoreInstanceState(savedInstanceState.getParcelable(KEY_LIST_VIEW_STATE));
myListView.setAdapter(customAdapter);
}
}
else{
if (isNetworkAvailable()) {
getData theJsonData = new getData();
theJsonData.execute();
tvNoInet.setVisibility(View.GONE);
btnRetry.setVisibility(View.GONE);
} else {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_SHORT).show();
tvNoInet.setVisibility(View.VISIBLE);
btnRetry.setVisibility(View.VISIBLE);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
customAdapter.onSaveInstanceState(savedInstanceState);
savedInstanceState.putParcelable(KEY_LIST_VIEW_STATE, myListView.onSaveInstanceState());
}
and my updated list adapter:
private ListMode mListMode = ListMode.IMAGES_AND_TEXT;
private ArrayList<Item> mItems= new ArrayList<>();
private ArrayList<Item> mImages= new ArrayList<>();
private ArrayList<Item> mTexts= new ArrayList<>();
public void onSaveInstanceState(Bundle savedInstanceState) {
//savedInstanceState.putParcelableArrayList("list_items", getAllItems());
savedInstanceState.putParcelableArrayList(KEY_ADAPTER_STATE, getAllItems());
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(KEY_ADAPTER_STATE)) {
ArrayList<Item> objects = savedInstanceState.getParcelableArrayList(KEY_ADAPTER_STATE);
getAllItems().clear();
getAllItems().addAll(objects);
//mImages.clear();
//mImages.addAll(objects);
}
}
And this is the code in the options menu that switches the list. If I haven't rotated the screen yet this works. When I rotate the screen and select a different list the listview is then blank. If I select "All" which should display All items then whatever list I had selected before if restored. So If I selected Images Only at first, rotate the screen everything is displayed right, if I rotate the screen back and select Text Only or Images Only again, the list is blank, if I select "All" then whatever list I picked the first time (in this case Images Only) is displayed
if (id == R.id.all) {
item.setChecked(true);
customAdapter.setListMode(ListAdapter.ListMode.IMAGES_AND_TEXT);
myListView.setSelectionAfterHeaderView();
return true;
}
if (id == R.id.images) {
item.setChecked(true);
customAdapter.setListMode(ListAdapter.ListMode.IMAGES_ONLY);
myListView.setSelectionAfterHeaderView();
return true;
}
if (id == R.id.text) {
item.setChecked(true);
customAdapter.setListMode(ListAdapter.ListMode.TEXT_ONLY);
myListView.setSelectionAfterHeaderView();
return true;
}
Well, since I got you into this mess.... :)
Something I do in situations like this is to pass in the saved instance state Bundle to the constructor for the adapter. Since you made your Item class Parcelable, everything else should be easy.
public ListAdapter(Bundle savedInstanceState) {
if (savedInstanceState != null) {
int ordinal = savedInstanceState.getInt("adapter_mode", 0);
mListMode = ListMode.values()[ordinal];
ArrayList<Item> items =
savedInstanceState.getParcelableArrayList(KEY_ADAPTER_STATE);
if (items != null) {
setItems(items);
}
}
}
public void onSaveInstanceState(Bundle outState) {
outState.putInt("adapter_mode", mListMode.ordinal());
outState.putParcelableArrayList(KEY_ADAPTER_STATE, mItems);
}
So with the saved instance state in the constructor, you don't need an explicit method to restore the adapter state.
public void setItems(JSONArray jsonArray) throws JSONException {
List<Item> items = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
items.add(new Item((JSONObject) jsonArray.get(i)));
}
setItems(items);
}
private void setItems(List<Item> items) {
for (Item item : items) {
mItems.add(item);
if (item.getmType().equals("image")) {
mImages.add(item);
}
if (item.getmType().equals("text")) {
mTexts.add(item);
}
}
notifyDataSetChanged();
}
Your app crashes if you call ListAdapter.getAllItems().clear() without calling ListAdapter.setItems() before
Cause: ListAdapter.getAllItems() may return null if mItems, mImages, mTexts are not initialized.
One workaround may be
public class ListAdapter extends ... {
...
private ArrayList<Item> mItems = new ArrayList<>();
private ArrayList<Item> mImages = new ArrayList<>();
private ArrayList<Item> mTexts = new ArrayList<>();
...
}

PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type

am building an open source project, here is its link
http://slidese.github.io/slidese/2013/11/25/update_listview_item.html
I've imported all library projects which it is using into eclipse. All are fine except PullToRefresh library. it is giving me the error "PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type" where fragment implements it
2nd error is at
mPullToRefreshAttacher.addRefreshableView(mListview, this);
it says "The method addRefreshableView(View, ViewDelegate) in the type PullToRefreshAttacher is not applicable for the arguments (ListView, ContentFragment)"
3rd error is at
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
It is asking me to remove override annotation. here is complete code of fragment.
public class ContentFragment extends Fragment implements PullToRefreshAttacher.OnRefreshListener {
private final String TAG = "ContentFragment";
public static final String CONTENT_MODE = "content_mode";
public static final int MODE_ADFREE = 0;
public static final int MODE_PREMIUM = 1;
private StartActivity mListener;
private PullToRefreshAttacher mPullToRefreshAttacher;
private UpdaterAsyncTask mUpdater;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
ListView mListview;
Button mPlayButton;
ContentAdapter mAdapter;
int mMode;
Map<String, UpdateHolder> mUpdates = new HashMap<String, UpdateHolder>();
public ContentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (StartActivity) activity;
Log.d(TAG, "Attached podcast list fragment");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must be the StartActivity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, null);
mListview = (ListView) view.findViewById(android.R.id.list);
mListview.setEmptyView(view.findViewById(R.id.empty_list_view));
mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_menu_content, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
SparseBooleanArray checked = mListview.getCheckedItemPositions();
Content[] params = new Content[checked.size()];
int index = 0;
int first = mListview.getFirstVisiblePosition();
int last = mListview.getLastVisiblePosition();
for (int i = 0; i < mListview.getCount(); i++) {
if (checked.get(i)) {
params[index++] = (Content)mListview.getItemAtPosition(i);
if (i >= first && i <= last) {
View view = mListview.getChildAt(i-first);
Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right);
animation.setDuration(200);
//animation.setFillAfter(true);
animation.setStartOffset(100 * (index) );
view.startAnimation(animation);
}
}
}
new AsyncTask<Content, Void, Void>() {
#Override
protected Void doInBackground(Content... params) {
for (Content content : params) {
File file = Utils.getFilepath(content.getFilename());
file.delete();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
mode.finish();
return true;
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
});
mListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Content content = mAdapter.getItem(position);
mListener.showContentDetails(content);
}
});
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
mPullToRefreshAttacher = ((StartActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mListview, this);
mMode = getArguments().getInt(CONTENT_MODE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
if (mUpdater != null)
mUpdater.stop();
}
#Override
public void onResume() {
super.onResume();
updateAdapter();
mUpdater = new UpdaterAsyncTask();
mUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
public void refresh() {
updateAdapter();
}
public void replaceCurrentlyPlayingContent() {
GlobalContext.INSTANCE.replaceCurrentlyPLayingContent(mAdapter.getObjects(), mListener.getCurrentTrack());
}
private void updateAdapter() {
Log.d(TAG, "updateAdapter");
//new FetchContentAsyncTask(mMode).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final String mp3 = mListener.getSavedStateMp3();
final boolean isPlaying = mListener.getSavedStateIsPlaying();
final boolean isPaused = mListener.getSavedStateIsPaused();
List<Content> listOfContent = GlobalContext.INSTANCE.getCachedContent(mMode, mp3, isPlaying, isPaused);
mAdapter = new ContentAdapter(getActivity(), R.layout.list_item_card, listOfContent);
mListview.setAdapter(mAdapter);
}
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
boolean isRunning = true;
public void stop() {
isRunning = false;
}
#Override
protected Void doInBackground(Void... params) {
while (isRunning) {
/*
Map<String, UpdateHolder> map = gatherMetadata();
publishProgress(map);
*/
updateCurrentAdapterContent();
publishProgress();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... params) {
super.onProgressUpdate();
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row
int start = mListview.getFirstVisiblePosition();
for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
View view = mListview.getChildAt(i-start);
if (((Content)mListview.getItemAtPosition(i)).dirty) {
Log.v(TAG, "Content is dirty");
mListview.getAdapter().getView(i, view, mListview);
}
}
}
}
}
private void updateCurrentAdapterContent() {
List<Content> listOfContent = mAdapter.getObjects();
Map<String, UpdateHolder> map = new HashMap<String, UpdateHolder>();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
try {
Cursor cursor = ContentDownloadManager.INSTANCE.query(q);
while (cursor.moveToNext()) {
//long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
int downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
float progress = (float)downloaded/(float)total;
UpdateHolder holder = new UpdateHolder();
holder.progress = progress;
holder.status = status;
map.put(uri, holder);
}
cursor.close();
final Content currentContent = mListener.getCurrentTrack();
final boolean isPlaying = mListener.isPlaying();
final boolean isPaused = mListener.isPaused();
for (Content content : listOfContent) {
// First update any download progress we might have for this specific content item
UpdateHolder holder = map.get(content.mp3);
if (holder != null) {
if (content.downloadProgress != holder.progress) {
content.downloadProgress = holder.progress;
content.dirty = true;
}
if (content.downloadStatus != holder.status) {
content.downloadStatus = holder.status;
content.dirty = true;
}
}
else {
if (content.downloadProgress != 0f) {
content.downloadProgress = 0f;
content.dirty = true;
}
if (content.downloadStatus != -1) {
content.downloadStatus = -1;
content.dirty = true;
}
}
// Update with elapsed (to be done)
// File exists?
File file = Utils.getFilepath(content.getFilename());
if (content.exists != file.exists()) {
content.exists = file.exists();
content.dirty = true;
}
// Is this the currently playing content
if (currentContent != null && content.mp3.equals(currentContent.mp3)) {
if (content.isPlaying != isPlaying) {
content.isPlaying = isPlaying;
content.dirty = true;
}
if (content.isPaused != isPaused) {
content.isPaused = isPaused;
content.dirty = true;
}
}
else {
if (content.isPlaying != false) {
content.isPlaying = false;
content.dirty = true;
}
if (content.isPaused != false) {
content.isPaused = false;
content.dirty = true;
}
}
if (content.dirty) {
DatabaseManager.getInstance().createOrUpdateContent(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class UpdateHolder {
public String mp3;
public int status;
public boolean played;
public float progress;
public boolean exists = false;
public boolean isPlaying = false;
public boolean isPaused = false;
//public int elapsed;
//public int duration;
}
}
I couldn't find the issue in it. I'm stuck here for last 40 hours. Please help. Thank you!
Maybe you are using old version of the library. I found that PullToRefreshAttacher doesn't contain OnRefreshListener. (https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/library/src/main/java/uk/co/senab/actionbarpulltorefresh/library/PullToRefreshAttacher.java)
Try to import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; and use it instead of PullToRefreshAttacher.OnRefreshListener.

Calling notifyDataSetChanged() outside of the Fragment it is in

I'm writing an application that allows for the sharing of recipes. When one receives a recipe, they can save it to their phone and it will appear as a fragment of a list.
Problem is, when I save it, I get an IllegalStateException for not calling NotifyDataSetChanged(), which I can't find a way to do in the Activity that I am in. If anyone knows how I can find a way to get access to the adapter that calls this, that would be greatly appreciated. Making it static didn't seem to be an option.
public class SmsViewActivity extends Activity {
private static final String TAG = "SmsViewActivity";
private static final String SMS_FOOD = "food_recieved";
private FoodJSONSerializer mSerializer;
public Button mSaveButton, mDismissButton;
public int mNotificationId;
public String message;
private EditText mTitleField;
private EditText mServingsField;
private EditText mDirectionsField;
Food mFood;
private String msg;
private Activity mActivity;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.i(TAG, "OnCreate");
mActivity = this;
setContentView(R.layout.sms_view);
mSaveButton = (Button) findViewById(R.id.save_button_sms);
mDismissButton = (Button) findViewById(R.id.dismiss_button_sms);
// ------------------------------------------------------------
// Get extras and display information in view
//String sender = getIntent().getStringExtra("sender");
this.msg = getIntent().getStringExtra("message");
try {
JSONObject jsonRecipe = new JSONObject(this.msg);
this.mFood = new Food(jsonRecipe);
Log.i(TAG, "Food = " + mFood);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// -----------------------------------------------------------------------
mNotificationId = getIntent().getIntExtra("notificationid", 0);
if (mNotificationId == 0) {
Log.e(TAG, "Could not retrieve notification ID.");
Toast.makeText(this, "A fatal error has occurred in SMS viewer.",
Toast.LENGTH_LONG).show();
finish();
}
// Cancel the notification
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationMgr = (NotificationManager) getSystemService(ns);
notificationMgr.cancel(mNotificationId);
// --------------------------------------------------
this.mTitleField = (EditText) findViewById(R.id.food_title_sms);
this.mTitleField.setText(mFood.getTitle());
this.mServingsField = (EditText) findViewById(R.id.food_servings_sms);
this.mServingsField.setText(Integer.toString(mFood.getServings()));
this.mDirectionsField = (EditText) findViewById(R.id.directions_text_sms);
this.mDirectionsField.setText(mFood.getDirections());
// --------------------------------------------------
// Listener for Save button click
this.mSaveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FoodStorage.get(mActivity).addFood(mFood);
//NEED TO CALL notifyDataSetChanged(); HERE
finish();
}
});
// Listener for Dismiss button click
this.mDismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
backToList();
finish();
}
});
}
public void backToList() {
Intent i = new Intent(this, FoodListActivity.class);
startActivity(i);
}
}
Here is the Fragment where the adapter lives and where every other instance of adding or deleting occurs.
public class FoodListFragment extends ListFragment{
private ArrayList<Food> mFood;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.food_title);
mFood = FoodStorage.get(getActivity()).getFood();
FoodAdapter adapter = new FoodAdapter(mFood);
setListAdapter(adapter);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Use floating context menus on Froyo and Gingerbread
registerForContextMenu(listView);
} else {
// Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// Required, but not used in this implementation
}
// ActionMode.Callback methods
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.food_list_item_context, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
// Required, but not used in this implementation
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_food:
FoodAdapter adapter = (FoodAdapter)getListAdapter();
FoodStorage foodStorage = FoodStorage.get(getActivity());
for (int i = adapter.getCount() - 1; i >= 0; i--) {
if (getListView().isItemChecked(i)) {
foodStorage.deleteFood(adapter.getItem(i));
}
}
mode.finish();
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
// Required, but not used in this implementation
}
});
}
return v;
}
public void onListItemClick(ListView l, View v, int position, long id) {
// get the Food from the adapter
Food c = ((FoodAdapter)getListAdapter()).getItem(position);
// start an instance of CrimePagerActivity
Intent i = new Intent(getActivity(), FoodPagerActivity.class);
i.putExtra(FoodFragment.EXTRA_FOOD_ID, c.getId());
startActivityForResult(i, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
((FoodAdapter)getListAdapter()).notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_food_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_food:
Food food = new Food();
FoodStorage.get(getActivity()).addFood(food);
Intent i = new Intent(getActivity(), FoodPagerActivity.class);
i.putExtra(FoodFragment.EXTRA_FOOD_ID, food.getId());
startActivityForResult(i, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.food_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
FoodAdapter adapter = (FoodAdapter)getListAdapter();
Food food = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_food:
FoodStorage.get(getActivity()).deleteFood(food);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
private class FoodAdapter extends ArrayAdapter<Food> {
public FoodAdapter(ArrayList<Food> food) {
super(getActivity(), android.R.layout.simple_list_item_1, food);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// if we weren't given a view, inflate one
if (null == convertView) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_food, null);
}
// configure the view for this recipe
Food c = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.food_list_item_titleTextView);
titleTextView.setText(c.getTitle());
TextView servingsTextView =
(TextView)convertView.findViewById(R.id.food_list_item_servingsTextView);
servingsTextView.setText("Makes " + c.getServings() + " servings");
TextView ingredientsTextView = (TextView) convertView
.findViewById(R.id.food_list_item_ingredientsTextView);
JSONArray j = c.jIngredients;
String display = "";
for (int i = 0; i < j.length(); i++) {
try {
display = display + j.get(i) + "\n";
} catch (JSONException e) {
// Do nothing.
e.printStackTrace();
}
}
ingredientsTextView.setText("Ingredients:\n" + display);
TextView directionsTextView =
(TextView)convertView.findViewById(R.id.food_list_item_directionsTextView);
directionsTextView.setText("Directions:\n " + c.getDirections());
return convertView;
}
}
}
You may use Eventbus from greenrobot. It provides you with a way to post events anywhere to any subscriber who can receive the event and call any method.
In the onCreate method of your fragment, call this EventBus.getDefault().register(this); to register your fragment as a subscriber.
Create a new method in your fragment: public void onEvent(AnyEventType event) {}. When an event is posted on the event bus, this method will be called. you may call adapter.notifyDatasetChanged() in the onEvent method. AnyEventType can be just any class (can be a POJO). You may use this class to pass any info to your fragment.
In your activity, you can call EventBus.getDefault().post(event); to notify your fragment. The onEvent method in your fragment will be executed when the event is posted.
Refer to the EventBus readme for more info.

Categories

Resources