サーバーからいくつかのjsonデータをロードし、それらをアプリに表示します.RecyclerViewを使用します. 初めて10個のアイテムをロードし、スクロールで他の10個のアイテムをロードしたい。
どうすればいいですか?
私はこのチュートリアルを使用していますが、この時点でチュートリアルを自分のコードに一致させることはでき ません
アップデート
これは活動中の私のコードです
public class NewsActivity extends AppCompatActivity {
//--------------------------------
private ProgressDialog pDialog;
//----------------------------------
private String urlJsonArray="http://kazeroon.mosbate16.com/news/news.php";
private static String TAG = ListActivity.class.getSimpleName();
static List<News> mNews = new ArrayList<>();
private int page=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//-------------
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
//----------------
if (isOnline()==true) {
makeJsonArrayRequest_News();
}else
Toast.makeText(getApplicationContext(),
"برای دریافت اطلاعات به اینترنت نیاز دارید.",
Toast.LENGTH_LONG).show();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
private void makeJsonArrayRequest_News() {
showpDialog();
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
RecyclerView recyclerViewlist = (RecyclerView) findViewById(R.id.newsList);
//tarif layout maneger baraye tarif noe nemayesh
recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
//tarif class adapter recyclview
final RVAdapterNews ad = new RVAdapterNews(NewsActivity.this, mNews, recyclerViewlist);
recyclerViewlist.setAdapter(ad);
ad.setOnLoadMoreListener(new ir.kazeroonsara.kazeroon.OnLoadMoreListener() {
@Override
public void onLoadMore() {
Log.e("haint", "Load More");
mNews.add(null);
ad.notifyItemInserted(mNews.size() - 1);
//Load more data for reyclerview
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.e("haint", "Load More 2");
//Remove loading item
mNews.remove(mNews.size() - 1);
ad.notifyItemRemoved(mNews.size());
//Load data
//-----------------------------------------------------------------------------------------------
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
@Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
page=page+1;
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
//----------------------------------------------------------------------------------------------
ad.notifyDataSetChanged();
ad.setLoaded();
}
}, 5000);
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
@Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public interface OnLoadMoreListener {
void onLoadMore();
}
}
これは私のコードアダプターです
public class RVAdapterNews extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//consteraktor ra misazim
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private Context context;
private LayoutInflater inflater;
List<News> mNews;
News news=new News();
private RecyclerView mRecyclerViewlist;
public RVAdapterNews(final NewsActivity context, List<News> mNews,RecyclerView recyclerViewlist){
this.context=context;
this.inflater=LayoutInflater.from(context);
this.mNews=mNews;
this.mRecyclerViewlist=recyclerViewlist;
//-------------------------------------------------
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerViewlist.getLayoutManager();
mRecyclerViewlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
@Override
public int getItemViewType(int position) {
//return super.getItemViewType(position);
return mNews.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
//--------------------------------------------------------MyViewHolder----------------------------------------------
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//bayad aval yek layout besazim - recycler_layout
//layout ro moarefi mikonim
//View v=inflater.inflate(R.layout.rvnews_layout,parent,false);
// vh=new MyViewHolder(v);
//return vh;
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(context).inflate(R.layout.rvnews_layout, parent, false);
MyViewHolder vh=new MyViewHolder(view);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
LoadingViewHolder vh2=new LoadingViewHolder(view);
return vh2;
}
return null;
}
//--------------------------------MyViewHolder holder------------------------------------------------------------
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
//itemhaei ke bayad neshan dadeh shavad bayad inja vared shavad
if (holder instanceof MyViewHolder) {
news = mNews.get(position);
final MyViewHolder myViewHolder = (MyViewHolder) holder;
myViewHolder.newsTitle.setText(news.getTitle());
//----------------------
long seconds = Long.parseLong(news.getDiffDate());
//int day = (int) TimeUnit.SECONDS.toDays(seconds);
//long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
//long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
//long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
long minute = seconds / 60;
long hours = minute / 60;
int day = (int) hours / 24;
int week = day / 7;
int month = day / 30;
int year = day / 365;
if (seconds < 60)
myViewHolder.newsDatePublication.setText(seconds + " ثانیه قبل");
else if (seconds >= 60 && seconds < 3600)
myViewHolder.newsDatePublication.setText(minute + " دقیقه قبل");
else if (seconds >= 3600 && seconds < 86400)
myViewHolder.newsDatePublication.setText(hours + " ساعت قبل");
else if (seconds >= 86400 && seconds < 604800)
myViewHolder.newsDatePublication.setText(day + " روز قبل");
else if (seconds >= 604800 && seconds < 2629743)
myViewHolder.newsDatePublication.setText(week + " هفته قبل");
else if (seconds >= 2629743 && seconds < 31556926)
myViewHolder.newsDatePublication.setText(month + " ماه قبل");
else
myViewHolder.newsDatePublication.setText(year + " سال قبل");
//----------------------
//holder.newsDatePublication.setText(newsPublicationDateItems.get(position));
Uri uri = Uri.parse(news.getPic());
Picasso.with(context).load(uri).resize(200, 200).centerCrop().into(myViewHolder.newsPic, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
myViewHolder.newsPic.setImageResource(R.mipmap.ic_default_list);
}
});
myViewHolder.cvNews.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
News news = mNews.get(position);
Intent intent = new Intent(context, NewsViewActivity.class);
intent.putExtra("id", news.getId());
intent.putExtra("title", news.getTitle());
intent.putExtra("shortContent", news.getShortContent());
intent.putExtra("longContent", news.getLongContent());
intent.putExtra("datePublication", news.getPublicationDate());
intent.putExtra("pic", news.getPic());
intent.putExtra("src", news.getSrc());
intent.putExtra("link", news.getLink());
context.startActivity(intent);
}
});
}else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
@Override
public int getItemCount() {
//tedad itemhara baraye nemayesh midahim
//return mNews.size();
return mNews == null ? 0 : mNews.size();
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
//bayad ajzaye layout ro tarif konim
ImageView newsPic;
TextView newsTitle;
TextView newsShortContent;
TextView newsLongContent;
TextView newsDatePublication;
CardView cvNews;
public MyViewHolder(View itemView) {
super(itemView);
newsPic=(ImageView) itemView.findViewById(R.id.ivNewsPic);
newsTitle= (TextView) itemView.findViewById(R.id.txtNewsTitle);
newsDatePublication = (TextView) itemView.findViewById(R.id.txtNewsDatePublication);
cvNews = (CardView) itemView.findViewById(R.id.CVNews);
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
public void setLoaded() {
isLoading = false;
}
}