I've wrote this code. Somehow when I call notifyDatasetChanged on my adapter it doesn't work. Could anyone explain me why this doesn't work.
Also I have another question (I think related to this) I give at the creation of the class a HoodID = 27 but how can I do this another way because when I do this I can't select the first item in my Spinner.
package com.example.sander.app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.helper.StaticLabelsFormatter;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.DataPointInterface;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.OnDataPointTapListener;
import com.jjoe64.graphview.series.Series;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import android.R.layout.*;
import android.widget.Toast;
/**
* Created by Sander on 8-4-2017.
*/
public class GraphFrame extends Fragment implements AdapterView.OnItemSelectedListener {
Integer hoodSelector = 27;
ArrayList<HoodData> hoodDataList = new ArrayList<>();
ArrayList<String> hoodList = new ArrayList<>();
Context mContext;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void refreshFragment(){
hoodDataList.clear();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_graph,
container, false);
//API Request for all the hoods
getDataFromApi((GraphView) view.findViewById(R.id.graph));
getDataForSpinner((Spinner) view.findViewById(R.id.spinner));
return view;
}
public void setHoodId(Integer hood){
hoodSelector = hood;
}
public void getDataFromApi(final GraphView graph) {
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/damage_or_theft_car_wijk.php?hood_id=" + hoodSelector;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("");
for (int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
hoodDataList.add(new HoodData(jsonObject.getDouble("percentage"), jsonObject.getInt("hood_id"), jsonObject.getInt("year"), jsonObject.getString("hood_name")));
}
} catch (JSONException ex){}
StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
new DataPoint(1, hoodDataList.get(0).getPercentage()),
new DataPoint(2, hoodDataList.get(1).getPercentage()),
new DataPoint(3, hoodDataList.get(2).getPercentage()),
new DataPoint(4, hoodDataList.get(3).getPercentage()),
new DataPoint(5, hoodDataList.get(4).getPercentage())
//new DataPoint(12, 0)
});
// set manual x bounds
staticLabelsFormatter.setHorizontalLabels(new String[] {"2006", "2007","2008","2009","2011"});
//creates custom x-axis
graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
graph.setTitle("Wijk " + hoodSelector + " - " + hoodDataList.get(0).getHood_name());
//set nice background color :)
series.setDrawBackground(true);
//shows points at datapoints
series.setDrawDataPoints(true);
//size of the points
series.setDataPointsRadius(10.0f);
series.setOnDataPointTapListener(new OnDataPointTapListener() {
#Override
public void onTap(Series series, DataPointInterface dataPoint) {
Toast.makeText(getActivity(), "Punt "+ dataPoint, Toast.LENGTH_SHORT).show();
}
});
series.setTitle("%");
series.setAnimated(true);
graph.getLegendRenderer().setVisible(true);
graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
graph.addSeries(series);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
public void getDataForSpinner(final Spinner spinner){
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/damage_or_theft_car_wijk.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("");
for (int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
if (!hoodList.contains(jsonObject.getString("hood_name"))) {
hoodList.add(jsonObject.getString("hood_name"));
}
}
} catch (JSONException ex){}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(spinner.getContext(), android.R.layout.simple_spinner_item, hoodList);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setPrompt("Title");
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
for(int i = 1; i < hoodList.size(); i++) {
if (item.equals(hoodList.get(i))) {
setHoodId(i + 27);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
}
Declare
private GraphView mGraphView;
private Spinner mSpinner;
private ArrayAdapter<String> adapter;
And remove parameter in method getDataFromApi and getDataForSpinner.
Recall getDataFromApi instead of adapter.notifyDataSetChanged();
Add adapter.notifyDataSetChanged(); in the end of onResponse in getDataFromApi
Related
Good afternoon,
I'm still a beginner in programming, currently learning Android.
I am making a screen that captures some information from a website and moves to a list view. The code below works when I use only the main page of the site, when I try to move to page 2 instead of adding to the end of the Array, it overwrites the entire Array.
I have reached the limit of my knowledge, I can kick it a silly mistake in how they are built, but I could not reach the solution alone.
I'm sorry if I have any typos, I'm using a translator.
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
String[] aniNomes;
String[] aniLinks;
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks[posicao]);
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
aniNomes = new String[nome.size()];
aniLinks = new String[links.size()];
for(Element nomeTemp : nome){
nomeExp = nomeTemp.text();
adaptador.add(nomeExp);
}
}
for (int i = 0; i < nome.size(); i++) {
aniNomes[i] = nome.get(i).text();
}
for (int i = 0; i < links.size(); i++) {
aniLinks[i] = links.get(i).attr("abs:HREF");
}
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
conteudo.setAdapter(adaptador);
}
}
}
New code after the proposed modification.
THANKS FOR THE HELP!!!
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
ArrayList<String> aniNomes = new ArrayList<>();
ArrayList<String> aniLinks = new ArrayList<>();
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks.get(position));
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
for (Element nomeT : nome){
aniNomes.add(nomeT.text());
}
for (Element linkT : links){
aniLinks.add(linkT.attr("abs:HREF"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
conteudo.setAdapter(adaptador);
}
}
}
Its because you're creating a new adapter in your asynctask and then in your onPostExecute method you're calling setAdapter which swaps out the old adapter and its entries with the new adapter and its new entries.
Rather than creating a new adapter in your asynctask I would just create an array/arraylist, add the new entries to it and then in your onPostExecute just append the entries from this array/list into the one and only adapter entry set.
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 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();