addOnScrollListener, pass base and limit - android

I am learning how to use onscrolllistner
The RecyclerOkHttpHandler class will execute a select with base 0 and limit 5 from server. what I want is to execute again the RecyclerOkHttpHandler to get the new data , for examle base 5 limit 10. but when adding the below on onscrolllistner
handler.execute().get();
i got this error :
Cannot execute task: the task has already been executed (a task can be executed only once)
ok i understand i cannot execute again the task , but how should i passe base and limit ?
this (it is working) will execute a class that will get images from server, however I need to pass base 0 and limit 5
final RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
mAdapter_first = new MyAdapter(result,SearchActivity.this);
mAdapter_first.notifyDataSetChanged();
mRecyclerView_first.setAdapter(mAdapter_first);
}
},"girls",base,limit);
try {
handler.execute().get();
} catch (Exception e) {
Log.d("SearchActivity error", "error in mRecyclerView_first");
e.printStackTrace();
}
and this is the addOnScrollListener,
mRecyclerView_first.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mRecyclerView_first.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
System.out.println("previousTotal:" + previousTotal);
System.out.println("totalItemCount:" + totalItemCount);
System.out.println("visibleItemCount:" + visibleItemCount);
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
System.out.println(totalItemCount);
Log.i("Yaeye!", "end called");
// base =String.valueOf(firstVisibleItem);
// limit=String.valueOf(visibleItemCount);
// Do something
try {
handler.execute().get();
} catch (Exception e) {
Log.d("SearchActivity error", "error in mRecyclerView_first");
e.printStackTrace();
}
loading = true;
}
}
});
this is the class RecyclerOkHttpHandler
public class RecyclerOkHttpHandler extends AsyncTask<String, Void, String> {
private Context mContext;
private MyInterface mListener;
public String category;
public String basestart;
public String limitend;
public RecyclerOkHttpHandler(Context context, MyInterface mListener, String categ, String base, String limit){
mContext = context;
this.mListener = mListener;
category=categ;
basestart=base;
limitend=limit;
}
public interface MyInterface {
public void myMethod(ArrayList result);
}
private final String Fetch_URL = "http://justedhak.com/old-files/Recyclerview_data.php";
// ArrayList<Listitem> Listitem;
ArrayList<CategoryList> Listitem;
int resulta;
OkHttpClient httpClient = new OkHttpClient();
ListView list;
String myJSON;
JSONArray peoples = null;
InputStream inputStream = null;
#Override
protected String doInBackground(String... params) {
Log.d("okhttp Fetch_URL", Fetch_URL);
RequestBody formBody = new FormEncodingBuilder()
.add("category", category)
.add("base", basestart)
.add("limit", limitend)
.build();
Request request = new Request.Builder()
.url(Fetch_URL)
.post(formBody)
.build();
String result = null;
try {
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
inputStream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
resulta = 1; //"Success
// return response.body().bytes();
} catch (Exception e) {
Toast.makeText(mContext, "Connection failed, check your connection",
Toast.LENGTH_LONG).show();
e.printStackTrace(); }
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
if( resulta ==1){
myJSON=result;
Log.e("result",result);
showList();
}
else{
Log.e("d","there is an error on postexecute in okhhttphandler.java");
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println("Length:"+peoples.length());
int J_length=peoples.length()-1;
//JSONObject maxj = peoples.getJSONObject(peoples.length() - 1);
// max of arrray
jsonObj= peoples.getJSONObject(J_length);
String j_id= jsonObj.getString("id");
int _id = Integer.parseInt(j_id);
System.out.println(j_id);
//max of
DatabaseHandler db = new DatabaseHandler(mContext);
String db_id="";
db_id = db.getmax();
if (db_id== null)
{
db_id="0";
}
int d_id = Integer.parseInt(db_id);
Log.e("db_id", db_id);
Log.e("j_id",j_id);
// if (_id < d_id) {
System.out.println("Getting json result ");
Listitem = new ArrayList<CategoryList>();
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
Listitem.add(new CategoryList(id, url));
}
if (mListener != null)
mListener.myMethod(Listitem);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

I read your problem again, and the solution might just be to create a new RecyclerOkHttpHandler each time. That's what the error message says and that's how AsyncTasks work. If you call .execute() once you cannot call it again, you have to create a new object.
Still you should override onPostExecute() else you are blocking the UI thread. Have a look at AsyncTask.
I need the code for RecyclerOkHttpHandler to say more...

Related

RecyclerView not displaying any items

The following is the code for MainActivity where I use Async task to download data. But the data is not getting displayed.In the onPostExecute method movieList is containing 15 items but its showing as zero items in onCreate method for the same variable.
public class MainActivity extends AppCompatActivity {
public static final String YIFY_REQUEST_URL = "https://yts.am/api/v2/list_movies.json?limit=15&page=1";
RecyclerView recyclerView;
int k = 1;
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;
MovieAdapter adapter;
List<Movie> movieList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YifyAsyncTask yifyAsyncTask = new YifyAsyncTask();
yifyAsyncTask.execute(YIFY_REQUEST_URL);
adapter = new MovieAdapter(movieList);
Log.v("Movie%count",movieList.size() +"");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
final GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
gridLayoutManager.setSpanCount(2);
recyclerView.setLayoutManager(gridLayoutManager);}
else
{ gridLayoutManager.setSpanCount(3);
recyclerView.setLayoutManager(gridLayoutManager);}
//recyclerView.setItemViewCacheSize(20);
//recyclerView.setDrawingCacheEnabled(true);
//recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = gridLayoutManager.getItemCount();
firstVisibleItem = gridLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
Log.v("Yaeye!", "end called");
int cur = adapter.getItemCount();
// Do something
new YifyAsyncTask().execute("https://yts.am/api/v2/list_movies.json?limit=15&page=" + (++k));
adapter.notifyItemRangeInserted(cur,15);
loading = true;
}
}
});
}
private class YifyAsyncTask extends AsyncTask<String,Void,List<Movie>>{
#Override
protected List<Movie> doInBackground(String... urls) {
URL url = createUrl(urls[0]);
String jsonresponse = "";
try{
jsonresponse = makeHttpRequest(url);
}
catch (IOException e){
}
return extractMovieFromJson(jsonresponse);
}
#Override
protected void onPostExecute(List<Movie> moviesList) {
//MovieAdapter adapter = new MovieAdapter(movieList);
//recyclerView.setAdapter(adapter);
//adapter.notifyItemRangeInserted(adapter.getItemCount(),15);
movieList.addAll(moviesList);
}
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
return null;
}
return url;
}
private String makeHttpRequest(URL url) throws IOException{
String jsonresponse = null;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonresponse = readFromStream(inputStream);
}
catch (IOException e){
}
finally {
if(urlConnection != null)
urlConnection.disconnect();
if (inputStream != null)
inputStream.close();
}
return jsonresponse;
}
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream , Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null){
output.append(line);
line = reader.readLine();
}
}
//Log.v("response",output.toString());
return output.toString();
}
private List<Movie> extractMovieFromJson(String movieJson){
List<Movie> movieList = new ArrayList<>();
if (TextUtils.isEmpty(movieJson))
return null;
try{
JSONObject basejsonresponse = new JSONObject(movieJson);
JSONObject data = basejsonresponse.getJSONObject("data");
JSONArray movieArray = data.getJSONArray("movies");
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
String movieName = movie.getString("title_long");
String movieUrl = movie.getString("url").replaceAll("\\\\","");
String movieImg = movie.getString("large_cover_image").replaceAll("\\\\","");
//Log.v("url",movieImg);
movieList.add(new Movie(movieName,movieUrl,movieImg));
}
return movieList;
}
catch (JSONException e){
}
return null;
}
}
}
It worked before when I set the adapter in the onPostExecute method.But Later I removed that and set it in the onCreate method.But if I use the notifyDataSetChanged method in the onPostExecute movies are displaying. If I use notifyItemRangeChanged method even then data is not displaying.I'm not able to understand where I'm doing wrong.I'm a beginner and don't mind my bad coding style.
You cannot call notifyDataSetChanged() method the way you are doing, that method is supposed to be called on your onPostExecute() or a method called from it. Since you are executing an asynchronous request, see below. Your next line(adapter.notifyItemRangeInserted(cur,15);) is not guaranteed/expected to be called after the line below.
new YifyAsyncTask().execute("https://yts.am/api/v2/list_movies.json?limit=15&page=" + (++k));

How to implement Endless listview in Fragment?

I am implementing endless listview in Fragment. When I writes the code for setOnScrollListener for my listview then my app is crashing with the error The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. I have tried almost everything to apply notifyDataSetChanged() on my adapter. Please help me to solve the problem.
below is my code.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_all_campaign, container, false);
allCampaignList = (ListView) rootView.findViewById(R.id.allCampaignList);
adapter = new CampaignListAdapter(getActivity(), CampaignDataArrayList);
loadCampaignsData(offsetValue);
allCampaignList.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScroll(AbsListView view,
int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
//Algorithm to check if the last item is visible or not
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
// you have reached end of list, load more data
loadCampaignsData(offsetValue + 1);
offsetValue++;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//blank, not using this
}
});
return rootView;
}
Below is the method loadCampaignsData():
public void loadCampaignsData(final int offset) {
pDialog.setMessage("Please wait..");
pDialog.setTitle("Loading");
showDialog();
Handler h = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what != 1) {
hideDialog();// code if not connected
viewUtils.internertErrorMsgDialog();
} else {
GetAllCampaign getAllCampaign = new GetAllCampaign();
getAllCampaign.execute(String.valueOf(offset));
}
}
};
viewUtils.isNetworkAvailable(h, 2000); // get the answser within 2000 ms
}
Below is the asynctask written for fetching webservice.
private class GetAllCampaign extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Constants.DADAMI_URL + Constants.ALL_CAMPAIGN);
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("cat_id", "0"));
list.add(new BasicNameValuePair("user_id", ""));
list.add(new BasicNameValuePair("offset", params[0]));
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return readResponse(httpResponse);
//return null;
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
hideDialog();
if (result == null) {
Toast.makeText(context, "Something went wrong.. Please try again..!!", Toast.LENGTH_LONG).show();
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
allCampaignList.setAdapter(adapter);
}
});
}
}
}
private ArrayList<HashMap<String, String>> readResponse(HttpResponse res) {
InputStream is = null;
try {
is = res.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
JSONObject mainObj = new JSONObject(sb.toString());
JSONArray fundraiser_data = null;
fundraiser_data = mainObj.getJSONArray("fundraiser_data");
for (int i = 0; i < fundraiser_data.length(); i++) {
JSONObject elem = fundraiser_data.getJSONObject(i);
String fundraiser_photo = elem.getString("fundraiser_photo");
String title = elem.getString("title");
String fullname = elem.getString("fullname");
HashMap<String, String> campaignData = new HashMap<>();
campaignData.put("fundraiser_photo", Constants.DADAMI_IMAGE_URL + fundraiser_photo);
campaignData.put("title", title);
campaignData.put("fullname", fullname);
CampaignDataArrayList.add(campaignData);
}
} catch (Exception e) {
e.printStackTrace();
}
return CampaignDataArrayList;
}

how to add OnScrollListener in my below code

It's been a while since I have been using android. can you please tell me how to add OnScrollListener in this code ? Everytime I scroll down I want to fetch 5 more images.
This is the Asyncatask its working correct, but I need fetch 5 image everytime I scroll down(load more).
public class RecyclerOkHttpHandler extends AsyncTask<String, Void, String> {
private Context mContext;
private MyInterface mListener;
public String category;
public String basestart;
public String limitend;
public RecyclerOkHttpHandler(Context context, MyInterface mListener, String categ, String base, String limit){
mContext = context;
this.mListener = mListener;
category=categ;
basestart=base;
limitend=limit;
}
public interface MyInterface {
public void myMethod(ArrayList result);
}
private final String Fetch_URL = "http://justedhak.com/old-files/Recyclerview_data.php";
// ArrayList<Listitem> Listitem;
ArrayList<CategoryList> Listitem;
int resulta;
OkHttpClient httpClient = new OkHttpClient();
ListView list;
String myJSON;
JSONArray peoples = null;
InputStream inputStream = null;
#Override
protected String doInBackground(String... params) {
Log.d("okhttp Fetch_URL", Fetch_URL);
RequestBody formBody = new FormEncodingBuilder()
.add("category", category)
.add("base", basestart)
.add("limit", limitend)
.build();
Request request = new Request.Builder()
.url(Fetch_URL)
.post(formBody)
.build();
String result = null;
try {
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
inputStream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
resulta = 1; //"Success
// return response.body().bytes();
} catch (Exception e) {
Toast.makeText(mContext, "Connection failed, check your connection",
Toast.LENGTH_LONG).show();
e.printStackTrace(); }
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
if( resulta ==1){
myJSON=result;
Log.e("result",result);
showList();
}
else{
Log.e("d","there is an error on postexecute in okhhttphandler.java");
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println("Length:"+peoples.length());
int J_length=peoples.length()-1;
//JSONObject maxj = peoples.getJSONObject(peoples.length() - 1);
// max of arrray
jsonObj= peoples.getJSONObject(J_length);
String j_id= jsonObj.getString("id");
int _id = Integer.parseInt(j_id);
System.out.println(j_id);
//max of
DatabaseHandler db = new DatabaseHandler(mContext);
String db_id="";
db_id = db.getmax();
if (db_id== null)
{
db_id="0";
}
int d_id = Integer.parseInt(db_id);
Log.e("db_id", db_id);
Log.e("j_id",j_id);
// if (_id < d_id) {
System.out.println("Getting json result ");
Listitem = new ArrayList<CategoryList>();
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
Listitem.add(new CategoryList(id, url));
}
if (mListener != null)
mListener.myMethod(Listitem);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the when I set the adapter
private String base = "0";
private String limit = "5";
final RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
mAdapter_first = new MyAdapter(result,SearchActivity.this);
mAdapter_first.notifyDataSetChanged();
mRecyclerView_first.setAdapter(mAdapter_first);
}
},"girls jokes",base,limit);
try {
handler.execute().get();
} catch (Exception e) {
Log.d("SearchActivity error", "error in mRecyclerView_first");
e.printStackTrace();
}
For the first load, call your RecyclerOkHttpHandler AsyncTaskto get your first 5 items.
Now, for any further load, all you have to do is to check if the listView is scrolled to its bottom and you can refer to this link Find out if ListView is scrolled to the bottom? to know how to deal with it.
So, each time you detect that the user has scrolled the listview to the bottom, it's time to call the RecyclerOkHttpHandler AsynTask to get the 5 new images.
PS: You need to save the limit you have reached in each load, so that in the next load, you start loading from that limit.
Hope this helps :)

GridView is blank after updating its data after scrolling down

I am usind TMDb API to build a project app. Every api call gives me back 20 movies, so normally the app shows only 20 movie posters on startup. I added this code to fetch another 20 movies, using the &page= query, when the user scrolls down the grid View.
gridView.setOnScrollListener(onScrollListener());
private AbsListView.OnScrollListener onScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = gridView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (gridView.getLastVisiblePosition() >= count - threshold && pageCount < 2) {
Log.v(LOG_TAG, "loading more data");
// Execute LoadMoreDataTask AsyncTask
updateMovies(sortBy, true);
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
But this solution works really bad. If i scroll down it executes updateMovies(sortBy, true); for 2-3 times at once, jumping pages and making it impossible to read.
Also, the data shown on screen is completely replaced after every page refresh, for example if I am seeing the data on page=1 and I scroll down then i see only the data from page 2 or 3 but the original data is gone.
here is my AsyncTask
public class FetchMoviesTask extends AsyncTask<String, Void, List<Movie>> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private final static String API_KEY = "480a9e79c0937c9f4e4a129fd0463f96";
#Override
protected List<Movie> doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonStr = null;
try {
final String BASE_URL = "http://api.themoviedb.org/3/movie";
final String API_KEY_PARAM = "api_key";
final String PAGE_PARAM = "page";
URL url;
if (params[1].equals("true")){
// if a bool is true
// then I intend to load an additional page
// (needed otherwise going back from detailAct loads a new increasing page
currentPage += 1;
pageCount++;
}else{
currentPage = 1;
}
if (params[0].equals(POPULARITY_DESC)){
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendPath("popular")
.appendQueryParameter(API_KEY_PARAM, API_KEY) // my own API key
.appendQueryParameter(PAGE_PARAM , Integer.toString(currentPage))
.build();
url = new URL(builtUri.toString());
}else if(params[0].equals(RATING_DESC)) {
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendPath("top_rated")
.appendQueryParameter(API_KEY_PARAM, API_KEY)// my own API key
.appendQueryParameter(PAGE_PARAM , Integer.toString(currentPage))
.build();
url = new URL(builtUri.toString());
}else {
Log.v(LOG_TAG, "Something went wrong with URI building :(");
url = new URL("ERROR URL");
}
Log.v(LOG_TAG, "URL BUILT: " + url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
jsonStr = buffer.toString(); // finally parsed JSON string
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getMoviesDataFromJson(jsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
private List<Movie> getMoviesDataFromJson(String jsonStr) throws JSONException {
JSONObject movieJson = new JSONObject(jsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<Movie> results = new ArrayList<>();
for(int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
Movie movieModel = new Movie(movie); // basically Movie has already the fields to fill (image,
// description, rating, etc) and this adds those values from the JSONObject
results.add(movieModel); // it does this one object at the time, for the lenght of the array
}
return results;
}
#Override
protected void onPostExecute(List<Movie> mv) {
if (mv != null) {
if (movieGridAdapter != null) {
movieGridAdapter.clear();
for (Movie movie : mv) {
movieGridAdapter.add(movie);
}
}
movies = new ArrayList<>();
movies.addAll(mv);
}
}
}

How to show other Json objects in RecylerView on Android

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
I can show title, description and thumbnail. but i want show medium from thumbnail_images instance of thumbnail. I don't know how to read images from medium ?!
My Json Link : Link
AsyncTaskCodes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString(mediumImage)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
for fetch medium image i use this code :
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
but when set mediumImage for infoModels.add(new MainDataModel() not show me any posts!
How can set images from medium ? thanks all <3
private void setImageWithPicaso(String imageUrl) {
if (!(imageUrl == null)) {
Picasso.with(getActivity()).load(imageUrl).placeholder(R.drawable.placeholder_background).into(imageView, new Callback() {
#Override
public void onSuccess() {
//On Success
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
//On Error
}
});
} else {
spinner.setVisibility(View.GONE);
//On Error
}
}

Categories

Resources