I am using spinner in my app I am populating spinner with the data fetching from the server.I am using Retrofit2 as a networking library. There are 2 values I am fetching from the server one is state name and other is state id.
In spinner I am showing state name, but on select state it should select corresponding state name id that I have fetched from the server. In spinner state name is showing successfully but I want to gets corresponding state name id that I have in POJO class and not item position.
Below is my code:
Server response is given below:
{
"data": [
{
"id": "5",
"name": "Bihar"
},
{
"id": "7",
"name": "Chhattisgarh"
},
{
"id": "10",
"name": "Delhi"
}
],
"status": true,
"code": 200
}
States.java
public class States {
#SerializedName("data")
#Expose
private List<AllStates> data = null;
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("code")
#Expose
private int code;
public States(){
}
public List<AllStates> getData() {
return data;
}
public void setData(List<AllStates> data) {
this.data = data;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
AllStates.java
public class AllStates {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
public AllStates(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CalenderFragment.java
public class CalendarFragment extends Fragment {
Spinner spinnerState;
List<AllStates> stateList = new ArrayList<>();
ArrayList<String> stateSpinnerList = new ArrayList<>();
public CalendarFragment() {
// 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_calendar, container, false);
spinnerState = view.findViewById(R.id.spinnerState);
spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
apiService.allStates().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<States>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(States states) {
stateList = states.getData();
stateSpinnerList.add("Select state");
for(int i =0;i<stateList.size();i++){
stateSpinnerList.add(stateList.get(i).getName());
}
ArrayAdapter<String> stateAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,stateSpinnerList);
spinnerState.setAdapter(stateAdapter);
}
#Override
public void onError(Throwable e) {
TastyToast.makeText(getActivity(),e.getMessage(),TastyToast.LENGTH_SHORT,
TastyToast.ERROR).show();
}
#Override
public void onComplete() {
}
});
return view;
}
}
How can I get the desired result?
So what I understand is you are selecting state from Spinner and getting name of state but you want to get stateId.
one possible solution, I can think of is to use HashMap<StateName, StateId> map.
when you receive state name from spinner just call map.get(name) and you will get state Id.
Edit:
you can implement it like this
HashMap<String, Integer> map = new HashMap<>();
for(state in list){
map.put(state.name, state.id);
}
spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name = parent.getItemAtPosition(position).toString();
int id = map.get(name);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If you don't want to use a custom adapter then fetch selected spinner position and using that position fetch your State model
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// int position = spinnerState.getSelectedItemPosition();
if(position >= 1){
AllStates allStates = stateList.get(position - 1)
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Now you can access id from allStates model
Related
I've been working with Java for a few months but new to Android. This is a recipe holder app.
I have an ArrayAdapter set on a ListView and am needing to select an item in the ListView and delete it with a Button (I've already successfully set up adding of Strings to the Listview). I'm using an ArrayList for the list used to store Ingredient objects rather than a regular array. I'm attempting to use AdapterView.onSelectedItemListener to identify a user selection in the ListView and then use the Button to delete the selected item. For the Button, I'm implementing Button.onClickItemListener.
To get the list items into the ListView I'm using a dialog. I'm using an interface to send the string input from the dialog to the ListView in RecipeFragmentNew. I haven't been having issues getting the Strings from the dialog to RecipeFragmentNew, so I haven't included any of that code.
Problem: Button is deleting list items but it is deleting the first item in the list, not the item that is being selected.
Recipe.java
public class Recipe {
private UUID mID;
private String mName;
private Date mDate;
private boolean mIsFavorite;
private final ArrayList<Ingredient> ingredients;
public final ArrayList<Instruction> instructions;
public Recipe() {
mID = UUID.randomUUID();
mDate = new Date();
this.ingredients = new ArrayList<>();
this.instructions = new ArrayList<>();
}
public UUID getID() {
return mID;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public boolean isFavorite() {
return mIsFavorite;
}
public void setFavorite(boolean favorite) {
mIsFavorite = favorite;
}
public ArrayList<Ingredient> getIngredients() {
return ingredients;
}
public ArrayList<Instruction> getInstructions() {
return instructions;
}
}
Ingredient.java
public class Ingredient {
private String name;
private String amount;
public Ingredient(String name, String amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public String getAmount() {
return amount;
}
#Override
public String toString() {
return this.name + " " + this.amount;
}
}
The arrayList is retreived from Recipe class using mRecipe.getIngredients().
The ListView is mIngredientWindow.
RecipeFragmentNew.java
public class RecipeFragmentNew extends Fragment implements IngredientListDialog.OnInputSelected {
public static final String TAG = "RecipeFragmentNew";
public static final String DIALOG_INGREDIENTS = "DialogIngredients";
private Recipe mRecipe;
private EditText mNameField;
private Button mIngredientAdd;
private Button mIngredientDelete;
private ListView mIngredientWindow;
private int listViewPosition;
private ArrayAdapter<Ingredient> listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID recipeId = (UUID) getArguments().getSerializable(ARG_RECIPE_ID);
mRecipe = RecipeQueue.get(getActivity()).getRecipe(recipeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lists_detail_view, container, false);
mIngredientDelete = v.findViewById(R.id.delete_ingredient_button);
mIngredientDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < mRecipe.getIngredients().size(); i++) {
if (i == listViewPosition) {
mRecipe.getIngredients().remove(i);
}
listAdapter.notifyDataSetChanged();
}
}
});
listAdapter = new ArrayAdapter<Ingredient>(
getActivity(),
android.R.layout.simple_list_item_1,
mRecipe.getIngredients()
);
mIngredientWindow = v.findViewById(R.id.ingredients_window);
mIngredientWindow.setAdapter(listAdapter);
AdapterView.OnItemSelectedListener itemSelectedListener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
listViewPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
Button is deleting list items but it is deleting the first item in
the list, not the item that is being selected.
The variable listViewPosition is always 0 because the setOnItemSelectedListener is not called. please check this answer
So you can replace this method with setOnItemClicklistener like the below code:
mIngredientWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//mIngredientWindow.setSelection(position);
listViewPosition = position;
}
});
Simple
the listViewPosition variable always equals 0
Here's Why, You have defined an object from AdapterView.OnItemSelectedListener but you never attache it to the listview
all you need to do is add
mIngredientWindow.setOnItemSelectedListener (itemSelectedListener );
I'm referring this tutorial ==> https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/ in my project I have bottom navigation...I am trying to add favourites in the first tab and displaying favourites in the second tab in the bottom navigation bar. I'm using Room library.
When activity loads favourites are all blank at first, but when I first row as favourite and go-to favourite tab it displays properly but when I came back to the first tab it fills all the favourites icon automatically (which I have not done I had only done the first row)
Really need help. Thanks in advance.
Dao:
#Dao
public interface FavoriteDao {
#Insert
public void addData(FavoriteList favoriteList);
#Query("select * from favoritelist")
public List<FavoriteList> getFavoriteData();
#Query("SELECT EXISTS (SELECT 1 FROM favoritelist WHERE id=:id)")
public int isFavorite(int id);
#Delete
public void delete(FavoriteList favoriteList);
}
Database:
#Database(entities={FavoriteList.class},version = 1)
public abstract class FavoriteDatabase extends RoomDatabase {
public abstract FavoriteDao favoriteDao();
}
FavoriteList:
#Entity(tableName="favoritelist")
public class FavoriteList {
#PrimaryKey
private int id;
#ColumnInfo(name = "source")
private String source;
#ColumnInfo(name = "author")
private String author;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "description")
private String description;
#ColumnInfo(name = "url")
private String url;
#ColumnInfo(name = "urlToImage")
private String urlToImage;
#ColumnInfo(name = "publishedAt")
private String publishedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
News fragment:
public class news extends Fragment {
ImageView favbtn;
RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
EditText etQuery;
Button btnSearch;
Adapter adapter;
List<Articles> articles = new ArrayList<>();
public static FavoriteDatabase favoriteDatabase;
public news() {
// 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_news, container, false);
swipeRefreshLayout = view.findViewById(R.id.swiprefresh);
etQuery = view.findViewById(R.id.etQuery);
btnSearch = view.findViewById(R.id.btnSearch);
favoriteDatabase= Room.databaseBuilder(getActivity(),FavoriteDatabase.class,"myfavdb").
allowMainThreadQueries().build();
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final String country = getCountry();
retrieveJson("", country, API_Key);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etQuery.getText().toString().equals("")) {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(etQuery.getText().toString(), country, API_Key);
}
});
retrieveJson(etQuery.getText().toString(), country, API_Key);
} else {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson("", country, API_Key);
}
});
retrieveJson("", country, API_Key);
}
}
});
return view;
}
private void showChangeLanguageDialog() {
}
public void retrieveJson(String query, String country, String apiKey) {
swipeRefreshLayout.setRefreshing(true);
Call<Headlines> call;
if (!etQuery.getText().toString().equals("")) {
call = ApiClient.getInstance().getApi().getSpecifiedData(query, apiKey);
} else {
call = ApiClient.getInstance().getApi().getHeadLines(country, apiKey);
}
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null) {
swipeRefreshLayout.setRefreshing(false);
// articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(), articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final Adapter.ViewHolder holder, final int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
String url = a.getUrl();
holder.tvTitle.setText(a.getTitle());
Picasso.get().load(imageUrl).into(holder.imageView);
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(dateTime(a.getPublishedAt()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailedActivity.class);
intent.putExtra("title",a.getTitle());
intent.putExtra("source",a.getSource().getName());
intent.putExtra("time",dateTime(a.getPublishedAt()));
intent.putExtra("desc",a.getDescription());
intent.putExtra("imageUrl",a.getUrlToImage());
intent.putExtra("url",a.getUrl());
context.startActivity(intent);
}
});
if (news.favoriteDatabase.favoriteDao().isFavorite(articles.get(position).getId())==1)
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
else
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FavoriteList favoriteList = new FavoriteList();
int id = articles.get(position).getId();
String source = articles.get(position).getSource().getName();
String author = articles.get(position).getAuthor();
String publishedAt = articles.get(position).getPublishedAt();
String description = articles.get(position).getDescription();
String title = articles.get(position).getTitle();
String url = articles.get(position).getUrl();
String urlToImage = articles.get(position).getUrlToImage();
favoriteList.setId(id);
favoriteList.setAuthor(author);
favoriteList.setDescription(description);
favoriteList.setSource(source);
favoriteList.setPublishedAt(publishedAt);
favoriteList.setTitle(title);
favoriteList.setUrl(url);
favoriteList.setUrlToImage(urlToImage);
favoriteList.setPublishedAt(dateTime(articles.get(position).getPublishedAt()));
if (news.favoriteDatabase.favoriteDao().isFavorite(id)!=1){
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
news.favoriteDatabase.favoriteDao().addData(favoriteList);
}else {
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
news.favoriteDatabase.favoriteDao().delete(favoriteList);
}
}
});
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate;
ImageView imageView;
ImageButton bookmark;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvId);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
bookmark = itemView.findViewById(R.id.favrr);
}
}
Steps to debug:
Add 2-3 items as Favs.
Restart the Application.
Check if it shows those items as fav after restarting application .
also add logs to those if conditions where you are changing the drawables.
After looking at your JSON it looks like id is what creating problems. Id is null for all your json items so when fav. one it shows fav. to all.
Solution : Use another field to check if the data is added to fav.list
Delete will not work either
Try
#Query("DELETE FROM favoritelist WHERE title = :title")
void deleteByUserId(String title);
To delete item
Also https://github.com/amitshekhariitbhu/Android-Debug-Database
check this library to debug your database
I have objects in my firebase database called userForm .
Each userForm have an instance variable called isPassedInspection that is either set to true or false in my firebase.
users can send Form object to my firebase, therefore I manually set isPassedInspection to true once I consider the form they send as "approved" by my standards.
I would like that my RecyclerView only create CardViews for userForm that it's isPassedInspection is true, otherwise, don't create a CardView (return null).
This is my code:
adapter = new FirebaseRecyclerAdapter<userForm, userFormViewHolder>(options) {
boolean isFormInspected;
#Override
public userFormViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
isPassedFormQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
Log.e(TAG,"datasnapshot doesn't exist in db");
}
for(DataSnapshot singleSnapshot: dataSnapshot.getChildren()){
if(singleSnapshot.exists()){
//get the boolean variable from firebase for this item, and set it to "isFormInspected"
isFormInspected = singleSnapshot.getValue(userForm.class).isPassedInspection();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// if form is manually inspected create a CardView for that form, else return null
if(isFormInspected){
CardView cv =(CardView)LayoutInflater.from(parent.getContext())
.inflate(R.layout.form_card, parent, false);
Log.e(TAG, "Created a CardView");
return new userFormViewHolder(cv);
}
else{
Log.e(TAG,"Form is not inspected,so dont create a CardView");
return null;
}
}
even though I know for sure that my item isPassedInspection is true, I always get this log I made:
Form is not inspected,so dont create a CardView
and after that this error:
java.lang.NullPointerException: Attempt to write to field 'int
android.support.v7.widget.RecyclerView$ViewHolder.mItemViewType' on a
null object reference
any suggestions? thank you!
Use your own adapter class.
you can see the codes.
UserForm.class
public class UserForm {
String name,birthday,hobby;
boolean isPassedInspection;
public UserForm(String name, String birthday, String hobby, boolean isPassedInspection) {
this.name = name;
this.birthday = birthday;
this.hobby = hobby;
this.isPassedInspection = isPassedInspection;
}
public UserForm() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public boolean isPassedInspection() {
return isPassedInspection;
}
public void setPassedInspection(boolean passedInspection) {
isPassedInspection = passedInspection;
}}
// adapter class
public class FormsAdapter extends RecyclerView.Adapter<FormsViewHolder> {
private ArrayMap<String,UserForm> formsList=new ArrayMap<>();
/*use arrayMap to get from data and key */
public FormsAdapter() {
formsList=new ArrayMap<>();
}
#Override
public FormsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
// inflating card view item
View v = inflater.inflate(R.layout.form_card, parent, false);
return new FormsViewHolder(v);
}
#Override
public void onBindViewHolder(FormsViewHolder holder, int position) {
String itemKey=formsList.keyAt(position);
UserForm userForm=formsList.get(itemKey);
// set one forms data
holder.setFormsData(userForm);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// handle click event
}
});
}
#Override
public int getItemCount() {
return formsList.size();
}
public void addAFormItem(String key,UserForm userForm)
{
if (!formsList.containsKey(key))
{
formsList.put(key,userForm);
notifyItemInserted(formsList.size());
}
} }
ViewHolder class
public class FormsViewHolder extends RecyclerView.ViewHolder {
public View view;
public FormsViewHolder(View itemView) {
super(itemView);
view=itemView;
}
public void setFormsData(UserForm userForm)
{
// initialise card views items and set value in them
TextView userName=(TextView)view.findViewById(R.id.userName);
userName.setText(userForm.getName());
}}
your fragment
public class FormsListFragment extends Fragment {
private DatabaseReference formsRef;
private FormsAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_forms_list, container, false);
/**/
RecyclerView recyclerView=(RecyclerView)view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter=new FormsAdapter();
recyclerView.setAdapter(adapter);
formsRef= FirebaseDatabase.getInstance().getReference().child("forms");
formsRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
/*add data in adapter one by one if isPassedInspection true*/
String itemKey=dataSnapshot.getKey();
UserForm userForm=dataSnapshot.getValue(UserForm.class);
if (userForm.isPassedInspection())
adapter.addAFormItem(itemKey,userForm);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
/*when something change in data then add in adapter if isPassedInspection true*/
String itemKey=dataSnapshot.getKey();
UserForm userForm=dataSnapshot.getValue(UserForm.class);
if (userForm.isPassedInspection())
adapter.addAFormItem(itemKey,userForm);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}}
I am trying to Access a Json object nested within another Json object. I have written a POJO class but does not allow me to access data:
Here is Json Example:
{
"relationships": {
"competition": {
"data": {
"type": "competitions",
"id": "37"
}
}
},
"attributes": {
"has_league_table": false,
"name": "Round of 16",
"stage": "Round of 16"
},
"type": "rounds",
"id": "881"
},
I want to access the data JSON Object within Relationships->Competitions JSON objects
Here is my POJO Classes:
public class Relationships {
private Competition competition;
public Competition getCompetition ()
{
return competition;
}
public void setCompetition (Competition competition)
{
this.competition = competition;
}
}
Competition POJO
public class Competition {
private Data data;
public Data getData ()
{
return this.data;
}
public void setData (Data data)
{
this.data = data;
}
}
DATA POJO
public class Data {
private String id;
private String type;
public String getId ()
{
return this.id;
}
public void setId (String id)
{
this.id = id;
}
public String getType ()
{
return this.type;
}
public void setType (String type)
{
this.type = type;
}
}
And my Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private List<Included> includedData;
public Adapter(List<Included> includedData) {
this.includedData = includedData;
}
#Override
public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.tvCompetitionName.setText(includedData.get(position).getAttributes().getName());
holder.homeTeam.setText(includedData.get(position).getRelationships().getCompetition().getData().getType());
holder.itemView.setTag(includedData.get(position));
}
#Override
public int getItemCount() {
return includedData.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView tvCompetitionName;
private TextView homeTeam;
private TextView score;
public ViewHolder(View itemView) {
super(itemView);
tvCompetitionName = (TextView) itemView.findViewById(R.id.competitionNameTV);
homeTeam = (TextView) itemView.findViewById(R.id.homeTeamTv);
score = (TextView) itemView.findViewById(R.id.score);
}
}
}
However in my onBindViewHolder
holder.homeTeam.setText(includedData.get(position).getRelationships().getCompetition().getData().getType());
produces error:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.xxx.xxxx.DataModel_Included.Data com.xxxx.xxxx.DataModel_Included.Competition.getData()' on a null object reference
Any help on this?
I have seen others ask this question but it seems to me that I have done all the things that are required and I'm still not getting it to work. I am getting the No setter/field for name found on class error. Database
I included a pic of what my database is. It is incredibly simple.
public class Restaurants {
private String name;
public Restaurants(){}
public Restaurants(String name)
{
this.name = name;
}
public String getRestaurant()
{
return name;
}
public void setRestaurant(String name)
{
this.name = name;
}
#Override
public String toString() {
return "Restaurants" +
"name" + name;
}
}
I have my getter and setter here so in theory it should be working.
public class RestaurantSelectionList extends Fragment {
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mRestReference = mRootRef.child("restaurants");
List<String>listofrest = new ArrayList<String>();
ListView restaurantListView;
ListAdapter restaurantListAdapter;
public RestaurantSelectionList(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.restaurant_selection_list_frag,container,false);
restaurantListView = (ListView) view.findViewById(R.id.restaurantListView);
restaurantListAdapter = new FirebaseListAdapter<Restaurants>(getActivity(),Restaurants.class,R.layout.individual_restaurant_name,mRestReference) {
#Override
protected void populateView(View v, Restaurants model, int position) {
TextView restName = (TextView) v.findViewById(R.id.restname);
restName.setText(model.getRestaurant());
listofrest.add(position,model.getRestaurant());
}
};
restaurantListView.setAdapter(restaurantListAdapter);
restaurantListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "test", Toast.LENGTH_SHORT).show();
}
});
return view;
}
This is the code that calls it. Please tell me what I am missing. This is going on 4 hours of looking at this.
Please change your Model Class to:
public class Restaurants {
private String name;
public Restaurants(){}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
#Override
public String toString() {
return "Restaurants" + "name" + name;
}
}