I have a problem I am trying to make (private void Method)work into my Fragment in ( onCreateView ) but it does not work.
As if I put code directly to onCreateView it's work fine without make it into private void().
Example how its not working :
public class classtwst {
public class Status extends Fragment {
private List<List_Data> list;
private RecyclerView rvy;
private MyAdapter adapter;
String id;
private static final String TAG = "Status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.status, container, false);
Intent i = getActivity().getIntent();
final String id = i.getStringExtra("id");
rvy=(RecyclerView)rootView.findViewById(R.id.recyclerview);
rvy.setHasFixedSize(true);
rvy.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
list=new ArrayList<>();
adapter=new MyAdapter(list);
getComment();//--------Here is the problem
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void getComment(){
final String HI ="http://000000000/Cm.php?id=" + id ;
StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray array=jsonObject.getJSONArray("info");
for (int i=0; i<array.length(); i++ ){
JSONObject ob=array.getJSONObject(i);
List_Data listData=new List_Data(ob.getString("namelast")
,ob.getString("contry"));
list.add(listData);
}
rvy.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
}
}
How it works:
public class classtwst {
public class Status extends Fragment {
private List<List_Data> list;
private RecyclerView rvy;
private MyAdapter adapter;
String id;
private static final String TAG = "Status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.status, container, false);
Intent i = getActivity().getIntent();
final String id = i.getStringExtra("id");
rvy=(RecyclerView)rootView.findViewById(R.id.recyclerview);
rvy.setHasFixedSize(true);
rvy.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
list=new ArrayList<>();
adapter=new MyAdapter(list);
final String HI ="http://000000000/Cm.php?id=" + id ;
StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray array=jsonObject.getJSONArray("info");
for (int i=0; i<array.length(); i++ ){
JSONObject ob=array.getJSONObject(i);
List_Data listData=new List_Data(ob.getString("namelast")
,ob.getString("contry"));
list.add(listData);
}
rvy.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
}
So how I can make it work as private void getComment() ?what is the wrong?
You have to pass id to getComment method to make it work as shown below
in onCreateView:
getComment(id);
and in your method:
private void getComment(String id){
//your code
}
Hope this helps
Related
I am working on developing an application that contains (recyclerView ) display member responses.I have a problem after a member posts a new comment the (recyclerView ) is not updated in real time.
How can I update the data (recyclerView ) after entering new data without the user exiting or closing the application؟
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private List<List_Data>list_data;
public MyAdapter(List<List_Data> list_data) {
this.list_data = list_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_data,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
List_Data listData=list_data.get(position);
holder.txtname.setText(listData.gettext());
holder.txtmovie.setText(listData.getmovie_id());
}
#Override
public int getItemCount() {
return list_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView txtname,txtmovie,ImageView;
public ViewHolder(View itemView) {
super(itemView);
txtname=(TextView)itemView.findViewById(R.id.txt_name);
txtmovie=(TextView)itemView.findViewById(R.id.txt_moviename);
}
}
}
public class StatusFragment extends Fragment {
Button btn_send_comment;
EditText ETXT_comment;
String id;
private List<List_Data> list;
private RecyclerView rvy;
private MyAdapter adapter;
ImageView btn_add_comments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.status, container, false);
ETXT_comment = (EditText)rootView.findViewById(R.id.ETXT_comment);
btn_add_comments = (ImageView) rootView.findViewById(R.id.btn_add_comments);
btn_send_comment = (Button) rootView.findViewById(R.id.btn_send_comment);
Intent i = getActivity().getIntent();
final String movie_id = i.getStringExtra("id");
rvy=(RecyclerView)rootView.findViewById(R.id.recyclerview);
rvy.setHasFixedSize(true);
rvy.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
list=new ArrayList<>();
adapter=new MyAdapter(list);
getComment(movie_id);
//----------------Send Commant
btn_send_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String comment_text = ETXT_comment.getText().toString().trim();
if (comment_text.equals("")) {
} else {
//
final String REGISTER_URL = "http://0000000/Comment.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// getComment(movie_id);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
params.put("comment", comment_text);
return params;
}
};
RequestQueue requestQueue = (RequestQueue) Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
}
});
//--------------------
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void getComment(String id){
final String HI ="http://0000000/Cm.php?id=" + id ;
StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray array=jsonObject.getJSONArray("info");
for (int i=0; i<array.length(); i++ ){
JSONObject ob=array.getJSONObject(i);
List_Data listD=new List_Data(ob.getString("comment")
,ob.getString("name"));
list.add(listD);
// adapter.notifyItemRangeChanged(0, list_data.size());
// rv.removeAllViews();
}
rvy.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
}
Also whene I put getComment(movie_id); into onResponse it's work but there are other problem it's show data Repeats in two times For each comment from user.
Did you try to add new comment into your list and then call the statement
adapter.notifyDataSetChanged()
Move rvy.setAdapter(adapter) from getComment() to onViewCreated()
Clear the list at the start of your getComment() method, add this line:
list.clear()
In your code, you appended the same items to this instance of List when you call .add(), hence, repeated elements appear.
After list.add(listD), call adapter.notifyDataSetChanged()
When you return a new comment, you didn't add the RecyclerView adapter list with the new comment. What you just did is updating the fragment list with the new comment, and the adapter has no idea about this list update.
So, modify you adapter to accept a new comment method and update the list with just the new inserted row using notifyItemInserted():
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private List<List_Data>list_data;
public MyAdapter(List<List_Data> list_data) {
this.list_data = list_data;
}
public addComment(List_Data comment) {
this.list_data.add(comment);
notifyItemInserted(list_data.size() - 1); // Updating adapter list
}
// ... rest of code
}
And in your getComment() use the new added adapter method when you get the response.
Notice the change in // <<<<<<<<<<<<<<<< Updating adapter list
private void getComment(String id){
final String HI ="http://0000000/Cm.php?id=" + id ;
StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray array=jsonObject.getJSONArray("info");
for (int i=0; i<array.length(); i++ ){
JSONObject ob=array.getJSONObject(i);
List_Data listD = new List_Data(ob.getString("comment")
,ob.getString("name"));
list.add(listD);
adapter.addComment(listD); // <<<<<<<<<<<<<<<< Updating adapter list
// rv.removeAllViews();
}
rvy.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
finally don't forget to uncomment the usage of the getComment() within the btn_send_comment button listener.
I am trying to pass data Adapter class to TabView Layout. I have used fragment in tab. I want to pass data from adapter to fragment (fragment class for tab).
________________________________________Adapter Class________________________________________________
package com.livediscount.restaurants.Adapter;
public class LiveContestAdapter extends RecyclerView.Adapter<LiveContestAdapter.MyViewHolder> {
Context context;
List<Contest_Data> contest_data;
public LiveContestAdapter(Context context, List<Contest_Data> contest_data) {
this.context=context;
this.contest_data=contest_data;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
context=viewGroup.getContext();
View vh= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_list_win_iphone,viewGroup,false);
MyViewHolder myViewHolder=new MyViewHolder(vh);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final LiveContestAdapter.MyViewHolder myViewHolder, final int i) {
final Contest_Data contest_position = contest_data.get(i);
Picasso.with(context).load(contest_data.get(i).getContestImage()).error(R.drawable.damme).placeholder(R.drawable.damme).into(myViewHolder.img);
myViewHolder.remainSlot.setText(contest_data.get(i).getContestTotal_slot());
myViewHolder.ent_fee.setText(contest_data.get(i).getContestEntry_Fee());
myViewHolder.Booked_Slot.setText(contest_data.get(i).getContestBooked());
final String contest_status = contest_data.get(i).getContestStatus();
String previous_contest = contest_data.get(i).getPrevious_contest();
String winner_announce = contest_data.get(i).getWinner_announce();
}
#Override
public int getItemCount() {
return contest_data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
//name=itemView.findViewById(R.id.totalslot);
img=itemView.findViewById(R.id.imageView2);
htp = itemView.findViewById(R.id.button2);
remainSlot=itemView.findViewById(R.id.tvTotalSlotNumber);
}
}
}
___________________________________________AppCompactActivity______________________________________
public class PrizeBreakup extends AppCompatActivity {
ImageButton back;
TabLayout tabLayout;
ViewPager viewPager;
String contest_id,contest_name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prize_breakup);
back = findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
tabLayout= findViewById(R.id.tabs);
viewPager = findViewById(R.id.container);
PrizeLayoutAdapter adapter = new PrizeLayoutAdapter(getSupportFragmentManager());
adapter.add(new PrizeLayout(),"Prize Breakup");
adapter.add(new WinnerLayout(),"Winners");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
//here
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("contestid1", "contest_id");
editor.apply();
/* Bundle bundle = getIntent().getExtras();
assert bundle!= null;
contest_id = bundle.getString("contest_id");
contest_name = bundle.getString("contest_name");*/
/* Bundle data = new Bundle();
data.putString("contestid1","contest_id");
Fragment argumentFragment = new PrizeLayout();
argumentFragment.setArguments(data);*/
}
}
_____________________________________PrizeLayout Fragment________________________________________
package com.livediscount.restaurants;
public class PrizeLayout extends Fragment {
List<Contest_Data> contest_data;
LiveContestAdapter live_contest_adapter;
private RecyclerView recyclerView;
TextView ContestId;
public static PrizeLayout newInstance() {
return new PrizeLayout();
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.prize_layout, container, false);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String contestid = getActivity().prefs.getString("contestid1", "contestid not found");
String Contest_id = this.getArguments().getString("edttext");
ContestId= view.findViewById(R.id.referral_code);
ContestId.setText(contestid);
return view;
}
}
________________________________________Winner Fragment______________________________________________
package com.livediscount.restaurants;
public class WinnerLayout extends Fragment {
private List<Winner_data> winner_data=new ArrayList<>();
private RecyclerView recyclerView_winner;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container , Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.winner_layout,container,false);
recyclerView_winner = view.findViewById(R.id.Recyclerview_Winner);
if(winner_data!=null)
{
winner_data.clear();
}
Winner_Data();
return view;
}
private void Winner_Data() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = ("http://livediscounts.in/webservices/User_interface/Winner_List?contest_id=\"+razorpayPaymentID+\"");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//progressBar_contest.setVisibility(View.GONE);
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("1")) {
JSONArray jsonArray = jsonObject.getJSONArray("records");
/*for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Winner_data wd = new Winner_data();
cd.setContestId(obj.getString("id"));
cd.setContestName(obj.getString("name"));
cd.setContestImage(obj.getString("prize_1"));
cd.setContestDescription(obj.getString("description"));
cd.setContestType(obj.getString("type"));
cd.setContestEntry_Fee(obj.getString("entry_fee"));
cd.setContestTotal_slot(obj.getString("total_slot"));
cd.setContestTotal_winner(obj.getString("total_winner"));
cd.setContestPrice_Description(obj.getString("price_description"));
cd.setContestPrize_21(obj.getString("prize_21"));
cd.setContestPrize_22(obj.getString("prize_22"));
cd.setContestPrize_31(obj.getString("prize_31"));
cd.setContestPrize_32(obj.getString("prize_32"));
cd.setContestPrize_41(obj.getString("prize_41"));
cd.setContestPrize_42(obj.getString("prize_42"));
cd.setContestPrize_51(obj.getString("prize_51"));
cd.setContestPrize_52(obj.getString("prize_52"));
cd.setContestPrize_61(obj.getString("prize_61"));
cd.setContestPrize_62(obj.getString("prize_62"));
cd.setContestPrize_71(obj.getString("prize_71"));
cd.setContestPrize_72(obj.getString("prize_72"));
cd.setContestStatus(obj.getString("status"));
cd.setContestContest_Note(obj.getString("contest_note"));
cd.setContestStart_date(obj.getString("start_date"));
cd.setContestEnd_date(obj.getString("end_date"));
cd.setContestBooked(obj.getString("booked_slot"));
winner_data.add(wd);
}*/
/*WinnerAdapter winnerAdapter = new WinnerAdapter(getApplicationContext(), winner_data);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_winner.setLayoutManager(llm);
recyclerView_winner.setAdapter(winnerAdapter);*/
} else {
// Toast.makeText(getApplicationContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
//progressBar_contest.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(),"No Data Found",Toast.LENGTH_LONG).show(); ex.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
}
}
);
requestQueue.add(request);
}
}
you can use shared pref using parent activity.
By using below code I am fetching data. When I run it the first time it will show all data. When I insert new data it will be inserted successfully but on going to report page and clicking on that it shows previous data and not the new or updated data.
public class Fragment_Emp_Report extends Fragment {
List<Get_EmpNameAdapter> get_empNameAdapter1;
RecyclerView recyclerView;
ProgressBar progressBar;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String url = "http://ghawadediilip.000webhostapp.com/Services/jsonFetchName.php";
String JSON_NAME = "emp_name";
JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_emp_report,container,false);
fetchEmpName();
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
get_empNameAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView)view.findViewById(R.id.report_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
}
public void fetchEmpName()
{
jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
jsonFetch(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(jsonArrayRequest);
RequestQueue.RequestFinishedListener listener = new RequestQueue.RequestFinishedListener() {
#Override
public void onRequestFinished(Request request) {
recyclerViewadapter.notifyDataSetChanged();
}
};
requestQueue.addRequestFinishedListener(listener);
}
public void jsonFetch(JSONArray array)
{
for (int i=0;i<array.length();i++)
{
Get_EmpNameAdapter get_empNameAdapter2 = new Get_EmpNameAdapter();
JSONObject json=null;
try {
json = array.getJSONObject(i);
get_empNameAdapter2.setEmpname(json.getString(JSON_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setAdapter(recyclerViewadapter);
get_empNameAdapter1.add(get_empNameAdapter2);
}
recyclerViewadapter = new Report_Recyclerview_Adapter(get_empNameAdapter1,getContext());
recyclerView.setAdapter(recyclerViewadapter);
}
}
Your fetchEmpName(); called only one time when onCreateView is called if you want to refetch the date when back from another fragment then you have to call your method again you can achieve that by calling it in onResume.
I have a fragment, the name is galery. in the fragment galery i'll showing a recycleView that contains name list. but i find an error in this script :
LinearLayoutManager llm = new LinearLayoutManager(this);
and this my full code :
public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;
ArrayList<HashMap<String, String>> list_data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) rootView.findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(galery.this);
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
return rootView;
}
}
Try This On Fragment Create Adapter And Model Class And RecyclerView in .xml Class.
public class Event extends Fragment {
RecyclerView recyclerView;
private Event_Adapter event_adapter;
public Event_Model event_model;
public static List<Event_Model> list;
RecyclerView.LayoutManager mLayoutManager;
private static final String FETCH_ID = "id";
private static final String FETCH_NAME = "event_type";
private static final String FETCH_MOBILE = "contact";
private static final String FETCH_DATE = "date";
private static final String FETCH_IMAGE = "uri";
public static final String FETCH_DETAIL = "Your Url";
String type,number,date,uri,id;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_event, container, false);
list = new ArrayList<Event_Model>();
recyclerView = (RecyclerView) v.findViewById(R.id.event_recycler);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
fetchdetails();
return v;
}
private void fetchdetails(){
StringRequest jor = new StringRequest(Request.Method.POST, FETCH_DETAIL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
/* Toast.makeText(getActivity(),response,Toast.LENGTH_LONG).show();*/
try {
JSONArray ja = new JSONArray(response);
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
Integer.parseInt(jsonObject.optString("id").toString());
type = jsonObject.getString(FETCH_NAME);
number = jsonObject.getString(FETCH_MOBILE);
date = jsonObject.getString(FETCH_DATE);
uri = jsonObject.getString(FETCH_IMAGE);
id = jsonObject.getString(FETCH_ID);
event_model = new Event_Model(type,number,date,uri,id);
list.add(event_model);
}
} catch (JSONException e) {
e.printStackTrace();
}
event_adapter= new Event_Adapter(getActivity(), list);
recyclerView.setAdapter(event_adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
RetryPolicy retryPolicy=new DefaultRetryPolicy(60000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jor.setRetryPolicy(retryPolicy);
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jor);
}
}
I did some changes it works fine in my app try it and if any error occurred mention in comment.
public class GalaryFragment extends Fragment {
private RecyclerView recyclerView;
private List<ProductModel> list1;
private ProductModel productMode;
private ProductAdapter productAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frament_galary, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String url = "http://bls.hol.es/read.php";
mRecyclerView = (RecyclerView) view.findViewById(R.id.lvhape);
list1 = new ArrayList<>();
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
cashbackAdapter = new ProductAdapter(getActivity(), list1);
mRecyclerView2.setAdapter(productAdapter);
final ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading......");
dialog.show();
StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(getActivity(),response+"",Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String image = jsonObject.getString("image");
productModel = new ProductModel(id, name, image);
list1.add(productModel);
}
productAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
});
VolleySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
}
ProductAdapter code:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {
private List<ProductModel> list;
private Context mContext;
public ProductAdapter(Context mContext, List<ProductModel> list) {
this.mContext = mContext;
this.list=list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_galary, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final ProductModel productModel=list.get(position);
holder.name.setText(productModel.getName());
Picasso.with(mContext)
.load(productModel.getImage())
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(holder.iv);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public ImageView iv;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
iv = (ImageView) view.findViewById(R.id.image);
}
}
}
PoductModel code:
public class ProductModel {
String id;
String name;
String image;
public nameModel(String id, String name, String image) {
this.id = id;
this.name = name;
this.image = image;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
VolleySingleton class:
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) getView().findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(gallary.getContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(galery.this);
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
return rootView;
}
onCreate() will be called before onCreateView() methods so getView() will return null
Try like this
public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;
ArrayList<HashMap<String, String>> list_data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
return rootView;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) view.findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(getActivity());
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
}
I'm trying to retrieve json data using JsonArrayRequest.Here's my code for doing that
public class QuestionDetailFragment extends Fragment {
private static final String url = "http://10.0.2.2:80/forumtest/readquestion.php?format=json";
private String data;
RequestQueue requestQueue;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question_details_layout, container, false);
readQuestionDetails();
Log.d("user","data:"+data);
return view;
}
private void readQuestionDetails() {
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i=0;i<response.length();i++) {
JSONObject jsonObject = response.getJSONObject(i);
data=jsonObject.getString("user");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("user",e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("user", error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
}
The problem is that when i use data variable inside the loop it returns the required value, but whenever i try to use the data variable outside the loop(let's say when i use data from onCreateView) it returns null value.
Thats because the JsonArrayRequest is being added to the volley queue which executes task asynchronously. So even though you are calling the Log.d("tag","data:"+data); after readQuestionDetails() the request has not executed yet, meaning data is null.
Something like this will work:
public class QuestionDetailFragment extends Fragment {
private static final String url = "http://10.0.2.2:80/forumtest/readquestion.php?format=json";
private String data;
RequestQueue requestQueue;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question_details_layout, container, false);
readQuestionDetails();
return view;
}
private void readQuestionDetails() {
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i=0;i<response.length();i++) {
JSONObject jsonObject = response.getJSONObject(i);
data=jsonObject.getString("user");
printData(data);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("user",e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("user", error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
private void printData(String data){
Log.d("user","data:"+data);
}
}