Error: In BackgroundTask i get the data in arraylist in try block,but after when i reach after errorListener(), my arrayList becomes null. In LogCat i found these problem.How i solve this problem..??
package com.example.rahul.volley_jarray;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
public class DisplayList extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Contact> arrayList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list);
recyclerView= (RecyclerView) findViewById(R.id.recylerView);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
BackgroundTask backgroundTask=new BackgroundTask(DisplayList.this);
arrayList=backgroundTask.getList();
Log.d("dispaly Array List",""+arrayList.toString());
adapter=new RecyclerAdapter(arrayList);
Log.d("My adapter",arrayList.toString());
recyclerView.setAdapter(adapter);
}
}
Error: at this place. BackgroundTask
package com.example.rahul.volley_jarray;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by rahul on 7/4/2016.
*/
public class BackgroundTask {
Context context;
ArrayList<Contact> arrayList=new ArrayList<>();
String str_url="https://raw.githubusercontent.com/ianbar20/JSON-Volley-Tutorial/master/Example-JSON-Files/Example-Array.JSON";
String data="";
public BackgroundTask(Context context)
{
this.context=context;
}
public ArrayList<Contact> getList()
{
final JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET, str_url, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("My Json",response.toString());
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
JSONObject jsonObject1 = jsonObject.getJSONObject("phone");
Contact contact = new Contact(jsonObject.getString("name"), jsonObject.getString("email"), jsonObject1.getString("home"));
Log.d("contact", "" + contact.toString());
arrayList.add(contact);
Log.d("arrayList" + count, "" + arrayList.toString());
count++;
} catch (JSONException e) {
e.printStackTrace();
Log.d("Mytag", e.toString());
}
Log.d("arrayList in while" + count, "" + arrayList.toString());
Log.d("arrayList2" + count, "" + arrayList.toString());
if (arrayList.toString() == null) {
Log.d("if first", "null");
} else {
Log.d("else first", "not null");
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error...!!!",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
Log.d("final arrayList",""+arrayList.toString());
//return arrayList;
if(arrayList.toString()==null)
{
Log.d("if second","null");
}
else {
Log.d("else second","not null");
}
Log.d("JsonArray Request",""+jsonArrayRequest.toString());
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
//
return arrayList;
}
}
//MySinglton Class
package com.example.rahul.volley_jarray;
import android.content.Context;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
/**
* Created by rahul on 7/4/2016.
*/
public class MySingleton {
private static MySingleton mInstance;
private static Context mCtx;
private RequestQueue requestQueue;
private MySingleton(Context context) {
mCtx = context;
requestQueue = getRequestQueue();
Log.d("request queue", "" + requestQueue.toString());
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
Log.d("mInstaces", "" + mInstance);
return mInstance;
}
public <T> void addToRequestQueue(Request<T> request) {
Log.d("request",""+request.toString());
requestQueue.add(request);
Log.d("now request queue",""+requestQueue.toString());
}
}
Volley does async requests. When you check for arrayList it hasn't finished yet (actually it's not even in the queue yet), that's why it is null (actually should be empty since you init it in the field already, not null).
You can use a custom listener, pass it into the request class and call it onResponse.
Some pseudo code to clarify:
//define this interface in background task and implement it in caller activity
public interface CustomReqFinished(){
public void onCustomReqFinished(ArrayList list){}
}
//in backgroundtask constructor store the activity you pass as follows
listener = (CustomReqFinished) activity; //set Activity as param instead of context
//in onResponse do this as last step
listener.onCustomReqFinished(arrayList);
EDIT to clarify as requested. In DisplayList modify as follows:
public class DisplayList extends AppCompatActivity implements CustomReqFinished {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Contact> arrayList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list);
recyclerView= (RecyclerView) findViewById(R.id.recylerView);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
BackgroundTask backgroundTask=new BackgroundTask(this);
backgroundTask.getList();
}
#Override
public void onCustomReqFinished(ArrayList<Contact> list) {
Log.d("dispaly Array List",""+list.toString());
adapter=new RecyclerAdapter(list);
recyclerView.setAdapter(adapter);
}
}
In backgroundTask modify as follows:
public class BackgroundTask {
public interface CustomReqFinished{
public void onCustomReqFinished(ArrayList<Contact> list);
}
Context context;
CustomReqFinished listener;
ArrayList<Contact> arrayList=new ArrayList<>();
String str_url="https://raw.githubusercontent.com/ianbar20/JSON-Volley-Tutorial/master/Example-JSON-Files/Example-Array.JSON";
String data="";
public BackgroundTask(Activity activity)
{
this.context = activity;
this.listener = (CustomReqFinished) activity;
}
public void getList()
{
final JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(str_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("My Json",response.toString());
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
JSONObject jsonObject1 = jsonObject.getJSONObject("phone");
Contact contact = new Contact(jsonObject.getString("name"), jsonObject.getString("email"), jsonObject1.getString("home"));
Log.d("contact", "" + contact.toString());
arrayList.add(contact);
Log.d("arrayList" + count, "" + arrayList.toString());
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
listener.onCustomReqFinished(arrayList);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error...!!!",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}
}
Related
I will encode user input into a single URL, I use Uri.encode but error response remains 400. how to make the encode work?
the result is that "space" is replaced with "%20" but the response still fails
And this is my code.,
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
Any help would be appreciated.
Modify your code like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
getJobs(""); //get your data as it is
OnQuerySubmit();
return view;
}
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
getJobs(query);
return false;
}
});
}
public void getJobs(final String query) {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, AppConfig.URL_GETJOBS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "onResponse: " + response);
try {
JSONObject jsonObject=new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if (!error) {
jobList.clear();
JSONArray transaksiArray = jsonObject.JSONArray("transaksi");
....
....
....
jobList.add(job);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(Tag, error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
if(!TextUtils.isEmpty(query){
map.put("title", query);
}else{}
return map;
}
};
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
package com.mimdudin.carekkerje.Activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.mimdudin.carekkerje.Adapter.HomeRecyclerViewAdapter;
import com.mimdudin.carekkerje.Helper.AppController;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import com.mimdudin.carekkerje.Util.AppConfig;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static com.android.volley.VolleyLog.TAG;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private HomeRecyclerViewAdapter homeRecyclerViewAdapter;
private List<Job> jobList;
private RequestQueue queue;
private MaterialSearchView searchView;
private ProgressDialog progressDialog;
private SharedPreferences sharedPreferences;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance() {
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
jobList = getJobs(AppConfig.URL_GETJOBS);
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
homeRecyclerViewAdapter.notifyDataSetChanged();
sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
OnQuerySubmit();
return view;
}
public void OnQuerySubmit(){
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
super.onCreateOptionsMenu(menu, inflater);
}
public void showDialog() {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
public void hideDialog(){
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
HomeRecyclerviewAdapter.java
package com.mimdudin.carekkerje.Adapter;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mimdudin.carekkerje.Activities.HomeFragment;
import com.mimdudin.carekkerje.Activities.HomeFragmentDetail;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import java.util.List;
/**
* Created by master on 12/12/17.
*/
public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<HomeRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Job> jobList;
public HomeRecyclerViewAdapter(Context context, List<Job> jobs){
this.context = context;
jobList = jobs;
}
#Override
public HomeRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.home_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(HomeRecyclerViewAdapter.ViewHolder holder, int position) {
Job job = jobList.get(position);
holder.title.setText(job.getTitle());
holder.namaPerusahaan.setText(job.getNamaPerusahaan());
holder.kriteria_1.setText(job.getKriteria_1());
holder.kriteria_2.setText(job.getKriteria_2());
holder.kriteria_3.setText(job.getKriteria_3());
holder.gaji.setText(job.getGaji());
holder.lokasi.setText(job.getLokasi());
holder.tanggal.setText(job.getTanggal());
String img_logoLink = job.getImg_logo();
Glide.with(context)
.load(img_logoLink) // URL
.apply(new RequestOptions().placeholder(android.R.drawable.ic_dialog_info)
.error(android.R.drawable.ic_dialog_alert).centerCrop().dontAnimate()
// .centerCrop(), .crossFade(), .thumbnail(), .dontAnimate(), .dontTransform() BitmapTransformation(.circleCrop())
)
.into(holder.img_logo); //TARGET GAMBAR YANG NAK DIUBAH
}
#Override
public int getItemCount() {
return jobList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView title;
TextView namaPerusahaan;
TextView lokasi;
TextView kriteria_1;
TextView kriteria_2;
TextView kriteria_3;
TextView gaji;
ImageView img_logo;
TextView tanggal;
public ViewHolder(final View itemView, final Context ctx) {
super(itemView);
context = ctx;
title = itemView.findViewById(R.id.titleID);
namaPerusahaan = itemView.findViewById(R.id.namaPerusahaanID);
kriteria_1 = itemView.findViewById(R.id.satuTv);
kriteria_2 = itemView.findViewById(R.id.duaTv);
kriteria_3 = itemView.findViewById(R.id.tigaTv);
gaji = itemView.findViewById(R.id.gajiID);
lokasi = itemView.findViewById(R.id.lokasiID);
img_logo = itemView.findViewById(R.id.img_logoID);
tanggal = itemView.findViewById(R.id.tanggalID);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HomeFragmentDetail fragmentDetail = new HomeFragmentDetail();
Bundle bundle = new Bundle();
Job job = jobList.get(getAdapterPosition());
bundle.putSerializable("job", job);
fragmentDetail.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
android.support.v4.app.FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.replace(R.id.frame_fragmenthome, fragmentDetail);
fragmentTransaction.commit();
//// Intent intent = new Intent(context, HomeDetailActivity.class);
//// intent.putExtra("job", job);
//// ctx.startActivity(intent);
}
});
}
}
}
HomeFragmentDetail.java
package com.mimdudin.carekkerje.Activities;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
*/
public class HomeFragmentDetail extends Fragment {
private TextView tvDeskripsi;
private TextView tvIndustri;
public HomeFragmentDetail() {
// Required empty public constructor
}
public static HomeFragmentDetail newInstance(){
HomeFragmentDetail homeFragmentDetail = new HomeFragmentDetail();
return homeFragmentDetail;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home_fragment_detail, container, false);
tvDeskripsi = view.findViewById(R.id.tvDeskripsi);
tvIndustri = view.findViewById(R.id.tvIndustri);
Bundle bundle = getArguments();
Job job = (Job) bundle.getSerializable("job");
String PostID = job.getId_post();
String titleID = job.getTitle();
tvDeskripsi.setText(PostID);
tvIndustri.setText(titleID);
return view;
// DataHolder dataholder=new DataHolder("1","TestName");
// Bundle bundle=new Bundle();
// bundle.putSerializable("obj",dataholder);
// Fragment fragment=new FragmentB();
// fragment.setArguments(bundle);
// fragmentManager = getActivity(). getSupportFragmentManager();
// fragmentTransaction = fragmentManager .beginTransaction();
// fragmentTransaction.add(R.id.container, fragment);
// fragmentTransaction.commit();
//Job job = (Job) getIntent.getSerializableExtra("job");
// Bundle bundle = getArguments();
// Job job = (Job) bundle.getSerializable("job");
// String jobID = job.getId_post();
// String titleID = job.getTitle();
}
}
AppConfig.java
package com.mimdudin.carekkerje.Util;
/**
* Created by master on 10/12/17.
*/
public class AppConfig {
public static final String URL = "http://192.168.43.142/Carekkerje/v1";
public static final String URL_REGISTER = URL + "/daftarUser";
public static final String URL_LOGIN = URL + "/loginUser";
public static final String URL_GETJOBS = URL + "/seluruhLowongan/";
public static final String URL_GETJOBSS = URL + "/seluruhLowongan/:title";
}
I am learning about android swipe refresh layout. I post runabble on swipeRefreshLayout "setRefreshing(true)", then on method onRefresh i wrote fetchMovie(). But fetchMovie() didn't called. How to fix it?
package com.example.zihadrizkyef.belajarswiperefresh;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.zihadrizkyef.belajarswiperefresh.app.MyApplication;
import com.example.zihadrizkyef.belajarswiperefresh.helper.Movie;
import com.example.zihadrizkyef.belajarswiperefresh.helper.SwipeListAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private String TAG = MainActivity.class.getSimpleName();
private String URL_TOP_250 = "http://api.androidhive.info/json/imdb_top_250.php?offset=";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<Movie>();
adapter = new SwipeListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "aaaaaaaaaa", Toast.LENGTH_SHORT).show();
}
});
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
#Override
public void onRefresh() {
fetchMovie();
}
private void fetchMovie() {
swipeRefreshLayout.setRefreshing(true);
String url = URL_TOP_250+offSet;
JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println(TAG+response.toString());
if (response.length() > 0) {
for (int i=0; i<=response.length(); i++) {
try {
JSONObject movieObject = response.getJSONObject(i);
int rank = movieObject.getInt("rank");
String title = movieObject.getString("title");
Movie movie = new Movie(rank, title);
movieList.add(0, movie);
if (rank > offSet) {
offSet = rank;
}
} catch (JSONException e) {
System.out.println(TAG + " : JSON Parsing error : "+e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(TAG+" : Server error : "+error.getMessage());
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
}
As seen in the documentation about the SwipeRefreshLayout:
If an activity wishes to show just the progress animation, it should call setRefreshing(true).
Calling setRefreshing() will not call the OnRefreshListener. You can call fetchMovie() just after it though :
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovie();
}
});
Related doc : https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html
I want to receive the value of the variable Id from the listItem clicked and to pass it in the other activity.But I am not receiving anything in the variable.
Here is the attached code :
MainActivity.java
package com.example.hp.citysearchapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<City> cityList = new ArrayList<City>();
private ListView listView;
private static String url;
ImageView searchIcon;
String idGet;
String edittextSearch;
TextInputLayout searchLayout;
EditText search;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.city_listView);
searchLayout=(TextInputLayout)findViewById(R.id.input_layout_search);
search=(EditText)findViewById(R.id.input_search);
searchIcon=(ImageView)findViewById(R.id.imageView);
adapter = new CustomListAdapter(this,cityList);
searchIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edittextSearch=search.getText().toString();
Log.d("hello2", search.getText().toString());
adapter.notifyDataSetChanged();
url = "http://test.maheshwari.org/services/testwebservice.asmx/SuggestCity?tryValue="+edittextSearch;
parsingMethod();
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,CityDetailsActivity.class);
City city = cityList.get(position);
idGet=city.getId();
Log.d("dfjdkfj", idGet); //Not receiving anything ,here is the problem
intent.putExtra("gettingId",idGet);
startActivity(intent);
}
});
}
private void parsingMethod() {
Log.d("hello", url);
pDialog = new ProgressDialog(this);
// Showing progress dialog
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest cityReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
// Parsing json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
City city = new City();
try {
city.setId(obj.getString("Id"));
city.setTitle(obj.getString("Title"));
city.setDescription(obj.getString("Description"));
city.setExv1(obj.getString("ExtraValue1"));
Log.d("hello",obj.getString("ExtraValue1"));
city.setExv2(obj.getString("ExtraValue2"));
city.setExv3(obj.getString("ExtraValue3"));
city.setExv4(obj.getString("ExtraValue4"));
city.setExv5(obj.getString("ExtraValue5"));
city.setExv6(obj.getString("ExtraValue6"));
city.setExv7(obj.getString("ExtraValue7"));
city.setExv8(obj.getString("ExtraValue8"));
city.setExv9(obj.getString("ExtraValue9"));
cityList.add(city);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(cityReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
City.java
package com.example.hp.citysearchapp;
/**
* Created by hp on 22-03-2016.
*/
public class City {
String title,description,exv1,exv3,exv6,id,exv2,exv4,exv5,exv9,exv7,exv8;
public City(String title, String description, String id, String exv1, String exv3, String exv6,
String exv2, String exv4 , String exv5 , String exv7 , String exv8 , String exv9) {
this.title = title;
this.description=description;
this.id=id;
this.exv1=exv1;
this.exv2=exv2;
this.exv3=exv3;
this.exv4=exv4;
this.exv5=exv5;
this.exv6=exv6;
this.exv7=exv7;
this.exv8=exv8;
this.exv9=exv9;
}
public City() {
}
public String getId() {
return id;
}
public String getExv2() {
return exv2;
}
public String getExv4() {
return exv4;
}
public String getExv5() {
return exv5;
}
public String getExv7() {
return exv7;
}
public String getExv8() {
return exv8;
}
public String getExv9() {
return exv9;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getExv1() {
return exv1;
}
public String getExv3() {
return exv3;
}
public String getExv6() {
return exv6;
}
public void setId(String id) {
this.id = id;
}
public void setExv2(String exv2) {
this.exv2 = exv2;
}
public void setExv4(String exv4) {
this.exv4 = exv4;
}
public void setExv5(String exv5) {
this.exv5 = exv5;
}
public void setExv7(String exv7) {
this.exv7 = exv7;
}
public void setExv8(String exv8) {
this.exv8 = exv8;
}
public void setExv9(String exv9) {
this.exv9 = exv9;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setExv1(String exv1) {
this.exv1 = exv1;
}
public void setExv3(String exv3) {
this.exv3 = exv3;
}
public void setExv6(String exv6) {
this.exv6 = exv6;
}
}
Please modify your code a bit to achieve this --
You already have --
City city = cityList.get(position);
Now add this line to get Id from the ListItem clicked --
String Id = city.getExv3(); //Use one of your actual Getter methods accordingly.
Hope this helps!
Since I'm using a CustomAdapter for my list , I have to use the following code :
TextView textView = (TextView)view.findViewById(R.id.id); /*(R.id.id) is the id of the textview */
String gettingID=textView.getText().toString();
I implement the Infinitie scroll in RecyclerView , every thing is ok , but when json is reloaded , cursor go to the first element then , adapter is reloaded .
This is my Activity where json is parsed and adapter set to the recyclerView
ArchiveActivity.java :
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.majid.aparat.R;
import com.majid.aparat.adapter.ArchiveRecyclerAdapter;
import com.majid.aparat.app.AppController;
import com.majid.aparat.pojo.VideoData;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArchiveActivity extends AppCompatActivity {
// ============ Global Variables ================ //
ProgressDialog progressDialog;
List<VideoData> videoDataList = new ArrayList<VideoData>();
RecyclerView archiveRecyclerView;
ArchiveRecyclerAdapter adapter;
private String after_url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_archive);
String TAG = ArchiveActivity.class.getSimpleName();
setUpToolbar();
//btn
Button btnVideo = (Button) findViewById(R.id.btnVideo);
btnVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ArchiveActivity.this, WatchActivity.class));
}
});
sendJsonRequest();
showPD();
//========================= initialize recyclerView ===========================//
archiveRecyclerView = (RecyclerView) findViewById(R.id.archiveRecylerView);
archiveRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ArchiveActivity.this);
archiveRecyclerView.setLayoutManager(linearLayoutManager);
// archiveRecyclerView.setItemAnimator(new SlideInUpAnimator());
archiveRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
loadMore();
}
});
adapter = new ArchiveRecyclerAdapter(this, videoDataList);
archiveRecyclerView.setAdapter(adapter);
}
//========================= send json request ===========================//
private void sendJsonRequest() {
//========================= get Category intent ===========================//
Intent intent = getIntent();
String catUrl = intent.getStringExtra("category");
String fUrl = String.format("http://www.aparat.com//etc/api/categoryvideos/%s", catUrl);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, fUrl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parsJsonResponse(response);
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TAG", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request);
}
//========================= parse json response ===========================//
private void parsJsonResponse(JSONObject response) {
if (response != null) {
try {
JSONObject ui = response.getJSONObject("ui");
after_url = ui.getString("pagingForward");
JSONArray categoryViedeos = response.getJSONArray("categoryvideos");
for (int i = 0; i < categoryViedeos.length(); i++) {
JSONObject currentVideo = categoryViedeos.getJSONObject(i);
VideoData viNew = new VideoData();
viNew.setVideoThumbnail(currentVideo.getString("small_poster"));
viNew.setVideoTitle(currentVideo.getString("title"));
viNew.setVideoCount(currentVideo.getString("visit_cnt"));
viNew.setVideoDate(currentVideo.getString("sdate"));
videoDataList.add(viNew);
}
hidePD();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//========================= setUpToolbar ===========================//
private void setUpToolbar() {
Intent intent = getIntent();
String catName = intent.getStringExtra("catName");
Toolbar archiveToolbar = (Toolbar) findViewById(R.id.archiveToolbar);
//Toast.makeText(this , catUrl , Toast.LENGTH_SHORT).show();
setSupportActionBar(archiveToolbar);
archiveToolbar.setTitleTextColor(Color.WHITE);
getSupportActionBar().setTitle(catName);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_left);
}
//========================= showPD Method ===========================//
private void showPD() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("در حال بارگزاری ");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
//========================= hidePD Method ===========================//
private void hidePD() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
//========================= LoadMore for infinitie scroll ===========================//
private void loadMore() {
//Toast.makeText(ArchiveActivity.this , "we are loading !!!" ,Toast.LENGTH_SHORT).show();
adapter = new ArchiveRecyclerAdapter(ArchiveActivity.this , videoDataList);
archiveRecyclerView.setAdapter(adapter);
showPD();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, after_url, (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePD();
if (response != null) {
try {
JSONObject ui = response.getJSONObject("ui");
after_url = ui.getString("pagingForward");
JSONArray categoryViedeos = response.getJSONArray("categoryvideos");
for (int i = 0; i < categoryViedeos.length(); i++) {
JSONObject currentVideo = categoryViedeos.getJSONObject(i);
VideoData viNew = new VideoData();
viNew.setVideoThumbnail(currentVideo.getString("small_poster"));
viNew.setVideoTitle(currentVideo.getString("title"));
viNew.setVideoCount(currentVideo.getString("visit_cnt"));
viNew.setVideoDate(currentVideo.getString("sdate"));
videoDataList.add(viNew);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Error
}
});
AppController.getInstance().addToRequestQueue(request);
}
}
and This is the EndlessRecyclerOnScrollListener.java :
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = true; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;
private int current_page = 1;
private LinearLayoutManager mLinearLayoutManager;
public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
this.mLinearLayoutManager = linearLayoutManager;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLinearLayoutManager.getItemCount();
firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
current_page++;
onLoadMore(current_page);
loading = true;
}
}
public abstract void onLoadMore(int current_page);
}
and This is ArchiveRecyclerAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
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 com.majid.aparat.adapter.ArchiveRecyclerAdapter.ViewHolder;
import com.majid.aparat.pojo.VideoData;
import com.majid.aparat.R;
import java.util.List;
/**
* Created by majid on 18/01/2016.
*/
public class ArchiveRecyclerAdapter extends RecyclerView.Adapter<ArchiveRecyclerAdapter.ViewHolder> {
//================== Global Var
Context context;
List<VideoData> videoDataList ;
//=================== Constructor ============================= //
public ArchiveRecyclerAdapter(Context context , List<VideoData> videoDataList) {
this.context = context;
this.videoDataList = videoDataList;
}
//=================== ViewHolder ============================= //
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView imgThumbnailVideo;
private TextView txtTitleVideo;
private TextView txtCountVideo;
private TextView txtDateVideo;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
imgThumbnailVideo = (ImageView)itemView.findViewById(R.id.imgThumnailVideo);
txtTitleVideo = (TextView)itemView.findViewById(R.id.txtVideoTitle);
txtDateVideo = (TextView)itemView.findViewById(R.id.txtVideoDate);
txtCountVideo = (TextView) itemView.findViewById(R.id.txtVideoCount);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext() , txtTitleVideo.getText() , Toast.LENGTH_SHORT ).show();
}
}
//=================== OnCreateViewHolder ============================= //
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_item_row , null);
ViewHolder viewHolder = new ViewHolder(rootView);
return viewHolder;
}
//=================== onBindViewHolder ============================= //
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Context context = holder.itemView.getContext();
VideoData currentVideoData = videoDataList.get(position);
Glide.with(context).load(currentVideoData.getVideoThumbnail()).into(holder.imgThumbnailVideo);
holder.txtTitleVideo.setText(currentVideoData.getVideoTitle());
holder.txtCountVideo.setText(currentVideoData.getVideoCount());
holder.txtDateVideo.setText(currentVideoData.getVideoDate());
}
//=================== getItemCount ============================= //
#Override
public int getItemCount() {
return videoDataList.size();
}
}
Here:
adapter = new ArchiveRecyclerAdapter(ArchiveActivity.this , videoDataList);
archiveRecyclerView.setAdapter(adapter);
Probably these lines in loadMore() method causing issue because every time when onLoadMore method called setting new Adapter object to archiveRecyclerView.
Currently adapter object and setAdapter is already created and called in onCreate method, so no need to use these lines again.
I have a RecyclerView in the ArchiveActivity , it's populate with json , every thing is ok but when i swipe down the refresh layout , nothing happens , now my question is how can i retrieve the new json and populate the RecyclerView and doesn't have conflict with setOnScrollListenerMethod :
This is the activity_archive.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e6e6e6"
tools:context=".activities.ArchiveActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/archiveToolbar"
android:background="#34465d"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"/>
<Button
android:id="#+id/btnVideo"
android:layout_below="#+id/archiveToolbar"
android:text="Video Activity"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout_archive"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/archiveRecylerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/btnVideo"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
and this is the ArchiveActivity :
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.majid.aparat.R;
import com.majid.aparat.adapter.ArchiveRecyclerAdapter;
import com.majid.aparat.app.AppController;
import com.majid.aparat.pojo.VideoData;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import android.os.Handler;
import android.widget.Toast;
public class ArchiveActivity extends AppCompatActivity {
// ============ Global Variables ================ //
ProgressDialog progressDialog;
List<VideoData> videoDataList = new ArrayList<VideoData>();
RecyclerView archiveRecyclerView;
ArchiveRecyclerAdapter adapter;
private String after_url;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_archive);
String TAG = ArchiveActivity.class.getSimpleName();
setUpToolbar();
// ========== btn Video Activity =========== //
Button btnVideo = (Button) findViewById(R.id.btnVideo);
btnVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ArchiveActivity.this, WatchActivity.class));
}
});
//======== SwipeRefreshLayout init ======//
swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout_archive);
swipeRefreshLayout.setColorSchemeResources(R.color.red , R.color.green , R.color.blue);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sendJsonRequest();
swipeRefreshLayout.setRefreshing(false);
}
} , 1500 );
}
});
// ========================= sending jsonRequest ======================= //
sendJsonRequest();
showPD();
//========================= initialize recyclerView ===========================//
archiveRecyclerView = (RecyclerView) findViewById(R.id.archiveRecylerView);
archiveRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ArchiveActivity.this);
archiveRecyclerView.setLayoutManager(linearLayoutManager);
archiveRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
loadMore();
Toast.makeText(ArchiveActivity.this , "onLoadMore is calling" , Toast.LENGTH_SHORT).show();
}
});
adapter = new ArchiveRecyclerAdapter(this, videoDataList);
archiveRecyclerView.setAdapter(adapter);
}
//========================= send json request ===========================//
private void sendJsonRequest() {
//========================= get Category intent ===========================//
Intent intent = getIntent();
String catUrl = intent.getStringExtra("category");
String fUrl = String.format("http://www.aparat.com//etc/api/categoryvideos/%s", catUrl);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, fUrl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
videoDataList.clear();
parsJsonResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TAG", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request);
}
//========================= parse json response ===========================//
private void parsJsonResponse(JSONObject response) {
if (response != null) {
try {
JSONObject ui = response.getJSONObject("ui");
after_url = ui.getString("pagingForward");
JSONArray categoryViedeos = response.getJSONArray("lastvideos");
for (int i = 0; i < categoryViedeos.length(); i++) {
JSONObject currentVideo = categoryViedeos.getJSONObject(i);
VideoData viNew = new VideoData();
viNew.setVideoThumbnail(currentVideo.getString("small_poster"));
viNew.setVideoTitle(currentVideo.getString("title"));
viNew.setVideoCount(currentVideo.getString("visit_cnt"));
viNew.setVideoDate(currentVideo.getString("sdate"));
videoDataList.add(viNew);
}
adapter.addMoreItems(videoDataList);
hidePD();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
//========================= LoadMore for infinitie scroll ===========================//
private void loadMore() {
//Toast.makeText(ArchiveActivity.this , "we are loading !!!" ,Toast.LENGTH_SHORT).show();
showPD();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, after_url, (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePD();
parsJsonResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Error
}
});
AppController.getInstance().addToRequestQueue(request);
}
//========================= setUpToolbar ===========================//
private void setUpToolbar() {
Intent intent = getIntent();
String catName = intent.getStringExtra("catName");
Toolbar archiveToolbar = (Toolbar) findViewById(R.id.archiveToolbar);
//Toast.makeText(this , catUrl , Toast.LENGTH_SHORT).show();
setSupportActionBar(archiveToolbar);
archiveToolbar.setTitleTextColor(Color.WHITE);
getSupportActionBar().setTitle(catName);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_left);
}
//========================= showPD Method ===========================//
private void showPD() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("در حال بارگزاری ");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
//========================= hidePD Method ===========================//
private void hidePD() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
and This is ArchiveRecyclerAdapter :
import android.content.Context;
import android.support.v7.widget.RecyclerView;
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 com.majid.aparat.adapter.ArchiveRecyclerAdapter.ViewHolder;
import com.majid.aparat.pojo.VideoData;
import com.majid.aparat.R;
import java.util.List;
/**
* Created by majid on 18/01/2016.
*/
public class ArchiveRecyclerAdapter extends RecyclerView.Adapter<ArchiveRecyclerAdapter.ViewHolder> {
//================== Global Var
Context context;
List<VideoData> videoDataList ;
//=================== Constructor ============================= //
public ArchiveRecyclerAdapter(Context context , List<VideoData> videoDataList) {
this.context = context;
this.videoDataList = videoDataList;
}
//=================== ViewHolder ============================= //
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView imgThumbnailVideo;
private TextView txtTitleVideo;
private TextView txtCountVideo;
private TextView txtDateVideo;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
imgThumbnailVideo = (ImageView)itemView.findViewById(R.id.imgThumnailVideo);
txtTitleVideo = (TextView)itemView.findViewById(R.id.txtVideoTitle);
txtDateVideo = (TextView)itemView.findViewById(R.id.txtVideoDate);
txtCountVideo = (TextView) itemView.findViewById(R.id.txtVideoCount);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext() , txtTitleVideo.getText() , Toast.LENGTH_SHORT ).show();
}
}
//=================== OnCreateViewHolder ============================= //
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_item_row , null);
ViewHolder viewHolder = new ViewHolder(rootView);
return viewHolder;
}
//=================== onBindViewHolder ============================= //
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Context context = holder.itemView.getContext();
VideoData currentVideoData = videoDataList.get(position);
Glide.with(context).load(currentVideoData.getVideoThumbnail()).into(holder.imgThumbnailVideo);
holder.txtTitleVideo.setText(currentVideoData.getVideoTitle());
holder.txtCountVideo.setText(currentVideoData.getVideoCount());
holder.txtDateVideo.setText(currentVideoData.getVideoDate());
}
//=================== getItemCount ============================= //
#Override
public int getItemCount() {
return videoDataList.size();
}
//=================== addMoreItems ========================== //
public void addMoreItems(List<VideoData> videoDataList){
this.videoDataList.addAll(videoDataList);
}
}
Just calling adapter.notifyDataSetChanged(); will not add new items in current Adapter Data-Source.
To get it work create a method in ArchiveRecyclerAdapter for adding new items in Data-Source like:
public void addMoreItems(List<VideoData> videoDataList){
this.videoDataList.addAll(videoDataList);
}
Now call addMoreItems method in parsJsonResponse before calling adapter.notifyDataSetChanged();