RecyclerView not displaying any items - android

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));

Related

How can I get ArrayList back to fragment from parser class after parsing data and ArrayList send to fragment to set in Recyclerview adapter?

How can I get array list back to fragment after parsing to set into RecyclerView.
I tried to do that but when I call api it run background thread, till I get ArrayList from background my fragment created and it set null array to recycler adapter.
Then, I tried this way its working but I think it is a wrong approach. Please guide me -
How can I set adapter in Fragment after parsing data and send ArrayList back to fragment and set to RecyclerView adapter?
Here is my code fragment code
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view=inflater.inflate(R.layout.first_fragment,null);
recyclerView=(RecyclerView)view.findViewById(R.id.mFirstRecyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mswipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipelayoutm);
ParseDataClass mparser = new ParseDataClass(getActivity(),recyclerView,mswipeRefreshLayout);
mparser.execute("http://192.168.8.100/fetchtext.php", "1");
recyclerView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollX == 0) {
mswipeRefreshLayout.setEnabled(true);
} else mswipeRefreshLayout.setEnabled(false);
}
});
return view;
}
#Override
public String toString() {
return "FirstFragment";
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.rightimageitem).setVisible(false);
super.onPrepareOptionsMenu(menu);
}
}
And Here it is my parser class
public ParseDataClass(Context context,RecyclerView recyclerView,SwipeRefreshLayout swipeRefreshLayout) {
this.context = context;
progressDialog = new ProgressDialog(this.context);
progressDialog.setCancelable(false);
progressDialog.setMessage("Retrieving data...");
progressDialog.setTitle("Please wait");
progressDialog.setIndeterminate(true);
arrayList = new ArrayList<DataStored>();
getArraylist = new ArrayList<DataStored>();
this.recyclerView=recyclerView;
this.swipeRefreshLayout=swipeRefreshLayout;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
private static final String TAG = "Parser";
#Override
protected String doInBackground(String... strings) {
URL url = null;
int arryLength = strings.length;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(strings[0]);
String catId = strings[1];
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("catId", "UTF-8") + "=" + URLEncoder.encode(catId, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
// RestaurantData restaurantData;
if (s != null) {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String branchname = jsonObject.getString("brancname");
String branchaddress = jsonObject.getString("branchaddres");
String brandname = jsonObject.getString("brandsNae");
String brandlogo = jsonObject.getString("brndlogo");
String branchlogo = jsonObject.getString("brnchlogo");
String discAmount = jsonObject.getString("distAmount");
dataStored = new DataStored(branchname, branchaddress, brandname, brandlogo, branchlogo, discAmount);
arrayList.add(dataStored);
}
myAdapter = new MyRecyclerAdapter(context, arrayList, swipeRefreshLayout);
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
recyclerView.setAdapter(myAdapter);
} else {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
} else {
connected = false;
}
if (connected == false) {
Toast.makeText(context, "Null Data", Toast.LENGTH_LONG).show();
recyclerView.setAdapter(null);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error in Parsing =" + e, Toast.LENGTH_LONG).show();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
Now I am setting recycler view in parser class not in fragment my question is ..
how can I get ArrayList back to fragment after parsing then set into recylerview adapter in fragment.
How can I set adapter in Fragment after parsing data and send
ArrayList back to fragment and set to RecyclerView adapter?
Simple,
Step 1: Create an interface
public interface OnDataRetrievalCallback {
void onDataRetrieval(ArrayList<DataStored> dataSet);
}
Step 2: Create interface instance and setter in your Parser class
public class ParseDataClass extends AsyncTask<...> {
....
...
arrayList = new ArrayList<DataStored>();//Your arrayList to be filled
private OnDataRetrievalCallback onDataRetrievalCallback;
public void setOnDataRetrievalCallback(OnDataRetrievalCallback callback) {
this.onDataRetrievalCallback = callback;
}
// You can send the data back to Fragment via onDataRetrievalCallback
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// After parsing and filling up the data into arrayList
onDataRetrievalCallback.onDataRetrieval(arrayList); //arrayList to be sent
}
}
Step 3: set DataRetrievalCallback from your Fragment
public class MyFragment extends Fragment {
#Override
onCreateView(.....) {
ParseDataClass mparser = new ParseDataClass(getActivity(),recyclerView,mswipeRefreshLayout);
mparser.setOnDataRetrievalCallback(new OnDataRetrievalCallback{
public void onDataRetrieval(ArrayList<DataStored> dataSet) {
//dataSet is your arrayList, use it to set the adapter
}
});
mparser.execute("http://192.168.8.100/fetchtext.php", "1");
}
}

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);
}
}
}

addOnScrollListener, pass base and limit

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...

Count number of elements in a JSON Array, and display the result on Textview - Android

I want to count the number of elements I am getting through the JSON array, and display it over the TextView using .settext() method.
I am getting the following JSON ARRAY :
{
"result":
[
{
"id":"283",
"fullname":"shyam",
"contactno":"898888888",
"collegename":"mjc",
"emailaddress":"shyamzawar",
"eventname":"gaming"
},
{
"id":"285",
"fullname":"ffca",
"contactno":"8888888888",
"collegename":"Brihan maharashtra College of Commerce (BMCC)",
"emailaddress":"shyamzawar#ymail.com",
"eventname":"FootBall"
}
]
}
Below is my activity :
private static final String TAG = "userList";
private List<FeedItem> feedsList;
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
private ProgressBar progressBar;
private TextView ParticipantsCounts;
int count=0;
private SwipeRefreshLayout swipeRefreshLayout;
private final String url="http://bmcctroika.hol.es/get-data.php";;
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
// Initialize recycler view
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
ParticipantsCounts= (TextView) findViewById(R.id.ParticipantsCount);
// Downloading data from below url
new AsyncHttpTask().execute(url);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshitems();
}
});
}
private void refreshitems() {
new AsyncHttpTask().execute(url);
}
#Override
public void onRefresh() {
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200)
{
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null)
{
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result)
{
// Download complete.
progressBar.setVisibility(View.GONE);
if (result == 1)
{
adapter = new MyRecyclerAdapter(AdminActivity.this, feedsList);
mRecyclerView.setAdapter(adapter);
} else
{
Toast.makeText(AdminActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("result");
feedsList = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("fullname"));
item.setContact(post.optString("contactno"));
item.setEmail(post.optString("emailaddress"));
item.setEventname(post.optString("eventname"));
item.setCollegename(post.optString("collegename"));
feedsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You need to get the lenght of the result JSONArray. So in your code, you can get the length of posts -- JSONArray posts = response.optJSONArray("result");.
This will give you the number of items in the result array:
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("result");
int number = posts.length();
//then to set it to the text view:
ParticipantsCounts.setText(String.valueOf(number));
//the rest of your code ...
feedsList = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("fullname"));
item.setContact(post.optString("contactno"));
item.setEmail(post.optString("emailaddress"));
item.setEventname(post.optString("eventname"));
item.setCollegename(post.optString("collegename"));
feedsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Identical Fragments - one works, one doesn't

I have two fragments each being inflated from a sliding menu. One fragment works as expected, the other one force closes the app. The Fragments are identical, except in name. the second has a runtime, fatal exception main in the log.
Here is the Fragment(s):
public class FeedZFragment extends Fragment {
private static final String TAG = "RecyclerViewExample";
private List<FeedZ> feedItemList = new ArrayList<FeedZ>();
//added static might remove
private static RecyclerView mRecyclerView;
private static MyRecyclerAdapterZ adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate( R.layout.fragment_recyclerview, container, false);
/* Allow activity to show indeterminate progress-bar */
getActivity().requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
/* Initialize recycler view */
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
/*Downloading data from below url*/
final String url = "http://www.thisismysite.com/a.json";
new AsyncHttpTask().execute(url);
return rootView;
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
/* #Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}*/
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapterZ(getActivity(), feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray products = response.optJSONArray("products");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedZ>();
}
for (int i = 0; i < products.length(); i++) {
JSONObject product = products.optJSONObject(i);
FeedZ item = new FeedZ();
item.setTitle(product.optString("title"));
item.setImage_url(product.optString("image_url"));
item.setPackage_url(product.optString("package_url"));
item.setIds(product.optString("ids"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
the error is:
java.lang.NullPointerException
at com.nmthemes.WallFragment.onCreateView(WallFragment.java:44)
SOLUTION:
they weren't exactly identical.
getActivity().findViewById(R.id.my_recycler_view); should have been:
rootView.findViewById(R.id.my_recycler_view);
I changed it in one, not the other.

Categories

Resources