I have listview that have to fill from JSON file but until now after running app I see nothing and I don't know if the problem from java codes or JSON file??
also I notice that I can't add file extensions inside #Path ,,
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
final Retrofit retrofit = new Retrofit.Builder().baseUrl("http://10.0.2.2").addConverterFactory(GsonConverterFactory.create()).build();
TelService service = retrofit.create(TelService.class);
final retrofit.Call<List<tel_list>> calls = service.getphones("telephones");
calls.enqueue(new Callback<List<tel_list>>() {
#Override
public void onResponse(Response<List<tel_list>> response, Retrofit retrofit) {
if (!response.isSuccess()) {
//TODO
return;
}
List<tel_list> telephones = response.body();
TelAdapter adapter = new TelAdapter (MainActivity.this, telephones);
listView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
TelService.java
public interface TelService {
#GET("/alruthea/{getphones_1}.php")
retrofit.Call<List<tel_list>> getphones(#Path("getphones_1")String telephones);
}
TelAdapter.java
public class TelAdapter extends ArrayAdapter<tel_list> {
private Context context;
private List<tel_list> telephones;
public TelAdapter(Context context, List<tel_list> data) {
super(context, R.layout.list_item, data);
telephones = data;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View item = inflater.inflate(R.layout.list_item, null);
TextView name = (TextView) item.findViewById(R.id.names);
name.setText(telephones.get(position).getName());
TextView number = (TextView) item.findViewById(R.id.numbers);
number.setText(telephones.get(position).getNumber());
return item;
}
}
tel_list.java
public class tel_list {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Related
I'm on a project that, i'm getting datas from Json output. And showing them in my app. Json output includes categories in categories. I'm showing categories with listView, therefore i'm using adapters. It's all ok with FirstPageAdapter but when I switch the other, I can't get datas from FirstPageAdapter with using intent. That question(How to call getIntent() in adapter class) didn't helped me well btw.
FirstPageAdapter.java:
public class FirstPageAdapter extends BaseAdapter {
List<ResponseDTO> responseDTOList;
Context context;
Activity activity;
public FirstPageAdapter(List<ResponseDTO> responseDTOList, Context context, Activity activity) {
this.responseDTOList = responseDTOList;
this.context = context;
this.activity = activity;
}
#Override
public int getCount() {
return responseDTOList.size();
}
#Override
public Object getItem(int i) {
return responseDTOList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = LayoutInflater.from(context).inflate(R.layout.layout_main_act, viewGroup, false);
TextView id, idCategory, parent_id, categoryName, filters, brands;
Button categoriesButton, specsButton;
id = view.findViewById(R.id.id);
idCategory = view.findViewById(R.id.idCategory);
parent_id = view.findViewById(R.id.parent_id);
categoryName = view.findViewById(R.id.categoryName);
filters = view.findViewById(R.id.filters);
brands = view.findViewById(R.id.brands);
categoriesButton = view.findViewById(R.id.childCategories);
specsButton = view.findViewById(R.id.specs);
id.setText("ID : "+responseDTOList.get(i).getId());
idCategory.setText("Category ID: "+responseDTOList.get(i).getIdcategory());
parent_id.setText("Parent ID: "+responseDTOList.get(i).getParentId());
categoryName.setText("Category name : "+responseDTOList.get(i).getCategoryName());
filters.setText("Filters : "+responseDTOList.get(i).getFilters());
brands.setText("Brands : "+responseDTOList.get(i).getBrands());
final String post = "" + responseDTOList.get(i).getId();
final String id_category = "" + responseDTOList.get(i).getIdcategory();
categoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, ChildCategoriesAdapter.class);
intent.putExtra("post_id",post);
intent.putExtra("id_category",id_category);
activity.startActivity(intent);
}
});
specsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, ChildCategoriesAdapter.class);
intent.putExtra("post_id",post);
intent.putExtra("id_category",id_category);
activity.startActivity(intent);
}
});
return view;
}
}
ChildCategoriesAdapter.java:
public class ChildCategoriesAdapter extends BaseAdapter {
List<ResponseDTO> responseDTOList;
Context context;
Activity activity;
public ChildCategoriesAdapter(List<ResponseDTO> responseDTOList, Context context, Activity activity) {
this.responseDTOList = responseDTOList;
this.context = context;
this.activity = activity;
}
#Override
public int getCount() {
return responseDTOList.size();
}
#Override
public Object getItem(int i) {
return responseDTOList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
defVars(view, viewGroup);
return null;
}
public void defVars(View view, ViewGroup viewGroup)
{
view = LayoutInflater.from(context).inflate(R.layout.layout_activity_child, viewGroup, false);
Button variationsButton;
TextView id, idCategory, parent_id, categoryName, filters, brands;
id = view.findViewById(R.id.id);
idCategory = view.findViewById(R.id.idCategory);
parent_id = view.findViewById(R.id.parent_id);
categoryName = view.findViewById(R.id.categoryName);
filters = view.findViewById(R.id.filters);
brands = view.findViewById(R.id.brands);
variationsButton = view.findViewById(R.id.variationsButton);
}
public void request()
{
responseDTOList = new ArrayList<>();
//Call<List<ResponseDTO>> call = ManagerAll
}
}
I have their Activities apart from these.
MainActivity.java(FirstPageAdapter):
public class MainActivity extends AppCompatActivity {
FirstPageAdapter adp;
List<ResponseDTO> list;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
defVars();
request();
}
public void defVars()
{
listView = findViewById(R.id.listView);
}
public void request()
{
list = new ArrayList<>();
Call<List<ResponseDTO>> call = ManagerAll.getInstance().bringCall();
call.enqueue(new Callback<List<ResponseDTO>>() {
#Override
public void onResponse(Call<List<ResponseDTO>> call, Response<List<ResponseDTO>> response) {
if (response.isSuccessful())
{
list = response.body();
adp = new FirstPageAdapter(list, getApplicationContext(), MainActivity.this);
listView.setAdapter(adp);
}
}
#Override
public void onFailure(Call<List<ResponseDTO>> call, Throwable t) {
}
});
}
}
Nothing important in ChildCategories.java
This is my adapter for recycle view
CategoryAdapter Class
public class CategoryRAdapter extends RecyclerView.Adapter<CategoryRAdapter.MyViewHolder> {
private Context mcontext;
private List<Food> mData;
RequestOptions option;
public CategoryRAdapter(Context mcontext, List<Food> mData) {
this.mcontext = mcontext;
this.mData = mData;
option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Food current = mData.get(position);
holder.tv_Name.setText(current.getName());
holder.tv_Rating.setText(current.getRating());
holder.tv_Descip.setText(current.getDescrip());
holder.tv_Category.setText(current.getCateg());
Glide.with(mcontext).load(mData.get(position).getImages()).apply(option).into(holder.img_Thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_Name;
TextView tv_Rating;
TextView tv_Descip;
TextView tv_Category;
ImageView img_Thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
tv_Name = itemView.findViewById(R.id.food_name);
tv_Rating = itemView.findViewById(R.id.rating);
tv_Descip = itemView.findViewById(R.id.desc);
tv_Category = itemView.findViewById(R.id.category);
img_Thumbnail = itemView.findViewById(R.id.thumbnail);
}
}
}
This is my model
Food Class
public class Food {
String Name;
String Images;
String Descrip;
String Rating;
String Categ;
public Food() {
}
public Food(String name, String images, String descrip, String rating, String categ) {
this.Name = name;
this.Images = images;
this.Descrip = descrip;
this.Rating = rating;
this.Categ = categ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImages() {
return Images;
}
public void setImages(String images) {
Images = images;
}
public String getDescrip() {
return Descrip;
}
public void setDescrip(String descrip) {
Descrip = descrip;
}
public String getRating() {
return Rating;
}
public void setRating(String rating) {
Rating = rating;
}
public String getCateg() {
return Categ;
}
public void setCateg(String categ) {
Categ = categ;
}
}
My mian activity
CategoryActivity Class
public class CategoriaActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Food> dbObjects;
private RecyclerView.Adapter adapter;
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
TextView l_nombre,l_precio;
Button l_finalizar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoria);
recyclerView = findViewById(R.id.recycle_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dbObjects = new ArrayList<>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objList, ParseException e) {
if (e == null) {
for (ParseObject obj : objList) {
Food food = new Food();
food.setName(obj.getString("Name"));
food.setDescrip(obj.getString("Descrip"));
food.setRating(obj.getString("Rating"));
food.setCateg(obj.getString("Categ"));
food.setImages(obj.getString("Images"));
dbObjects.add(food);
}
} else {
FancyToast.makeText(CategoriaActivity.this, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, true).show();
}
}
});
adapter = new CategoryRAdapter(this, dbObjects);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.shoppingFlot);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
carritopop();
}
});
}
private void carritopop() {
dialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.pop_cart,null);
l_finalizar = view.findViewById(R.id.l_finalizar);
l_finalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pago();
}
});
dialogBuilder.setView(view);
dialog = dialogBuilder.create();
dialog.show();
}
private void pago() {
Intent intent = new Intent(CategoriaActivity.this, PagoActivity.class);
startActivity(intent);
}
}
I dont know whats wrong with the code, the recycle view aint working, it aint showing any items, i would really appreciate if someone could help me out and notice something wrong in my code
Call adapter.notifyDataSetChanged() in your query done callback, this will notify the adapter that the list has changed. This is happening because when you set the adapter, the list was empty as the query was running in background. Once it completes, you have to tell the adapter that new data has been added to list:
if (e == null) {
for (ParseObject obj : objList) {
...
}
adapter.notifyDataSetChanged();
}
Also, create your adapter before you send the query otherwise it may result in NullPointerException in case data is loaded before the next statement executes (highly unlikely but never hurts to be safe).
dbObjects = new ArrayList<>();
adapter = new CategoryRAdapter(this, dbObjects);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
I recommend you to use RxJava2 to user asynchronous methods, it's awesome... And about the problem, maybe your data is not ready when you're already creating the adapter with the ArrayList.
Try to move the recyclerView.setAdapter() to inside the FindCallback after create the Food Objects.
I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}
This question already has an answer here:
Android - null object reference when iterating List
(1 answer)
Closed 5 years ago.
i want parse json with retrofit2 but my code dose not work
this web service is:(please check the webservice):
http://services.groupkt.com/country/search?text=
this is my model class:
public class Country {
#SerializedName("name")
#Expose
private String name;
#SerializedName("alpha2_code")
#Expose
private String alpha2Code;
#SerializedName("alpha3_code")
#Expose
private String alpha3Code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlpha2Code() {
return alpha2Code;
}
public void setAlpha2Code(String alpha2Code) {
this.alpha2Code = alpha2Code;
}
public String getAlpha3Code() {
return alpha3Code;
}
public void setAlpha3Code(String alpha3Code) {
this.alpha3Code = alpha3Code;
}
}
And:
public class CountryResponse {
#SerializedName("messages")
#Expose
private List<String> messages = null;
#SerializedName("result")
#Expose
private List<Country> countryList = null;
public List<String> getMessages() {
return messages;
}
public void setMessages(List<String> messages) {
this.messages = messages;
}
public List<Country> getCountryList() {
return countryList;
}
public void setCountryList(List<Country> countryList) {
this.countryList = countryList;
}
}
And:
public class Example {
#SerializedName("RestResponse")
#Expose
private CountryResponse restResponse;
public CountryResponse getRestResponse() {
return restResponse;
}
public void setRestResponse(CountryResponse restResponse) {
this.restResponse = restResponse;
}
}
And this is my interface class:
public interface APIInterface {
#GET("search?text=")
Call<Example> getCountries();
}
And i write 2 classes for return retrofit object:
public class APIClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
public class APIUtils {
public static final String BASE_URL =
"http://services.groupkt.com/country/";
public static APIInterface getSOService() {
return APIClient.getClient(BASE_URL).create(APIInterface.class);
}
}
My Adapter:
public class ResponseAdapter extends
RecyclerView.Adapter<ResponseAdapter.ViewHolder> {
private List<Example> mItems;
private Context mContext;
Example example;
CountryResponse countyResponse;
public ResponseAdapter(Context context, Example example) {
this.example = example;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Example example = mItems.get(position);
TextView textView = holder.name;
textView.setText(example.getRestResponse()
.getCountryList().get(position).getName());
TextView textView1 = holder.alpha;
textView1.setText(example.getRestResponse().
getCountryList().get(position).getAl
pha2Code());
TextView textView2 = holder.alpha2;
textView2.setText(example.getRestResponse().
getCountryList().get(position).getAl
pha3Code());
}
#Override
public int getItemCount() {
return mItems.size();
}
public void updateAnswers(CountryResponse countryRes) {
countyResponse = countryRes;
notifyDataSetChanged();
}
private Example getItem(int adapterPosition) {
return mItems.get(adapterPosition);
}
public interface PostItemListener {
void onPostClick(long id);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, alpha, alpha2;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
alpha = (TextView) itemView.findViewById(R.id.alpha);
alpha2 = (TextView) itemView.findViewById(R.id.alpha2);
}
}
}
And My Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_response);
apiInterface= APIUtils.getSOService();
mRecyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter=new ResponseAdapter(this,new Example());
RecyclerView.LayoutManager layoutManager = new
LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
loadAnswers();
}
private void loadAnswers() {
apiInterface.getCountries().enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example>
response) {
mAdapter.updateAnswers(response.body().getRestResponse());
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
}
});
}
when run a error showing that
'java.util.Iterator java.util.List.iterator()' on a null object reference
You have
#Override
public int getItemCount() {
return mItems.size();
}
public void updateAnswers(CountryResponse countryRes) {
countyResponse = countryRes;
notifyDataSetChanged();
}
Your List is not initialized in the first place. Secondly you need to populate your List with items. And your list must be Country list not of type Example
You need to change to
public void updateAnswers(CountryResponse countryRes) {
mItems.addAll(countryRes.getCountryList())
notifyDataSetChanged();
}
And also initialize the list
List<Country> mItems = new ArrayList();
// note its of type Country not of Example
Finally update your views accordingly in onBindViewHolder
textView.setText(mItems.get(position).getName());
textView1.setText(mItems.get(position).getAlpha2Code());
textView2.setText(mItems.get(position).getAlpha3Code());
This question already has answers here:
Fragment cannot be converted to Context
(4 answers)
Closed 5 years ago.
I want to parse JSON and display with RecyclerView and CardView in Android. I have a tabHost menu and there are three fragments activities of it. I put all my code for the CardView into one of the fragment, but the code has errors when I use "this" to call GridLayoutManager and CustomAdapter.
This is the code in fragment activity, the error is in onViewCreated:
final TextView tv = (TextView) view.findViewById(R.id.tv);
adapter = new CustomAdapter(this,data_list);
The error message is:
Error:(75, 51) error: incompatible types: Tab2Fragment cannot be converted to Context, GridLayoutManager(android.content.Context, int) in GridLayoutManager cannot applied to (com.xxx.xxx.xxx.Tab2Fragment)
public class Tab2Fragment extends Fragment {
private RecyclerView recyclerView;
private GridLayoutManager gridLayoutManager;
private CustomAdapter adapter;
private List<MyData> data_list;
public Tab2Fragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab2, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences settings = this.getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
String username = settings.getString("username","default"); // get back the stored share preferences
final TextView tv = (TextView) view.findViewById(R.id.tv);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
data_list = new ArrayList<>();
load_data_from_server(username);
gridLayoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(gridLayoutManager);
adapter = new CustomAdapter(this,data_list);
recyclerView.setAdapter(adapter);
}
private void load_data_from_server(final String username) {
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.tootcards.com/instaidea/cardapi.php?username="+strings[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
MyData data = new MyData(object.getInt("shop_id"),object.getString("shop_name"),
object.getString("cardimg"));
data_list.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of content");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(username);
}
#Override
public void onDetach() {
super.onDetach();
}
}
The code in CustomAdapter.java:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<MyData> my_data;
public CustomAdapter(Context context, List<MyData> my_data) {
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.description.setText(my_data.get(position).getDescription());
Glide.with(context).load(my_data.get(position).getImage_link()).into(holder.imageView);
}
#Override
public int getItemCount() {
return my_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView description;
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.description);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
}
The code in myData.java:
class MyData {
private int id;
private String description, image_link;
public MyData(int id, String description, String image_link) {
this.id = id;
this.description = description;
this.image_link = image_link;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
}
Any help will be appreciated.
Change
this
to
getActivity()
try this
final TextView tv = (TextView) view.findViewById(R.id.tv); adapter = new CustomAdapter(getActivity(), data_list);
or
final TextView tv = (TextView) view.findViewById(R.id.tv); adapter = new CustomAdapter(getContext(), data_list);