I am making a call to a server using Retrofit and getting a json response. The error I'm getting is:
Expected BEGIN_OBJECT but was BEGIN_ARRAY
This is my code
Main method,
public class MainActivity extends ListActivity {
List<Movie> movieList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RestAdapter restadapter = new RestAdapter.Builder().setEndpoint("http://api.themoviedb.org").build();
api movieapi = restadapter.create(api.class);
movieapi.getData(new Callback<List<Movie>>() {
#Override
public void success(List<Movie> movies, Response response) {
movieList = movies;
adapter adapt = new adapter(getApplicationContext(),R.layout.item_file,movieList);
//ListView listView = (ListView) findViewById(R.id.list);
setListAdapter(adapt);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Interface api
public interface api {
#GET("/3/discover/movie?sort_by=popularity.desc&api_key=e2a804764747474747474574817b218e")
public void getData(Callback<List<Movie>> response);
}
class adapter
public class adapter extends ArrayAdapter<Movie> {
String url = "http://image.tmdb.org/t/p/w185";
private Context context;
private List<Movie> movieList;
public adapter(Context context, int resource, List<Movie> objects) {
super(context, resource, objects);
this.context = context;
this.movieList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_file,parent,false);
Movie movie = movieList.get(position);
TextView tv = (TextView) view.findViewById(R.id.name);
tv.setText(movie.getTitle());
ImageView img = (ImageView) view.findViewById(R.id.img);
Picasso.with(getContext()).load(url+movie.getPoster_path()).into(img);
return view;
}
}
Movie class (Where I handle the getters setters for json)
package com.wuno.moviesapp.model;
public class Movie
{
private String vote_average;
private String backdrop_path;
private String adult;
private String id;
private String title;
private String original_language;
private String overview;
private String[] genre_ids;
private String original_title;
private String release_date;
private String vote_count;
private String poster_path;
private String video;
private String popularity;
public String getVote_average ()
{
return vote_average;
}
public void setVote_average (String vote_average)
{
this.vote_average = vote_average;
}
public String getBackdrop_path ()
{
return backdrop_path;
}
public void setBackdrop_path (String backdrop_path)
{
this.backdrop_path = backdrop_path;
}
public String getAdult ()
{
return adult;
}
public void setAdult (String adult)
{
this.adult = adult;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getOriginal_language ()
{
return original_language;
}
public void setOriginal_language (String original_language)
{
this.original_language = original_language;
}
public String getOverview ()
{
return overview;
}
public void setOverview (String overview)
{
this.overview = overview;
}
public String[] getGenre_ids ()
{
return genre_ids;
}
public void setGenre_ids (String[] genre_ids)
{
this.genre_ids = genre_ids;
}
public String getOriginal_title ()
{
return original_title;
}
public void setOriginal_title (String original_title)
{
this.original_title = original_title;
}
public String getRelease_date ()
{
return release_date;
}
public void setRelease_date (String release_date)
{
this.release_date = release_date;
}
public String getVote_count ()
{
return vote_count;
}
public void setVote_count (String vote_count)
{
this.vote_count = vote_count;
}
public String getPoster_path ()
{
return poster_path;
}
public void setPoster_path (String poster_path)
{
this.poster_path = poster_path;
}
public String getVideo ()
{
return video;
}
public void setVideo (String video)
{
this.video = video;
}
public String getPopularity ()
{
return popularity;
}
public void setPopularity (String popularity)
{
this.popularity = popularity;
}
#Override
public String toString()
{
return "Movie [vote_average = "+vote_average+", backdrop_path = "+backdrop_path+", adult = "+adult+", id = "+id+", title = "+title+", original_language = "+original_language+", overview = "+overview+", genre_ids = "+genre_ids+", original_title = "+original_title+", release_date = "+release_date+", vote_count = "+vote_count+", poster_path = "+poster_path+", video = "+video+", popularity = "+popularity+"]";
}
}
Retrofit tries to parse the result to the type you've specified, and this is not the type that is returned. The list you've specified is a member of the object that returns.
You should create an object for the response:
public class MoviesResponse {
private int page;
private List<Movie> results;
private int total_pages;
private int total_results;
}
And change your callback:
#GET("/3/discover/movie?sort_by=popularity.desc&api_key=your_api_key")
public void getData(Callback<MoviesResponse> response);
Related
I'm trying to pass an object from my RecyclerView adapter to a fragment using parcelable. However when I try to receive the data, the bundle is null. I've looked at other examples, but I can't see where I'm going wrong.
Parcelable class
public class Country extends BaseObservable implements Parcelable {
#SerializedName("name")
#Expose
private String name;
#SerializedName("snippet")
#Expose
private String snippet;
#SerializedName("country_id")
#Expose
private String countryId;
#SerializedName("id")
#Expose
private String id;
#SerializedName("coordinates")
#Expose
private Coordinates coordinates;
#SerializedName("images")
#Expose
private List<CountryImage> images;
protected Country(Parcel in) {
name = in.readString();
snippet = in.readString();
}
public static final Creator<Country> CREATOR = new Creator<Country>() {
#Override
public Country createFromParcel(Parcel in) {
return new Country(in);
}
#Override
public Country[] newArray(int size) {
return new Country[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(snippet);
}
#Override
public int describeContents() {
return 0;
}
#Bindable
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
notifyPropertyChanged(BR.countryId);
}
#Bindable
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
notifyPropertyChanged(BR.id);
}
#Bindable
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
notifyPropertyChanged(BR.coordinates);
}
#Bindable
public List<CountryImage> getImages() {
return images;
}
public void setImages(List<CountryImage> images) {
this.images = images;
notifyPropertyChanged(BR.images);
}
#Bindable
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
notifyPropertyChanged(BR.snippet);
}
#Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
RetrofitAdapter.java
public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.MyViewHolder> implements CustomClickListener {
private List<Country> cities;
private CustomClickListener customClickListener;
private View view;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
RetroItemBinding retroItemBinding =
DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
R.layout.retro_item, viewGroup, false);
view = viewGroup;
return new MyViewHolder(retroItemBinding);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.bindTo(cities.get(i));
myViewHolder.retroItemBinding.setItemClickListener(this);
}
#Override
public int getItemCount() {
if (cities != null) {
return cities.size();
} else {
return 0;
}
}
public void setCityList(ArrayList<Country> cities) {
this.cities = cities;
notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private RetroItemBinding retroItemBinding;
public MyViewHolder(#NonNull RetroItemBinding retroItemBinding) {
super(retroItemBinding.getRoot());
this.retroItemBinding = retroItemBinding;
}
void bindTo(Country country) {
retroItemBinding.setVariable(BR.city, country);
retroItemBinding.setVariable(BR.itemClickListener, customClickListener);
retroItemBinding.executePendingBindings();
}
}
public void cardClicked(Country country) {
CountryFragment countryFragment = new CountryFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("Country", country);
countryFragment.setArguments(bundle);
((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction()
.replace(R.id.frag_container, new CountryFragment())
.commit();
}
}
Where I receive attempt to receive the data in CountryFragment.java
Country country;
Bundle bundle = this.getArguments();
if (bundle != null) {
country = bundle.getParcelable("Country");
}
.replace(R.id.frag_container, new CountryFragment())
should be
.replace(R.id.frag_container, countryFragment)
You are creating a second instance instead of passing the one you set the arguments on.
I have a listview getting filtered by an edit text on top. However, when I click on the item searched I get the result of another item being selected.
I Know similar questions are asked and answered by many already, but I went through all the forum but I am breaking my head from long back and sorry newbie much.
Any help will be appreciated.
My adapter:
public class Srv_Adapter extends RecyclerView.Adapter<Srv_Adapter.MyViewHolder> implements Filterable {
List<Srv_Pets> pets, srvPetsFilter;
private Context context;
private RecyclerViewClickListener mListener;
Srv_CustomFilter filter;
public Srv_Adapter(List<Srv_Pets> pets, Context context, RecyclerViewClickListener listener) {
this.pets = pets;
this.srvPetsFilter = pets;
this.context = context;
this.mListener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_srv, parent, false);
return new MyViewHolder(view, mListener);
}
#SuppressLint("CheckResult")
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.mName.setText(pets.get(position).getName());
holder.mType.setText(pets.get(position).getModel() + " / "
+ pets.get(position).getCreated_by());
holder.mDate.setText(pets.get(position).getBirth());
RequestOptions requestOptions = new RequestOptions();
requestOptions.skipMemoryCache(true);
requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
requestOptions.placeholder(R.drawable.logo);
requestOptions.error(R.drawable.logo);
Glide.with(context)
.load(pets.get(position).getPicture())
.apply(requestOptions)
.into(holder.mPicture);
final Boolean love = pets.get(position).getLove();
if (love){
holder.mLove.setImageResource(R.drawable.likeon);
} else {
holder.mLove.setImageResource(R.drawable.likeof);
}
}
#Override
public int getItemCount() {
return pets.size();
}
#Override
public Filter getFilter() {
if (filter==null) {
filter=new Srv_CustomFilter((ArrayList<Srv_Pets>) srvPetsFilter,this);
}
return filter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private RecyclerViewClickListener mListener;
private CircleImageView mPicture;
private ImageView mLove;
private TextView mName, mType, mDate;
private RelativeLayout mRowContainer;
public MyViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
mPicture = itemView.findViewById(R.id.picture);
mName = itemView.findViewById(R.id.name);
mType = itemView.findViewById(R.id.type);
mLove = itemView.findViewById(R.id.love);
mDate = itemView.findViewById(R.id.date);
mRowContainer = itemView.findViewById(R.id.row_container);
mListener = listener;
mRowContainer.setOnClickListener(this);
mLove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.row_container:
mListener.onRowClick(mRowContainer, getAdapterPosition());
break;
case R.id.love:
mListener.onLoveClick(mLove, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowClick(View view, int position);
void onLoveClick(View view, int position);
}
}
Search Menu Activity
public class Service_Main extends AppCompatActivity{
SharedPreferences prf;
Intent intent;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Srv_Adapter srvAdapter;
private List<Srv_Pets> srvPetsList;
Srv_ApiInterface srvApiInterface;
Srv_Adapter.RecyclerViewClickListener listener;
ProgressBar progressBar;
private String userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_main);
srvApiInterface = Srv_ApiClient.getApiClient().create(Srv_ApiInterface.class);
progressBar = findViewById(R.id.progress);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
TextView result = (TextView)findViewById(R.id.result);
recyclerView.setLayoutManager(layoutManager);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(Service_Main.this, loginActivity.class);
userInfo = prf.getString("username",null);
listener = new Srv_Adapter.RecyclerViewClickListener() {
private Srv_Pets getIteamposition(int position)
{
return srvPetsList.get(position);
}
#Override
public void onRowClick(View view, final int position) {
Intent intent = new Intent(Service_Main.this, Service_edit.class);
intent.putExtra("id", srvPetsList.get(position).getId());
intent.putExtra("name", srvPetsList.get(position).getName());
intent.putExtra("species", srvPetsList.get(position).getSpecies());
intent.putExtra("jobcard", srvPetsList.get(position).getJobcard());
intent.putExtra("model_code", srvPetsList.get(position).getModel_code());
intent.putExtra("picture", srvPetsList.get(position).getPicture());
intent.putExtra("birth", srvPetsList.get(position).getBirth());
intent.putExtra("entry_mode", srvPetsList.get(position).getEntry_mode());
intent.putExtra("pickup_done_by_code", srvPetsList.get(position).getPickup_done_by_code());
intent.putExtra("drop_mode", srvPetsList.get(position).getDrop_mode());
intent.putExtra("service_type", srvPetsList.get(position).getDrop_mode());
intent.putExtra("drop_done_by_code", srvPetsList.get(position).getDrop_done_by_code());
intent.putExtra("pick_emp_name", srvPetsList.get(position).getPick_emp_name());
intent.putExtra("drop_emp_name", srvPetsList.get(position).getDrop_emp_name());
startActivity(intent);
final int id = srvPetsList.get(position).getId();
final Boolean love = srvPetsList.get(position).getLove();
final ImageView mLove = view.findViewById(R.id.love);
if (love){
mLove.setImageResource(R.drawable.likeof);
srvPetsList.get(position).setLove(false);
updateLove("Rd_status", id, false);
srvAdapter.notifyDataSetChanged();
} else {
mLove.setImageResource(R.drawable.likeon);
srvPetsList.get(position).setLove(true);
updateLove("Rd_status", id, true);
srvAdapter.notifyDataSetChanged();
}
}
#Override
public void onLoveClick(View view, int position) {
// final int id = srvPetsList.get(position).getId();
// final Boolean love = srvPetsList.get(position).getLove();
// final ImageView mLove = view.findViewById(R.id.love);
// if (love){
// mLove.setImageResource(R.drawable.likeof);
// srvPetsList.get(position).setLove(false);
// updateLove("Rd_status", id, false);
// srvAdapter.notifyDataSetChanged();
// } else {
// mLove.setImageResource(R.drawable.likeon);
// srvPetsList.get(position).setLove(true);
// updateLove("Rd_status", id, true);
// srvAdapter.notifyDataSetChanged();
// }
}
};
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Service_Main.this, Service_edit.class));
}
});
FloatingActionButton fab1 = findViewById(R.id.log_out);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Service_Main.this, HomePage.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName())
);
searchView.setQueryHint("Search Pet...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String query) {
srvAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
srvAdapter.getFilter().filter(newText);
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getPets(){
String username = userInfo;
Call<List<Srv_Pets>> call = srvApiInterface.getPets(username);
call.enqueue(new Callback<List<Srv_Pets>>() {
#Override
public void onResponse(Call<List<Srv_Pets>> call, Response<List<Srv_Pets>> response) {
progressBar.setVisibility(View.GONE);
srvPetsList = response.body();
Log.i(Service_Main.class.getSimpleName(), response.body().toString());
srvAdapter = new Srv_Adapter(srvPetsList, Service_Main.this, listener);
recyclerView.setAdapter(srvAdapter);
srvAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<Srv_Pets>> call, Throwable t) {
Toast.makeText(Service_Main.this, "rp :"+
t.getMessage().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
public void updateLove(final String key, final int id, final Boolean love){
String night_updated_by = userInfo;
String reg_num = userInfo;
Call<Srv_Pets> call = srvApiInterface.updateLove(key, id, love, night_updated_by, reg_num);
call.enqueue(new Callback<Srv_Pets>() {
#Override
public void onResponse(Call<Srv_Pets> call, Response<Srv_Pets> response) {
Log.i(Service_Main.class.getSimpleName(), "Response "+response.toString());
String value = response.body().getValue();
String message = response.body().getMassage();
if (value.equals("1")){
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Srv_Pets> call, Throwable t) {
Toast.makeText(Service_Main.this, t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
getPets();
}
}
List of Items from PHP, MYSQL using Volly
package com.haerul.mypets.service;
import com.google.gson.annotations.SerializedName;
public class Srv_Pets {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
#SerializedName("species")
private String species;
#SerializedName("breed")
private String breed;
#SerializedName("model_code")
private int model_code;
#SerializedName("jobcard")
private int jobcard;
#SerializedName("birth")
private String birth;
#SerializedName("picture")
private String picture;
#SerializedName("love")
private Boolean love;
#SerializedName("value")
private String value;
#SerializedName("message")
private String massage;
#SerializedName("model")
private String model;
#SerializedName("entry_mode")
private int entry_mode;
#SerializedName("drop_mode")
private int drop_mode;
#SerializedName("pickup_done_by_code")
private String pickup_done_by_code;
#SerializedName("service_type")
private int service_type;
#SerializedName("drop_done_by_code")
private String drop_done_by_code;
#SerializedName("pick_emp_name")
private String pick_emp_name;
#SerializedName("drop_emp_name")
private String drop_emp_name;
#SerializedName("created_by")
private String created_by;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public int getModel_code() {
return model_code;
}
public void setModel_code(int gender) {
this.model_code = model_code;
}
public int getJobcard() {
return jobcard;
}
public void setJobcard(int jobcard) {
this.jobcard = jobcard;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public Boolean getLove() {
return love;
}
public void setLove(Boolean love) {
this.love = love;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getEntry_mode(){
return entry_mode;
}
public void setEntry_mode(int entry_mode){
this.entry_mode = entry_mode;
}
public String getPickup_done_by_code() {
return pickup_done_by_code;
}
public void setPickup_done_by_code(String pickup_done_by_code) {
this.pickup_done_by_code = pickup_done_by_code;
}
public int getDrop_mode(){
return drop_mode;
}
public void setDrop_mode(int drop_mode){
this.drop_mode = drop_mode;
}
public int getService_type(){
return service_type;
}
public void setService_type(){
this.service_type = service_type;
}
public String getDrop_done_by_code(){
return drop_done_by_code;
}
public void setDrop_done_by_code(String drop_done_by_code){
this.pickup_done_by_code = drop_done_by_code;
}
public String getPick_emp_name(){
return pick_emp_name;
}
public void setPick_emp_name(String pick_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getDrop_emp_name(){
return drop_emp_name;
}
public void setDrop_emp_name(String drop_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getCreated_by(){
return created_by;
}
public void setCreated_by(String created_by){
this.created_by = created_by;
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
in my app i have a Mysql and im getting data with volley and populating recyclerView with it and to be clear i have a Restaurant list that populates the recyclerView and if you long press a restaurant you can add a note to that specific restaurant so i need the restaurant id and its positon because my note table in my dataBase is a child table that is connected to Restaurant table with FK and uses restaurant id as a refrence, i dont know why im getting NPE for the adapter.getPosition please help
MainActivity
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
SwipeRefreshLayout swipeRefreshLayout;
RestaurantAdapter adapter;
List<Restaurant> restaurants = new ArrayList<>();
String request_url = "https://localhost/api/all_fastfoods.php";
String post_url= "https://localhost/api/add_note.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout=findViewById(R.id.swipe_layout);
swipeRefreshLayout.setOnRefreshListener(this);
recyclerView = findViewById(R.id.recycleViewContainer);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
restaurants = new ArrayList<>();
registerForContextMenu(recyclerView);
getData();
NukeSSLCerts.nuke();
}
private void getData() {
swipeRefreshLayout.setRefreshing(true);
sendRequest();
}
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
restaurants.clear();
for (int i = 0; i < response.length(); i++) {
Restaurant restaurant = new Restaurant();
try {
JSONObject jsonObject = response.getJSONObject(i);
restaurant.setId(jsonObject.getInt("restaurant_id"));
restaurant.setName(jsonObject.getString("restaurant_name"));
restaurant.setAddress(jsonObject.getString("restaurant_address"));
restaurant.setImage(jsonObject.getInt("restaurant_image_type"));
restaurant.setHasNote(jsonObject.getBoolean("restaurant_has_note"));
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
Log.i("Error",e.toString());
e.printStackTrace();
}
restaurants.add(restaurant);
}
mAdapter = new RestaurantAdapter(MainActivity.this, restaurants);
recyclerView.setAdapter(mAdapter);
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error:", String.valueOf(error));
}
});
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(jsonArrayRequest);
}
public boolean onContextItemSelected(MenuItem item) {
final Restaurant restaurant= new Restaurant();
if (item.getTitle().equals("Add Note")){
AlertDialog.Builder notepad = new AlertDialog.Builder(MainActivity.this);
LayoutInflater noteInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View notepadView = noteInflater.inflate(R.layout.notes,null,false);
notepad.setView(notepadView);
final AlertDialog notepadDialog = notepad.create();
notepadDialog.getWindow().getAttributes().windowAnimations = R.style.customdialog;
notepadDialog.show();
final EditText notepadedit = notepadView.findViewById(R.id.notepad);
final Button addnote = notepadView.findViewById(R.id.fab);
notepadedit.requestFocus();
addnote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONObject update = new JSONObject();
JSONObject postparams = new JSONObject();
try {
postparams.put("Content-Type", "application/json");
postparams.put("Accept", "application/json");
postparams.put("note_content",notepadedit.getText());
postparams.put("note_date_time",System.currentTimeMillis());
postparams.put("restaurant_id",restaurants.get(adapter.getPosition()).getId());
update.put("restaurant_has_note",true);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, post_url, postparams, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "SuccessFull", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("PostLog", String.valueOf(error));
}
}
RecyclerView Adapter
public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.MyViewHolder> implements View.OnClickListener{
private Context context;
private List<Restaurant> restaurantList;
private int position;
public int getPosition() {return position;}
public void setPosition(int position) {this.position = position; }
public RestaurantAdapter(Context context,List <Restaurant> restaurantList){
this.context = context;
this.restaurantList = restaurantList;
}
#Override
public void onClick(View view){
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
public TextView FastFoodName;
public TextView FastFoodAddress;
ImageView icon,noteIcon;
MyViewHolder(View itemView){
super(itemView);
icon = itemView.findViewById(R.id.type_ic);
FastFoodName = itemView.findViewById(R.id.listview_name);
FastFoodAddress = itemView.findViewById(R.id.listview_address);
noteIcon = itemView.findViewById(R.id.note_icon);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Add Note");
menu.add(0, 2, 1, "All Notes");
}
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
setPosition(holder.getAdapterPosition());
return false;
}
});
Restaurant restaurant = restaurantList.get(position);
holder.FastFoodName.setText(restaurant.getName());
holder.FastFoodAddress.setText(restaurant.getAddress());
switch (restaurant.getImage()){
case 1:
holder.icon.setImageResource(R.drawable.phoneorderr);
break;
case 2:
holder.icon.setImageResource(R.drawable.sitdownn);
break;
case 3:
holder.icon.setImageResource(R.drawable.takeaway);
break;
}
holder.noteIcon.setImageResource(R.drawable.notepadicon);
if(restaurant.isHasNote()){
holder.noteIcon.setVisibility(View.VISIBLE);
}else {
holder.noteIcon.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return restaurantList.size();
}
#Override
public long getItemId(int position) {
return position;
}
}
and My Model class
public class Restaurant implements Serializable {
private int id;
private String name;
private String address;
private int type;
private boolean hasNote = false;
private int image;
public Restaurant() {
}
public Restaurant(String name, String address,int type){
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address,int type){
this.id = id;
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address, int type,int image) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
this.image = image;
}
public int getId() { return id;}
public void setId (int id) { this.id = id;}
public String getName() {
return name;
}
public void setName(String name) { this.name = name;}
public boolean isHasNote(){
return hasNote;
}
public void setHasNote(boolean hasNote){
this.hasNote = hasNote;
}
public String getAddress() { return address;}
public void setAddress(String address) { this.address = address;}
public void setType(int type) {this.type = type;}
public int getType() {return type;}
public int getImage() {return image;}
public void setImage(int image) {this.image = image;}
}
You have not initialized adapter. Try to initialize it before use.
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
//remove this
//RecyclerView.Adapter mAdapter;
//User this everywhere
RestaurantAdapter adapter;
.....
public void sendRequest() {
....
adapter = new RestaurantAdapter(MainActivity.this, restaurants);
recyclerView.setAdapter(adapter);
....
}
}
API Json
{
"status": true,
"message": "Subjects found.",
"data": {
"subjects": [
{
"subj_id": "2",
"name": "Maths",
"img": "Math.jpg"
},
{
"subj_id": "1",
"name": "Physics",
"img": "physics.png"
}
],
"total": 2
}
}
GET Method
#GET(WebServices.GET_ACTIVE_SUBJECT)
Call<SubjectTopics> getSubjects();
Model Class
public class SubjectTopics
{
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
private Data data;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
#SerializedName("subjects")
#Expose
private List<Subjects> subjects = null;
#SerializedName("total")
#Expose
private Integer total;
public List<Subjects> getSubjects() {
return subjects;
}
public void setSubjects(List<Subjects> subjects) {
this.subjects = subjects;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public class Subjects {
#SerializedName("subj_id")
#Expose
private String subjId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("img")
#Expose
private String img;
public String getSubjId() {
return subjId;
}
public void setSubjId(String subjId) {
this.subjId = subjId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
My Adapter Class
public class DataAdapter extend
RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<Subjects> android;
private Context context;
public DataAdapter(ArrayList<Subjects> android,Context context) {
this.android = android;
this.context = context;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.subject_topic_list_row,
viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, final int position) {
viewHolder.subjectName.setText(android.get(position).getName());
viewHolder.relativeClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SubjectTopicList.class);
intent.putExtra("subject_id", android.get(position).getSubjId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Picasso.with(context)
.load(android.get(position).getImg())
.placeholder(R.drawable.load)
.into(viewHolder.ImageV);
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView subjectName;
private TextView ID;
private ImageView ImageV;
private RelativeLayout relativeClick;
public ViewHolder(View view) {
super(view);
subjectName = (TextView) itemView.findViewById(R.id.textView);
relativeClick = (RelativeLayout) itemView.findViewById(R.id.relative_click);
ImageV = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
Main Activity
private void initViews() {
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(UnitTestSubjects.this);
recyclerView.setLayoutManager(layoutManager);
if (NetworkUtils.isNetworkAvailableToastIfNot(getApplicationContext())) {
getSubjects();
}
}
private void getSubjects() {
progressBar.setVisibility(View.VISIBLE);
Call<SubjectTopics> getProductsModelClassCall = webService.getSubjects();
getProductsModelClassCall.enqueue(new Callback<SubjectTopics>() {
#Override
public void onResponse(Call<SubjectTopics> call, Response<Example> response) {
if (response.isSuccessful()) {
SubjectTopics jsonResponse = response.body();
list = new ArrayList<Subjects>(jsonResponse.getData().getSubjects());
adapter = new DataAdapter(list);
recyclerView.setAdapter(adapter);
} else {
APIError apiError = ErrorUtils.parseError(response);
Toast.makeText(UnitTestSubjects.this, ""+apiError, Toast.LENGTH_SHORT).show();
}
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
t.printStackTrace();
Toast.makeText(UnitTestSubjects.this, "Please Try Again", Toast.LENGTH_SHORT).show();
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
I am beginner in android Retrofit2 API call.
How to fetch items and set in recycler view .I think am not getting how to set items to the adapter class.
please help me out with this.
I have tried all possible ways to solve but not able to find any solution regarding this.
You have error with your models. They aren't properly configured. Please see this tutorial for a better understanding of retrofit and recyclerview.
I'm pretty new to android and third-party libraries, so I have one problem.
I want to store some data coming from REST API into Realm, then show it into RecyclerView. I have three tabs using the same recyclerView, so it can display three different states.
Here's my classes:
public class RealmContentAdapter extends RealmRecyclerViewAdapter<ContentDataModel, RealmContentAdapter.ViewHolder> {
private Context mContext;
public static class ViewHolder extends RecyclerView.ViewHolder{
private ImageView cardIcon;
private TextView likeCounter, cardHeader, cardAddress, cardDate, cardDays;
public ViewHolder(View itemView) {
super(itemView);
this.cardIcon = (ImageView) itemView.findViewById(R.id.card_icon);
this.likeCounter = (TextView) itemView.findViewById(R.id.like_counter);
this.cardHeader = (TextView) itemView.findViewById(R.id.card_header_text);
this.cardAddress = (TextView) itemView.findViewById(R.id.card_address_text);
this.cardDate = (TextView) itemView.findViewById(R.id.card_date_text);
this.cardDays = (TextView) itemView.findViewById(R.id.card_days_text);
}
}
public RealmContentAdapter (Context context, OrderedRealmCollection<ContentDataModel> data){
super(context, data, true);
mContext = context;
}
#Override
public RealmContentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RealmContentAdapter.ViewHolder holder, int position) {
ContentDataModel model = getData().get(position);
holder.likeCounter.setText(String.valueOf(model.getLikesCounter()));
holder.cardHeader.setText(model.getTitle());
holder.cardIcon.setImageResource(R.drawable.nature);
if (model.getGeoAddress() != null){
holder.cardAddress.setText(model.getGeoAddress().getAddress());
} else {
holder.cardAddress.setText("");
}
holder.cardDate.setText(model.getNormalDate());
holder.cardDays.setText(String.valueOf(model.getDays()));
}
public class ContentDataModel extends RealmObject {
#SerializedName("id")
#Expose
private int id;
#SerializedName("user")
#Expose
private User user;
#SerializedName("geo_address")
#Expose
private GeoAddress geoAddress;
#SerializedName("category")
#Expose
private Category category;
#SerializedName("type")
#Expose
private Type type;
#SerializedName("title")
#Expose
private String title;
#SerializedName("body")
#Expose
private String body;
#SerializedName("created_date")
#Expose
private int createdDate;
#SerializedName("start_date")
#Expose
private int startDate;
#SerializedName("state")
#Expose
private State state;
#SerializedName("ticket_id")
#Expose
private String ticketId;
#SerializedName("files")
#Expose
#Ignore
private List<Files> files = new ArrayList<>();
#SerializedName("performers")
#Expose
#Ignore
private List<Performer> performers = new ArrayList<>();
#SerializedName("deadline")
#Expose
private int deadline;
#SerializedName("likes_counter")
#Expose
private int likesCounter;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public GeoAddress getGeoAddress() {
return geoAddress;
}
public void setGeoAddress(GeoAddress geoAddress) {
this.geoAddress = geoAddress;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getCreatedDate() {
return createdDate;
}
public void setCreatedDate(int createdDate) {
this.createdDate = createdDate;
}
public int getStartDate() {
return startDate;
}
public void setStartDate(int startDate) {
this.startDate = startDate;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public String getTicketId() {
return ticketId;
}
public void setTicketId(String ticketId) {
this.ticketId = ticketId;
}
public List<Files> getFiles() {
return files;
}
public void setFiles(List<Files> files) {
this.files = files;
}
public List<Performer> getPerformers() {
return performers;
}
public void setPerformers(List<Performer> performers) {
this.performers = performers;
}
public int getDeadline() {
return deadline;
}
public void setDeadline(int deadline) {
this.deadline = deadline;
}
public int getLikesCounter() {
return likesCounter;
}
public void setLikesCounter(int likesCounter) {
this.likesCounter = likesCounter;
}
public String getNormalDate(){
return DateFormatter.getNormalDate(getStartDate());
}
public String getDays(){
return DateFormatter.getGoneDays(getStartDate());
}
I have some other pojo classes, but this one is the main.
And my Recycler Fragment:
public class RecyclerFragment extends Fragment {
private static final String KEY_FILE = "file";
private RealmContentAdapter mAdapter;
private RealmResults<ContentDataModel> mData;
private RecyclerView mRecyclerView;
private Realm mRealm;
public static Fragment newInstance(String file) {
RecyclerFragment fragment = new RecyclerFragment();
Bundle args = new Bundle();
args.putString(KEY_FILE, file);
fragment.setArguments(args);
return fragment;
}
public String getPage() {
return (getArguments().getString(KEY_FILE));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_fragment_layout, container, false);
mIntent = new Intent(getContext(), CardActivity.class);
mRealm = Realm.getDefaultInstance();
mData = mRealm.where(ContentDataModel.class).findAll();
ApiService apiService = ApiModule.getApiService();
Observable<List<ContentDataModel>> tabOneContent = apiService.loadCards(
getString(R.string.processing_state), 10);
Observable<List<ContentDataModel>> tabTwoContent = apiService.loadCards(
getString(R.string.done_state), 10);
Observable<List<ContentDataModel>> tabThreeContent = apiService.loadCards(
getString(R.string.pending_state), 10);
mRecyclerView = (RecyclerView) view.findViewById(R.id.tab_recycler);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mAdapter = new RealmContentAdapter(getContext(), mData);
mRecyclerView.setAdapter(mAdapter);
if (getPage().equals(getString(R.string.processing_flag))) {
tabOneContent
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<ContentDataModel>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ContentDataModel> dataSet) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(dataSet);
realm.commitTransaction();
realm.close();
}
});
} else if (getPage().equals(getString(R.string.done_flag))) {
tabTwoContent
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<ContentDataModel>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ContentDataModel> dataSet) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(dataSet);
realm.commitTransaction();
realm.close();
}
});
} else if (getPage().equals(getString(R.string.pending_flag))) {
tabThreeContent
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<ContentDataModel>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ContentDataModel> dataSet) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(dataSet);
realm.commitTransaction();
realm.close();
}
});
}
return view;
}
The problem is when I'm trying to save List dataset to Realm, it doesn't save any. And my RealmContentAdapter is empty.
P.S.: I set up GSON carefully and it ignores RealmObject.class
UPD: So, I've found what was wrong. Realm didn't want to save data, because I've missed to add #PrimaryKey to field id in my ContentDataModel. Thank you for attention.