I am stuck because I don't know how to change populating listView to populate spinner.
The code below should work when in layout spinner is changed to listview, but I need spinner.
Can anyone explain to me how to do it?
In the Java file I'm using DefaultHttpClient method.
MainActivity:
public class MainActivity extends ActionBarActivity {
private Spinner spinner;
private JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.spinner=(Spinner) this.findViewById(R.id.spinner);
new GetStat().execute(new Polaczenie());
}
public void setSpinner(JSONArray jsonArray){
this.spinner.setAdapter(new GetAllTeamListViewAdapter(jsonArray,this));
//this.GetStat.setAdapter(new GetAllTeamListViewAdapter(jsonArray,this));
}
public class GetStat extends AsyncTask<Polaczenie,Long,JSONArray>
{
#Override
protected JSONArray doInBackground(Polaczenie... params)
{
return params[0].GetStat();
}
#Override
public void onPostExecute(JSONArray jsonArray)
{
setSpinner(jsonArray);
}
}
}
GetAllTeamListViewAdapter activity:
public class GetAllTeamListViewAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
private static LayoutInflater inflater = null;
public GetAllTeamListViewAdapter(JSONArray jsonArray, Activity a)
{
this.dataArray=jsonArray;
this.activity=a;
inflater=(LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.dataArray.length();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ListTeam team;
if(convertView == null)
{
convertView= inflater.inflate(R.layout.get_all_team_list_view, null);
team = new ListTeam();
team.Name=(TextView) convertView.findViewById(R.id.team_full_name);
}
else
{
team =(ListTeam) convertView.getTag();
}
try
{
JSONObject jsonObject=this.dataArray.getJSONObject(position);
team.Name.setText(jsonObject.getString("name"));
}
catch(JSONException e)
{
e.printStackTrace();
}
return convertView;
}
private class ListTeam
{
private TextView Name;
}
}
Related
I have an Fragment with recycleview where I populate it with json items from internet.
It load fine and Next step I want to is open new Activity when any row is clicked. It works in activity, thus I modified the same code for fragment but for fragment it throws exception in line
mExampleAdapter.setOnItemClickListener(getActivity());
with errror setOnItemClickListener of refrence adatper cannot be applied to Fragment activty and thus when I change line to
(ExampleAdapter.OnItemClickListener)
and when i build and run . Then app crashes with error that Mainactivity which holds framgnet cannot be cast in to .ExampleAdapter$OnItemClickListener
Here is my whole Fragment class
public class Mynotes extends Fragment implements ExampleAdapter.OnItemClickListener{
public static final String YTD_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
String url="https://api.myjson.com/bins/16mecx";
public Mynotes() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_jsonfeed, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new MyDividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL, 36));
mExampleList = new ArrayList<>();
mExampleAdapter = new ExampleAdapter(getActivity(), mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener((ExampleAdapter.OnItemClickListener) getActivity());
parseJSON();
return view;
}
private void parseJSON() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
mExampleList.add(new ExampleItem(videoTitle, link));
mExampleAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(getActivity(), NewActiviyt.class);
ExampleItem clickedItem = mExampleList.get(position);
intent.putExtra(YTD_LINK, clickedItem.getmLink());
startActivity(intent);
}
#Override
public void onRefresh() {
}
}
and my Adapter Class is
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> exampleList) {
mContext = context;
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
// int likeCount = currentItem.getLikeCount();
// String imageUrl = currentItem.getImageUrl();
holder.mTextViewCreator.setText(title);
// holder.mTextViewLikes.setText("Likes: " + likeCount);
// Glide.with(mContext).load(imageUrl).apply(RequestOptions.circleCropTransform()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTextViewCreator;
// public TextView mTextViewLikes;
// public ImageView mImageView;
public ExampleViewHolder(View itemView) {
super(itemView);
// mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
// mImageView = itemView.findViewById(R.id.image_view);
mTextViewCreator = itemView.findViewById(R.id.text_title);
}
#Override
public void onClick(View view) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}
}
Thanks in advance.
replace getActivity with getContext when you work in fragment,
You can read more here
What is different between getContext and getActivity from Fragment in support library?
Your activity should implement ExampleAdapter.OnItemClickListener
I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.
I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?
The Adapter class:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
private Context context;
ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list){
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());
//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String foods = list.get(position).getName();
String carbo = list.get(position).getCarbohydrates();
String protein = list.get(position).getProtein();
String fats = list.get(position).getFats();
Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView foods, carbo, fats, protein;
public ViewHolder(View itemView) {
super(itemView);
carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);
}
}
}
The Fragment where the data comes from:
public class TrackingFragment extends Fragment {
DatabaseReference databaseReference;
ArrayList<FoodActivity> list;
RecyclerView recyclerView;
SearchView searchView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tracking, container, false);
databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
recyclerView = view.findViewById(R.id.rv);
searchView = view.findViewById(R.id.searchFood);
return view;
}
#Override
public void onStart() {
super.onStart();
if(databaseReference != null){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
list.add(ds.getValue(FoodActivity.class));
}
FoodAdapter adapter = new FoodAdapter(list);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if(searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str){
ArrayList<FoodActivity> searchList = new ArrayList<>();
for(FoodActivity object : list){
if(object.getName().toLowerCase().contains(str.toLowerCase())){
searchList.add(object);
}
}
FoodAdapter foodAdapter = new FoodAdapter(searchList);
recyclerView.setAdapter(foodAdapter);
}
}
And the class where it needs to go:
public class FoodFragment extends Fragment {
ImageButton addFood;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container, false);
addFood = view.findViewById(R.id.addFood);
addFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new TrackingFragment());
fr.addToBackStack(null).commit();
}
});
return view;
}
}
The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:
in activity:
String foods;
public String getFoods() {
return foods;
}
public void setFoods(String foods) {
this.foods = foods;
}
in adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((YourActivity)getActivity()).setFoods("Any value");
}
});
in destination fragment:
String foods = ((YourActivity)getActivity()).getFoods();
Add an interface to your adapter as follow
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
interface OnClickListener {
void onClick(FoodActivity clickedItem);
}
private OnClickListener mCallback;
private ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list){
this.list = list;
}
public void setOnClickListener(OnClickListener callback) {
mCallback = callback;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());
//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallback != null)
mCallback.onClick(list.get(position));
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView foods, carbo, fats, protein;
public ViewHolder(View itemView) {
super(itemView);
carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);
}
}
}
Android sometimes is a little complicated, when it involves the full stack:
01 RecyclerView Adapter
/** 01. Some Adapter */
public class SomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private WeakReference<Context> mContext;
/** Constructor */
public SomeAdapter(#NonNull Context context) {
this.mContext = new WeakReference<>(context);
}
#NonNull
protected Context getContext() {
return this.mContext.get();
}
/** Call to Activity from within the adapter. */
private void someMethod() {
SomeActivity activity = (SomeActivity) getContext();
synchronized(activity) {activity.showLoginDialog();}
}
}
02 AppCompatActivity
/** 02. Some Activity */
public class SomeActivity extends AppCompatActivity {
#Nullable
private BaseFragment currentFragment = null;
/** Constructor */
public SomeActivity() {}
public void setCurrentFragment(Fragment fragment) {
this.currentFragment = fragment;
}
/** Call to the current Fragment. */
public void someMethod() {
if (currentFragment != null) {
currentFragment.someMethod();
}
}
}
03 Fragment
/** Some Fragment */
public class SomeFragment extends Fragment {
/** Constructor */
public SomeFragment() {}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
((BaseActivity) context).setCurrentFragment(this);
}
#Override
public void onDetach() {
super.onDetach();
((BaseActivity) getActivity()).setCurrentFragment(this);
}
}
To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.
To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938
I write this code for main activity of recycleview with it's adapter and fetching data on it from json data so my question is about the onPostExecute()
I've used before a string so I used .append with it and everything works, now I used an arraylist for the first time so whats the problem with my function
Main Activity:
public class MainActivity extends AppCompatActivity {
private static final ArrayList<MovieItem> NUM_MOVIES = ;
RecyclerViewAdapter mAdapter;
RecyclerView mMoviesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMoviesList = (RecyclerView) findViewById(R.id.rv_movies);
GridLayoutManager LayoutManager = new GridLayoutManager(this, 2);
mMoviesList.setLayoutManager(LayoutManager);
mMoviesList.setHasFixedSize(true);
mAdapter = new RecyclerViewAdapter(NUM_MOVIES);
mMoviesList.setAdapter(mAdapter);
loadMoviesData();
}
private void loadMoviesData() {
new FetchMoviesTask().execute();
}
public class FetchMoviesTask extends AsyncTask<String, Void, ArrayList<MovieItem>> {
#Override
protected ArrayList<MovieItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String movie = params[0];
URL moviesRequestUrl = NetworkUtils.buildUrl(movie);
try {
String jsonMovieResponse = NetworkUtils.getResponseFromHttpUrl(moviesRequestUrl);
ArrayList<MovieItem> simpleJsonMovieData = OpenMovieJsonUtils.getSimpleMovieStringsFromJson(MainActivity.this, jsonMovieResponse);
return simpleJsonMovieData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(ArrayList<MovieItem> movieData) {
if (movieData != null) {
for (MovieItem movie : movieData) {
mMoviesList.append((movie) + "\n\n\n");
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sort, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.most_popular) {
loadMoviesData();
return true;
}
if (id == R.id.top_rated) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
ArrayList<MovieItem> mMoviesItems;
private Context context;
public RecyclerViewAdapter(ArrayList<MovieItem> MoviesItems) {
mMoviesItems = MoviesItems;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
context = viewGroup.getContext();
int layoutIdForListItem = R.layout.movie_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.MoviePopularity.setText(String.valueOf(mMoviesItems.get(position).getPopularity()));
Picasso.with(this.context).load(mMoviesItems.get(position).getPhoto()).into(holder.MoviePoster);
holder.MovieName.setText(mMoviesItems.get(position).getName());
}
#Override
public int getItemCount() {
return mMoviesItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView MoviePopularity;
ImageView MoviePoster;
TextView MovieName;
public RecyclerViewHolder(View itemView) {
super(itemView);
MoviePopularity = (TextView)itemView.findViewById(R.id.movie_popularity);
MoviePoster = (ImageView)itemView.findViewById(R.id.iv_item_movie);
MovieName = (TextView)itemView.findViewById(R.id.movie_name);
}
}
}
also about the private static final ArrayList<MovieItem> NUM_MOVIES = ;
when I use int I just used any number but now with arraylist what should I do
This is because you're trying to use a method that did not exist for the class.
In your source code, you define mMoviesList as RecyclerView:
RecyclerView mMoviesList;
Then you try the following:
protected void onPostExecute(ArrayList<MovieItem> movieData) {
if (movieData != null) {
for (MovieItem movie : movieData) {
mMoviesList.append((movie) + "\n\n\n");
}
}
}
There is no append method in RecyclerView
I have been trying to fetch JSON data using volley library. Everything is going fine but the data is not getting displayed on CustomListAdapter. I think the problem is with Custom Adapter. The Url for JSON is okay and the data is successfully fetched. The code is below.
CustomListAdapter.java code
public class CustomListAdapter extends ArrayAdapter<food> {
private Activity act;
private ArrayList<food>data;
private int layoutResource;
public CustomListAdapter(#NonNull Activity activity, int resource, ArrayList<food>items) {
super(activity, resource, items);
act=activity;
data=items;
layoutResource=resource;
}
#Override
public int getCount() {
return data.size();
}
#Nullable
#Override
public food getItem(int position) {
return super.getItem(position);
}
#Override
public int getPosition(#Nullable food item) {
return super.getPosition(item);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row=convertView;
ViewHolder holder=null;
if(row==null || (row.getTag()==null)){
LayoutInflater inflater=LayoutInflater.from(act);
row=inflater.inflate(layoutResource,parent,false);
holder=new ViewHolder();
//get references to views
holder.ItemName=(TextView)row.findViewById(R.id.listName);
row.setTag(holder);
}else{
holder=(ViewHolder)row.getTag();
}
holder.foodItem=data.get(position);
//we can now display data
holder.ItemName.setText(holder.foodItem.getItemName());
final ViewHolder finalHolder = holder;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(act, FoodDetails.class);
Bundle mbundle=new Bundle();
mbundle.putSerializable("bundleOnj", finalHolder.foodItem);
i.putExtras(mbundle);
act.startActivity(i);
}
});
return row;
}
public class ViewHolder{
TextView ItemName;
food foodItem;
}
}
ListActivity.java code; In this code when I setText for getting JSON object, it is running properly.
public class ListActivity extends AppCompatActivity {
private CustomListAdapter adapter;
private ListView listview;
private ArrayList<food>foodItems=new ArrayList<>();
private String LEFT_URL="https://api.nutritionix.com/v1_1/search/";
private String RIGHT_URL="?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=MY_IDd&appKey=MY_API";
private TextView selectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listview=(ListView)findViewById(R.id.listView);
selectedItem=(TextView)findViewById(R.id.selectedItem);
adapter=new CustomListAdapter(ListActivity.this,R.layout.row,foodItems);
listview.setAdapter(adapter);
getFoodDetails("Butter");
}
private void getFoodDetails(String item){
//clear data first
foodItems.clear();
String FINAL_URL=LEFT_URL+item+RIGHT_URL;
JsonObjectRequest foodObjectRequest=new JsonObjectRequest(Request.Method.GET,
FINAL_URL, (JSONObject) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray foodArray= response.getJSONArray("hits");
for(int i=0;i<foodArray.length();i++){
JSONObject JsonObject=foodArray.getJSONObject(i);
JSONObject fieldsObject=JsonObject.getJSONObject("fields");
//get the Json Details
String itemName=fieldsObject.getString("item_name");
//selectedItem.setText("item Selected: "+itemName);
String brand_name=fieldsObject.getString("brand_name");
selectedItem.setText("item Selected: "+brand_name);
String servingSizeUnit=fieldsObject.getString("nf_serving_size_unit");
double calories=fieldsObject.getDouble("nf_calories");
//selectedItem.setText("item Selected: "+calories);
double fat=fieldsObject.getDouble("nf_total_fat");
//putting data to set functions
food foodInfo=new food();
foodInfo.setBrandName(brand_name);
foodInfo.setItemName(itemName);
foodInfo.setCalories(calories);
foodInfo.setFat(fat);
foodInfo.setServingSizeunit(servingSizeUnit);
foodItems.add(foodInfo);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(foodObjectRequest);
}
}
call adapter.notifyDataSetChanged() after adding object to your list
You are setting adapter before fetching data.
set adapter after data is retrieved.
in onCreate remove this line
listview.setAdapter(adapter);
in getFoodDetails after for loop add this line
listview.setAdapter(adapter);
I'm trying to make a simple application in Android that displays all the beacons that are found in a ListView by using the AltBeacon library. The problem that I'm having is that no beacon is shown, I keep on getting a blank screen without any beacons.
Any ideas what could be wrong with my code?
This is the code I have:
MainActivity.java:
public class MainActivity extends Activity implements BeaconConsumer, RangeNotifier {
public BeaconManager mBeaconManager;
public List<Beacon> beaconlijst;
ListView lijst;
public BeaconListAdapter listAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconlijst = new ArrayList<>();
lijst = (ListView)findViewById(R.id.listViews);
listAdapter = new BeaconListAdapter(this, beaconlijst);
lijst.setAdapter(listAdapter);
mBeaconManager = BeaconManager.getInstanceForApplication(this.getApplicationContext());
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19"));
mBeaconManager.bind(this);
}
#Override
public void onBeaconServiceConnect() {
Region region = new Region("all-beacons-region", null, null, null);
try {
mBeaconManager.startRangingBeaconsInRegion(region);
}catch(RemoteException e) {
e.printStackTrace();
}
mBeaconManager.setRangeNotifier(this);
}
#Override
public void didRangeBeaconsInRegion(final Collection<Beacon> beacons, Region region) {
runOnUiThread(new Runnable() {
#Override
public void run() {
beaconlijst = new ArrayList<>(beacons);
listAdapter.notifyDataSetChanged();
}
});
}
public void onPause() {
super.onPause();
mBeaconManager.unbind(this);
}
}
BeaconListAdapter.java:
public class BeaconListAdapter extends BaseAdapter {
private Activity activity;
private List<Beacon> beacons;
private static LayoutInflater inflater = null;
public BeaconListAdapter(Activity _activity, List<Beacon> _beacons) {
this.activity = _activity;
this.beacons = _beacons;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return beacons.size();
}
#Override
public Object getItem(int position) {
return beacons.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView == null ) {
view = inflater.inflate(R.layout.tupple_monitoring, null);
}
TextView uuid = (TextView)view.findViewById(R.id.BEACON_uuid);
TextView rssi = (TextView)view.findViewById(R.id.BEACON_rssi);
TextView txpower = (TextView)view.findViewById(R.id.BEACON_txpower);
Beacon beacon = beacons.get(position);
if(beacon != null) {
uuid.setText(beacon.getId2().toString());
rssi.setText(beacon.getRssi());
txpower.setText(beacon.getTxPower());
}
return view;
}
}
Any help would greatly be appreciated.