I am trying to parse the following json and display it in ListView using BaseAdapter, Android. Here the objects 4 and 1 are dynamic.I know how to create a model class if those values are not dynamic. I tried to get the json using following way and it doesn't return any value. Is there anything wrong in Model.java? or Should I change format of json?
{
"effect_list":[
{
"4":[
{
"effects_id":"18",
"effects_name":"Band 1"
},
{
"effects_id":"19",
"effects_name":"Band 2"
}
],
"1":[
{
"effects_id":"1",
"effects_name":"Background Blur"
},
{
"effects_id":"4",
"effects_name":"Blemish Removal"
}
]
}
]
}
Model.java
public class Model{
#SerializedName("effect_list")
#Expose
List<Map<String,List<EffectList>>> effectlist;
public List<Map<String, List<EffectList>>> getEffectlist() {
return effectlist;
}
public void setEffectlist(List<Map<String, List<EffectList>>> effectlist) {
this.effectlist = effectlist;
}
}
EffectList.java
public class EffectList {
#SerializedName("effects_id")
#Expose
private String effectsId;
#SerializedName("effects_name")
#Expose
private String effectsName;
//GETTERS AND SETTERS
}
MyContactAdapter2.java
public class MyContactAdapter2 extends BaseAdapter {
ArrayList<Map<String, List<EffectList>>> contactList;
Context context;
private LayoutInflater mInflater;
public MyContactAdapter2(Context context, ArrayList<Map<String, List<EffectList>>> data) {
this.context = context;
this.mInflater = LayoutInflater.from(context);
contactList = data;
}
#Override
public int getCount() {
return 0;
}
#Override
public List<HashMap<String, List<EffectList>>> getItem(int position) {
return (List<HashMap<String, List<EffectList>>>) contactList.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder1 vh1;
if (convertView == null) {
View view = mInflater.inflate(R.layout.get_layout_row_view, parent, false);
vh1 = ViewHolder1.create((RelativeLayout) view);
view.setTag(vh1);
} else {
vh1 = (ViewHolder1) convertView.getTag();
}
EffectList item = (EffectList) getItem(position);
// vh.textViewName.setText(item.getEffectsId());
vh1.textViewName.setText(item.getEffectsName());
vh1.textViewEmail.setText(item.getEffectsId());
// Picasso.with(context).load(item.getProfilePic()).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(vh.imageView);
return vh1.rootView;
}
private static class ViewHolder1 {
public final RelativeLayout rootView;
public final ImageView imageView;
public final TextView textViewName;
public final TextView textViewEmail;
private ViewHolder1(RelativeLayout rootView, ImageView imageView, TextView textViewName, TextView textViewEmail) {
this.rootView = rootView;
this.imageView = imageView;
this.textViewName = textViewName;
this.textViewEmail = textViewEmail;
}
public static MyContactAdapter2.ViewHolder1 create(RelativeLayout rootView) {
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
TextView textViewEmail = (TextView) rootView.findViewById(R.id.textViewEmail);
return new MyContactAdapter2.ViewHolder1(rootView, imageView, textViewName, textViewEmail);
}
}
}
Is there anything wrong in MyContactAdapter2?
I think you should change this method
#Override
public int getCount() {
return contactList.size();
}
Hope This Help
Have a look at this
I am also having same problem regarding parsing with GSON, but achievd by making StringRequest<> instead of GSONRequest<>
Please check my answer.
You can create POJO Model class from JSON from this website
http://www.jsonschema2pojo.org/
I made this from your json! though your json should be simpler !
-----------------------------------com.example.EffectList.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class EffectList {
#SerializedName("4")
#Expose
private List<com.example._4> _4 = null;
#SerializedName("1")
#Expose
private List<com.example._1> _1 = null;
public List<com.example._4> get4() {
return _4;
}
public void set4(List<com.example._4> _4) {
this._4 = _4;
}
public List<com.example._1> get1() {
return _1;
}
public void set1(List<com.example._1> _1) {
this._1 = _1;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("effect_list")
#Expose
private List<EffectList> effectList = null;
public List<EffectList> getEffectList() {
return effectList;
}
public void setEffectList(List<EffectList> effectList) {
this.effectList = effectList;
}
}
-----------------------------------com.example._1.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _1 {
#SerializedName("effects_id")
#Expose
private String effectsId;
#SerializedName("effects_name")
#Expose
private String effectsName;
public String getEffectsId() {
return effectsId;
}
public void setEffectsId(String effectsId) {
this.effectsId = effectsId;
}
public String getEffectsName() {
return effectsName;
}
public void setEffectsName(String effectsName) {
this.effectsName = effectsName;
}
}
-----------------------------------com.example._4.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _4 {
#SerializedName("effects_id")
#Expose
private String effectsId;
#SerializedName("effects_name")
#Expose
private String effectsName;
public String getEffectsId() {
return effectsId;
}
public void setEffectsId(String effectsId) {
this.effectsId = effectsId;
}
public String getEffectsName() {
return effectsName;
}
public void setEffectsName(String effectsName) {
this.effectsName = effectsName;
}
}
Related
I bought a movie app from Codecanyon. The support team screwed up, they can't fix the problem. I'm having trouble with letters like ç, ş, ğ, ü (Space) while searching for movies in the app. When I add a space between a two-word movie, all movies come off the screen.
https://youtube.com/shorts/Z9SOkbIa5kk
Home.java
Searchlistaddepter.java
Searchlist.java
Below
----------------------------------------------------------------------------
HOME.java
---------------------------------------------------------------------------
void searchContent(String text) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.GET, AppConfig.url +"searchContent/"+text+"/"+onlyPremium, response -> {
if(!response.equals("No Data Avaliable") ) {
JsonArray jsonArray = new Gson().fromJson(response, JsonArray.class);
List<SearchList> searchList = new ArrayList<>();
for (JsonElement r : jsonArray) {
JsonObject rootObject = r.getAsJsonObject();
int id = rootObject.get("id").getAsInt();
String name = rootObject.get("name").getAsString();
String year = "";
if(!rootObject.get("release_date").getAsString().equals("")) {
year = getYearFromDate(rootObject.get("release_date").getAsString());
}
String poster = rootObject.get("poster").getAsString();
int type = rootObject.get("type").getAsInt();
int status = rootObject.get("status").getAsInt();
int contentType = rootObject.get("content_type").getAsInt();
if (status == 1) {
searchList.add(new SearchList(id, type, name, year, poster, contentType));
}
}
RecyclerView searchLayoutRecyclerView = findViewById(R.id.Search_Layout_RecyclerView);
SearchListAdepter myadepter = new SearchListAdepter(context, searchList);
searchLayoutRecyclerView.setLayoutManager(new GridLayoutManager(context, 3));
searchLayoutRecyclerView.setAdapter(myadepter);
} else {
View bigSearchLottieAnimation = findViewById(R.id.big_search_Lottie_animation);
RecyclerView searchLayoutRecyclerView = findViewById(R.id.Search_Layout_RecyclerView);
bigSearchLottieAnimation.setVisibility(View.VISIBLE);
searchLayoutRecyclerView.setVisibility(View.GONE);
}
}, error -> {
// Do nothing because There is No Error if error It will return 0
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("x-api-key", AppConfig.apiKey);
return params;
}
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put("search",text);
params.put("onlypremium", String.valueOf(onlyPremium));
return params;
}
};
queue.add(sr);
}
---------------------------------------------------------
SEARCHLİSTADDEPTER.Java
----------------------------------------------------------
package com.xxxx.android.adepter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.xxxx.android.AppConfig;
import com.xxxx.android.R;
import com.xxxx.android.MovieDetails;
import com.xxxx.android.list.SearchList;
import com.xxxx.android.WebSeriesDetails;
import java.util.List;
public class SearchListAdepter extends RecyclerView.Adapter<SearchListAdepter.MyViewHolder> {
private Context mContext;
private List<SearchList> mData;
Context context;
public SearchListAdepter(Context mContext, List<SearchList> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public SearchListAdepter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(AppConfig.contentItem,parent,false);
return new SearchListAdepter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchListAdepter.MyViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.setTitle(mData.get(position));
holder.setYear(mData.get(position));
holder.setImage(mData.get(position));
holder.IsPremium(mData.get(position));
holder.Movie_Item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mData.get(position).getContent_Type() == 1) {
Intent intent = new Intent(mContext, MovieDetails.class);
intent.putExtra("ID", mData.get(position).getID());
mContext.startActivity(intent);
} else if(mData.get(position).getContent_Type() == 2) {
Intent intent = new Intent(mContext, WebSeriesDetails.class);
intent.putExtra("ID", mData.get(position).getID());
mContext.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Title;
TextView Year;
ImageView Thumbnail;
View Premium_Tag;
CardView Movie_Item;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Title = (TextView) itemView.findViewById(R.id.Movie_list_Title);
Year = (TextView) itemView.findViewById(R.id.Movie_list_Year);
Thumbnail = (ImageView) itemView.findViewById(R.id.Movie_Item_thumbnail);
Premium_Tag = (View) itemView.findViewById(R.id.Premium_Tag);
Movie_Item = itemView.findViewById(R.id.Movie_Item);
}
void IsPremium(SearchList type) {
if(type.getType() == 1) {
Premium_Tag.setVisibility(View.VISIBLE);
} else {
Premium_Tag.setVisibility(View.GONE);
}
}
void setTitle(SearchList title_text) {
Title.setText(title_text.getTitle());
}
void setYear(SearchList year_text) {
Year.setText(year_text.getYear());
}
void setImage(SearchList Thumbnail_Image) {
Glide.with(context)
.load(Thumbnail_Image.getThumbnail())
.placeholder(R.drawable.thumbnail_placeholder)
.into(Thumbnail);
}
}
}
------------------------------------------
SEARCHLİST.Java
---------------------------------------
package com.xxxx.android.list;
public class SearchList {
private int ID;
private int Type;
private String Title;
private String Year;
private String Thumbnail;
private int Content_Type;
public SearchList(int ID, int type, String title, String year, String thumbnail, int content_Type) {
this.ID = ID;
Type = type;
Title = title;
Year = year;
Thumbnail = thumbnail;
Content_Type = content_Type;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getType() {
return Type;
}
public void setType(int type) {
Type = type;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getYear() {
return Year;
}
public void setYear(String year) {
Year = year;
}
public String getThumbnail() {
return Thumbnail;
}
public void setThumbnail(String thumbnail) {
Thumbnail = thumbnail;
}
public int getContent_Type() {
return Content_Type;
}
public void setContent_Type(int content_Type) {
Content_Type = content_Type;
}
public void onResponse(String response) {
try{ byte[] u = response.toString().getBytes("ISO-8859-1");
response = new String(u, "UTF-8");
}
catch (Exception e){
e.printStackTrace();
}
}
}
I am retrieving Cloud Firesstore data in (Modelo) and I'm trying to pass these variables from the constructor "Modelo" to fragment (DescDenuncia) using a adapter (Adapter) but to do that I need to get the context to pass using the .getSupportFragmentManager() I've already tried use "AppCompatActivity activity = (AppCompatActivity) view.getContext();", but my app crashes every time, and is necessary to use a Context in the getSupportFragmentManager() to it works. I truly don't know what I should do, please someone answer me.
Modelo
package com.example.safe;
public class Modelo {
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
public Modelo() {
}
public Modelo(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSetor() {
return setor;
}
public void setSetor(String setor) {
this.setor = setor;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getRisco() {
return risco;
}
public void setRisco(String risco) {
this.risco = risco;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getPrazo() {
return prazo;
}
public void setPrazo(String prazo) {
this.prazo = prazo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getResolucao() {
return resolucao;
}
public void setResolucao(String resolucao) {
this.resolucao = resolucao;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
Adapter
package com.example.safe;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
//Vinculando o reclycler view ao firestore
public class Adapter extends FirestoreRecyclerAdapter<Modelo, Adapter.myviewholder> {
public Adapter(#NonNull FirestoreRecyclerOptions<Modelo> options) {
super(options);
}
//Sobrescrevendo o método
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull final Modelo model) {
//Associando os itens do atalho ocorrências
holder.IDText.setText(model.getID());
holder.tipoText.setText(model.getTipo());
Glide.with(holder.img1.getContext()).load(model.getImg()).into(holder.img1);
///////////////////////////////////////THE PROBLEM IS HERE///////////////////////////////////////////
holder.RLAYOUT.setOnClickListener(new View. OnClickListener() {
#Override
public void onClick(View view) {
.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
model.getEmpresa(),
model.getArea(),
model.getSetor(),
model.getTipo(),
model.getRisco(),
model.getImg(),
model.getData(),
model.getPrazo(),
model.getDesc(),
model.getResolucao(),
model.getID()
)).addToBackStack(null).commit();
}
});
//////////////////////////////////////////////////////////////////////////////////////////////////////
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view);
}
//Coneção do reclycler view com essa classe
public class myviewholder extends RecyclerView.ViewHolder {
//Variáveis do modelo atalho
TextView tipoText, IDText;
RelativeLayout RLAYOUT;
ImageView img1;
private Context context;
//Associando os objetos ao modelo atalho
public myviewholder(#NonNull View itemView) {
super(itemView);
tipoText = itemView.findViewById(R.id.txtTipo);
img1 = itemView.findViewById(R.id.imageView);
IDText = itemView.findViewById(R.id.txtModeloID);
RLAYOUT = itemView.findViewById(R.id.RLlayout);
}
}
}
Add a Context parameter in your myviewholder constructor that will accept an additional context argument
public class myviewholder extends RecyclerView.ViewHolder {
private Context context;
...
...
public myviewholder(#NonNull View itemView, Context context) {
super(itemView);
this.context = context
}
and in your onCreateViewHolder simply call parent.getContext() and pass it to the construction of the view holder.
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view, parent.getContext()); // add <- this
Also please practice naming classes with Uppercase Initials
This is the Data model
package com.basirahmad.qpaisa.data_model;
public class Banner_data_model {
private String banner_url_com_logo;
private String banner_txt_title;
private String banner_txt_name;
private String banner_txt_description;
private String banner_url_banner;
private String banner_date_publish;
private String banner_date_expire;
private String banner_max_view;
private int banner_com_id;
private int banner_schedual_id;
private int banner_id;
public String getBanner_url_com_logo() {
return banner_url_com_logo;
}
public void setBanner_url_com_logo(String banner_url_com_logo) {
this.banner_url_com_logo = banner_url_com_logo;
}
public String getBanner_txt_title() {
return banner_txt_title;
}
public void setBanner_txt_title(String banner_txt_title) {
this.banner_txt_title = banner_txt_title;
}
public String getBanner_txt_name() {
return banner_txt_name;
}
public void setBanner_txt_name(String banner_txt_name) {
this.banner_txt_name = banner_txt_name;
}
public String getBanner_txt_description() {
return banner_txt_description;
}
public void setBanner_txt_description(String banner_txt_description) {
this.banner_txt_description = banner_txt_description;
}
public String getBanner_url_banner() {
return banner_url_banner;
}
public void setBanner_url_banner(String banner_url_banner) {
this.banner_url_banner = banner_url_banner;
}
public String getBanner_date_publish() {
return banner_date_publish;
}
public void setBanner_date_publish(String banner_date_publish) {
this.banner_date_publish = banner_date_publish;
}
public String getBanner_date_expire() {
return banner_date_expire;
}
public void setBanner_date_expire(String banner_date_expire) {
this.banner_date_expire = banner_date_expire;
}
public String getBanner_max_view() {
return banner_max_view;
}
public void setBanner_max_view(String banner_max_view) {
this.banner_max_view = banner_max_view;
}
public int getBanner_com_id() {
return banner_com_id;
}
public void setBanner_com_id(int banner_com_id) {
this.banner_com_id = banner_com_id;
}
public int getBanner_schedual_id() {
return banner_schedual_id;
}
public void setBanner_schedual_id(int banner_schedual_id) {
this.banner_schedual_id = banner_schedual_id;
}
public int getBanner_id() {
return banner_id;
}
public void setBanner_id(int banner_id) {
this.banner_id = banner_id;
}
}
This is the Adapter Class
package com.basirahmad.qpaisa.adapter;
public class Banner_adapter_con extend
RecyclerView.Adapter<Banner_adapter_con.BannerViewHolder> {
private Context context;
private List<Banner_data_model> banner_data_models;
//the class canstractor;
public Banner_adapter_con(Context context, List<Banner_data_model>banner_data_models ){
this.context = context;
this.banner_data_models = banner_data_models;
}
#Override
public BannerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.banner_view,parent,false);
return new BannerViewHolder(view);
}
#Override
public void onBindViewHolder(BannerViewHolder holder, int position) {
Banner_data_model data_model = banner_data_models.get(position);
holder.company_logo.setImageURI(Uri.parse(data_model.getBanner_url_com_logo()));
holder.title.setText(data_model.getBanner_txt_title());
holder.name.setText(data_model.getBanner_txt_name());
holder.description.setText(data_model.getBanner_txt_description());
holder.banner.setImageURI(Uri.parse(data_model.getBanner_url_banner()));
}
#Override
public int getItemCount() {
return banner_data_models.size();
}
public class BannerViewHolder extends RecyclerView.ViewHolder{
private ImageView company_logo;
private ImageView banner;
private TextView title;
private TextView name;
private ReadMoreTextView description;
public BannerViewHolder(View itemView) {
super(itemView);
company_logo = (ImageView) itemView.findViewById(R.id.img_company_logo);
banner = (ImageView) itemView.findViewById(R.id.img_banner);
title = (TextView) itemView.findViewById(R.id.banner_txt_title);
name = (TextView) itemView.findViewById(R.id.banner_txt_name);
description = (ReadMoreTextView) itemView.findViewById(R.id.banner_txt_description);
}
}
}
This is the Fragment Class
package com.basirahmad.qpaisa.Fragment;
public class Banner_fragment extends Fragment {
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.banner_fragment,container,false);
Banner_data_server banner_data_server = new Banner_data_server(this.getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.banner_fragment);
banner_data_server.getBanner(new Banner_data_server.OnbannerRecevid() {
#Override
public void onRecevid(List<Banner_data_model> banner_data_models) {
Banner_adapter banner_adapter =new Banner_adapter(getActivity(),banner_data_models);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
recyclerView.setAdapter(banner_adapter);
}
});
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
It will not throw any error. It just means when you initialized your RecyclerView you've not set its adapter,
IF you still want to remove this warning, you can call
recyclerview.setAdapter(adapter)
just after its initialization. will remove the warning.
how derar this is the class the get data from server i forgot this class to add to the quastion.
enter code here the class code
package com.basirahmad.qpaisa.connect_to_server;
public class Banner_data_server {
private Context context;
public Banner_data_server(Context context){
this.context = context;
}
public void getBanner(final OnbannerRecevid onbannerRecevid){
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, Url_of_server.urlReadBanner, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<Banner_data_model> banner_data_models = new ArrayList<>();
for (int i =0;i<response.length();i++){
Banner_data_model data_model = new Banner_data_model();
try {
JSONObject jsonObject =response.getJSONObject(i);
data_model.setBanner_id(jsonObject.getInt("Banner_id"));
data_model.setBanner_txt_name(jsonObject.getString("Banner_name"));
data_model.setBanner_txt_description(jsonObject.getString("Banner_description"));
data_model.setBanner_url_banner(jsonObject.getString("location"));
data_model.setBanner_schedual_id(jsonObject.getInt("id"));
data_model.setBanner_date_publish(jsonObject.getString("date_publish"));
data_model.setBanner_date_expire(jsonObject.getString("expire_date"));
data_model.setBanner_com_id(jsonObject.getInt("com_id"));
data_model.setBanner_url_com_logo(jsonObject.getString("logo"));
banner_data_models.add(data_model);
} catch (JSONException e) {
e.printStackTrace();
}
}
onbannerRecevid.onRecevid(banner_data_models);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(arrayRequest);
}
public interface OnbannerRecevid{
void onRecevid(List<Banner_data_model> banner_data_models);
}
}
I'm building on a tutorial I did in which I created a RecyclerView screen with cards with selectable options. I want one of the selectable options to bring the user to a new activity that has more information & options about the card they selected. My problem is when I try to transfer traits of that specific card to the next SlideViewActivity.java activity I am unable to successfully do so. I tried transforming my list into an array then sending that, but I keep obtaining a null value (which could be due to my syntax for all I know).
Any clarification & guidance would be appreciated, let me know if you would want any of the other code as well.
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private Context mContext;
private List<Properties> dogList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
public Adapter(Context mContext, List<Properties> dogList) {
this.mContext = mContext;
this.dogList = dogList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Properties dog = dogList.get(position);
holder.title.setText(dog.getName());
// loading dog cover using Glide library
Glide.with(mContext).load(dog.getThumbnail()).into(holder.thumbnail);
holder.overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupMenu(holder.overflow);
}
});
}
/**
* Showing popup menu when tapping on icon
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_add_favourite:
Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_more_info:
Intent slideStart = new Intent(mContext, SlideViewActivity.class);
String[] dogArray = new String[dogList.size()];
slideStart.putExtra("List", dogArray);
Log.e("putting extra", String.valueOf(dogArray[0]));
//TODO:MAKE NAME TRANSFERS WORK
mContext.startActivity(slideStart);
return true;
default:
}
return false;
}
}
Adding Properties.java:
public class Properties {
private String name;
private String info;
private int thumbnail;
public Properties() {
}
public Properties(String name, String info, int thumbnail) {
this.name = name;
this.info = info;
this.thumbnail = thumbnail;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void getInfo(String info) {
this.info = info;
}
public int getThumbnail() {
return thumbnail;
}
public void setThumbnail(int thumbnail) {
this.thumbnail = thumbnail;
}
}
You can pass ArrayList<T>, if T is Serializable.
for example:
ArrayList<String> list = new ArrayList<String>();
intent.putExtra("list", list);
use getSerializableExtra to extract data
Your array is dogList.size()-d null values.
String[] dogArray = new String[dogList.size()];
slideStart.putExtra("List", dogArray);
You should see null logged here.
Log.e("putting extra", String.valueOf(dogArray[0]));
It's not clear what type of class you have for Properties, but if it is your class, and not java.util.Properties, you should implement Parcelable on that class, then you'd have
intent.putParcelableArrayList("List", dogList)
(Tip: You should rename that class to Dog to avoid confusion for yourself and others)
But if you are just worried about getting null, case matters. You put a key="List", so make sure you aren't getting key="list" or anything else but "List"
Two ways possible for that::
First
While Sending the list using intent::
Intent slideStart = new Intent(mContext, SlideViewActivity.class);
slideStart.putExtra("List", dogList);
mContext.startActivity(slideStart);
In This just pass the list as is it is ::
But your class Properties should be implements "Serializable"
Now while receiving that intent ::
ArrayList<Properties> dogList =(ArrayList<Properties>) getIntent().getExtras().getSerializable("List");
Second way :: using Library
One library is there for converting string to arraylist & vice versa ,
compile 'com.google.code.gson:gson:2.4'
So, for this while sending list convert that list to string like ::
Type listType = new TypeToken<List<Properties>>() {
}.getType();
String listString=new Gson().toJson(dogList,listType );
pass this simple as string with intent:::
Intent slideStart = new Intent(mContext, SlideViewActivity.class);
slideStart.putExtra("List", listString);
mContext.startActivity(slideStart);
And while getting it back in other activity::
String listString =getIntent().getExtras().getString("List");
Type listType = new TypeToken<List<Properties>>() {}.getType();
List<Properties> list=new Gson().fromJson(listString, listType);
Tell me if need more help..
I have done a similar project I will share my code. Please take a look and if have doubts ping me
DataAdapter.java
package com.example.vishnum.indiavideo;
import android.content.Context;
import android.content.Intent;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}
Video_Details.java
package com.example.vishnum.indiavideo;
public class Video_Details {
private String id;
private String v_id;
private String title;
private String thumb;
public String getId() {
return id;
}
public String getV_id() {
return v_id;
}
public String getTitle() {
return title;
}
public String getThumb() {
return (Constants.urlvideo+v_id+"/0.jpg");
}
public void setId(String id) {
this.id = id;
}
public void setV_id(String v_id) {
this.v_id = v_id;
}
public void setTitle(String title) {
this.title = title;
}
public void setThumb(String v_id) {
this.thumb =Constants.urlvideo+v_id+"/0.jpg";
}
}
I'm tring to retrieve a json, store its data on a class, then show it on a ListView.
I am getting a nullpointerexception and I think it is because I'm making some mistake retrieving the infomation from the array of DaysList.
This is the main fragment, I'm not sure if the array declaration is fine. :
public class MainFragment extends Fragment {
private View view;
private RequestQueue requestQueue;
private WeatherAdapter weatherAdapter;
public WeatherForecast weatherForecast;
public WeatherForecast.DaysList[] daysForecast;
private ListView listview;
String URL = "http://api.openweathermap.org/data/2.5/forecast/daily?q=Rosario,ar&mode=json&units=metric&cnt=3&appid=c8ca9280dc6e2ebeb82e7fa63b2104fb";
String TAG = MainFragment.class.getSimpleName();
public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
public View onCreateView ( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.main_fragment,null);
listview = (ListView) view.findViewById(R.id.lista_forecast);
requestQueue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonWeatherRequest = new JsonObjectRequest(
URL,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
weatherForecast = parseWeatherToJson(response.toString());
daysForecast = weatherForecast.getDays();
weatherAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "On Error!");
}
}
);
requestQueue.add(jsonWeatherRequest);
weatherAdapter = new WeatherAdapter(getContext(), R.layout.listview_item,daysForecast); // This is where i get the nullpointer .
listview.setAdapter(weatherAdapter);
return view;
}
This is my custom adapter:
public class WeatherAdapter extends ArrayAdapter {
Context context;
int layoutResourceId;
WeatherForecast.DaysList[] daysList;
TextView dt;
TextView pressure;
TextView humidity;
public WeatherAdapter (Context context, int layoutResourceId, WeatherForecast.DaysList[] daysList) {
super(context, layoutResourceId, daysList);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.daysList = daysList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
dt = (TextView) row.findViewById(R.id.dt);
pressure = (TextView) row.findViewById(R.id.pressure);
humidity = (TextView) row.findViewById(R.id.humidity);
}
WeatherForecast.DaysList day = daysList[position];
dt.setText(day.getDtString());
pressure.setText(day.getPressureString());
humidity.setText(day.getHumidityString());
return row;
}
}
This is the WeatherForecast class. I only created a few getters to test the funcionality.:
public class WeatherForecast {
public City city;
public int cod;
public float message;
public int cnt;
public DaysList[] dayList;
public int getCnt() {return cnt;}
public String getCod() { return String.valueOf(cod);}
public DaysList[] getDays() { return dayList;}
public class City {
public int id;
public String name;
public Coord coord;
public String country;
public int population;
public String getName() {return name;}
}
public class Coord {
public double lon;
public double lat;
}
public class DaysList {
public int dt;
public Temp temp;
public double pressure;
public int humidity;
public Weather[] weather;
public double speed;
public int deg;
public int clouds;
public String getDtString() {return String.valueOf(dt);}
public String getPressureString() {return String.valueOf(pressure);}
public String getHumidityString() {return String.valueOf(humidity);}
}
public class Temp {
public double day;
public double min;
public double max;
public double night;
public double eve;
public double morn;
}
public class Weather {
public int id;
public String main;
public String description;
public String icon;
}
}
What am I doing wrong retrieving that array?
edit: the parsing method using Gson.
private WeatherForecast parseWeatherToJson(String jsonObject) {
Gson gson = new Gson();
WeatherForecast weather = gson.fromJson(jsonObject, WeatherForecast.class);
return weather;
}