How to implement Endless scrolling with recycler view - android

I want to show list of data seperated by pages that is first i want to show 5 details and then when user scrolls down then it loads 5 more by again calling the api now i have been able to show first 5 details but when scrolling it replaces previous 5 with new 5 details it is not adding data instead replacing it.
MainFile in which i want to show the data
package com.example.vinod.lcoportal;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
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 org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class StbDetailsFragment extends Fragment {
RecyclerView recycler_view_stb_details;
ArrayList<StbDetails> listitems_stb = new ArrayList<>();
String[] name = new String[50];
String[] address = new String[100];
String[] vc_stb = new String[100];
String[] city = new String[100];
String[] current_plan = new String[200];
String[] status = new String[50];
String[] csi = new String[300];
int currentpage = 0;
int pagesize = 5;
ProgressDialog pDialog;
JSONArray ja;
JSONObject jo;
String custcsi, custcity, custname, currentplan, custstatus, vc_no;
String stb_url = "http://lco.denonline.in/wapp/Service1.svc/Dashboard";
public StbDetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stb_details, container, false);
currentpage = currentpage + 1;
GetStb getStb= new GetStb(currentpage, pagesize);
getStb.execute(stb_url);
return view;
}
public class MyAdapterStb extends RecyclerView.Adapter<MyAdapterStb.MyViewHolderStb> {
private ArrayList<StbDetails> list;
public MyAdapterStb(ArrayList<StbDetails> Data) {
list = Data;
}
#Override
public MyViewHolderStb onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.stb_details_cardview, parent, false);
MyViewHolderStb holder = new MyViewHolderStb(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolderStb holder, int position) {
holder.cust_name.setText(list.get(position).getName());
holder.cust_address.setText(list.get(position).getAddress());
holder.cust_vc.setText(list.get(position).getVc_stb_no());
holder.cust_city.setText(list.get(position).getCity());
holder.cust_plan.setText(list.get(position).getCurrentPlan());
holder.cust_status.setText(list.get(position).getStatus());
// holder.events_imageview.setImageResource(list.get(position).getImageResourceId());
// holder.events_imageview.setTag(list.get(position).getImageResourceId());
// Glide.with(getActivity()).load(list.get(position).getImageResourceId_notices()).into(holder.notices_imageview);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolderStb extends RecyclerView.ViewHolder {
TextView cust_name, cust_address, cust_vc, cust_city, cust_plan, cust_status ;
public MyViewHolderStb(View v) {
super(v);
cust_name = (TextView) v.findViewById(R.id.name_stb_details);
cust_address = (TextView) v.findViewById(R.id.address_stb_details);
cust_vc = (TextView) v.findViewById(R.id.vc_stb_no_stb_details);
cust_city = (TextView) v.findViewById(R.id.city_stb_details);
cust_plan = (TextView) v.findViewById(R.id.current_plan_stb_details);
cust_status = (TextView) v.findViewById(R.id.status_stb_details);
// v.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent i = new Intent(getActivity(),NoticesViewActivity.class);
// i.putExtra("notice_url",pdf[getAdapterPosition()]);
// i.putExtra("notice_title",title_notices[getAdapterPosition()]);
// startActivity(i);
// }
// });
}
}
}
public void initializeList() {
listitems_stb.clear();
for (int i = 0; i < ja.length(); i++) {
StbDetails item = new StbDetails();
item.setName(name[i]);
item.setAddress(address[i]);
item.setVc_stb_no(vc_stb[i]);
item.setCity(city[i]);
item.setCurrentPlan(current_plan[i]);
item.setStatus(status[i]);
listitems_stb.add(item);
}
}
public class GetStb extends AsyncTask<String,String,String> {
HttpURLConnection httpURLConnection;
int CurrentPage, PageSize;
public GetStb(int currentpage, int pagesize) {
CurrentPage = currentpage;
PageSize = pagesize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Fetching Data...Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//pDialog.show();
// progress_dialog.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
Log.d("DoInBackground:URL", url.toString());
//Send Post Data request
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.addRequestProperty("api_key", "XBoGycClZkJrXDVphgpN5c9Bb82fcKQ4");
httpURLConnection.addRequestProperty("gulco", "fe96632f-5173-e611-942d-005056bb1e58");
httpURLConnection.addRequestProperty("currentpage", String.valueOf(CurrentPage));
httpURLConnection.addRequestProperty("pagesize", String.valueOf(PageSize));
//)httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
//Get the Server Response
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.d("DoInBackground", "Response:" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
GridLayoutManager MyLayoutManager = new GridLayoutManager(getActivity(),1);
MyLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recycler_view_stb_details = (RecyclerView) getActivity().findViewById(R.id.recycler_view_stb_details);
recycler_view_stb_details.setHasFixedSize(true);
try {
ja = new JSONArray(response);
//ja = jo.getJSONArray("notices");
//images = new String[ja.length()];
//title = new String[ja.length()];
for (int i=0;i<ja.length();i++) {
JSONObject json = ja.getJSONObject(i);
custcsi = json.getString("CSI");
custcity = json.getString("City");
custname = json.getString("CustName");
currentplan = json.getString("Plan");
custstatus = json.getString("Status");
vc_no = json.getString("VCNO");
name[i] = custname;
csi[i] = custcsi;
city[i] = custcity;
current_plan[i] = currentplan;
vc_stb[i] = vc_no;
status[i] = custstatus;
initializeList();
}
} catch (Exception e) {
e.printStackTrace();
}
//progress_dialog.setVisibility(View.GONE);
//pDialog.dismiss();
if (listitems_stb.size() > 0 & recycler_view_stb_details != null) {
recycler_view_stb_details.setAdapter(new MyAdapterStb(listitems_stb));
}
recycler_view_stb_details.setLayoutManager(MyLayoutManager);
//pDialog.dismiss();
}
}
}

I think your problem is that every time in the public void initializeList() you call first of all listitems_stb.clear(); so your list will be cleared every time and you will lose all the previous data.
So if you wanna add other elements to the list you shouldn't clear it. Just try to delete listitems_stb.clear();.
Then for pagination see this answer here.
Hope this helps

Related

I can't clear the listview in my fragment before populating it again?

NOTE :
First of all before writing any thing. this is not a duplicate because if it is then why I will post this here. I didn't find any of the stackoverflow similar questions' answers helpful to me at all for 2 days straight.
THE PROBLEM :
I have an activity that takes two fields of data and then go to the next activity where it has a view pager and the activity opens 2 fragments the posts and the profile. the problem here is that when I go back to the first activity to input different data and go to the fragments the listview shows duplicate data.
I tried every possible solution but none works.
I tried to clear adapter.
I tried to pass empty adapter.
I tried more things in the life cycle of the fragment but nothing.
so please I need help. thanks in advance.
package psychrating.psychrating;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/7/2017.
*/
public class PostsFragment extends Fragment {
static ListView posts_list;
Spinner list_order;
SearchView search;
String category, date, activity;
boolean get_data;
public static ArrayList<String> data = null;
static Context c;
transient ViewHolder holder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
data = null;
activity = getArguments().getString("activity");
category = getArguments().getString("category");
date = getArguments().getString("date");
if (activity == "main") {
// get_data = true;
}else {
// get_data = true;
}
View view = inflater.inflate(R.layout.post_tab, container, false);
init(view);
posts_list.clearChoices();
if (searchResultses != null) {
searchResultses.clear();
searchResultses = null;
}
return view;
}
private void init(View view) {
posts_list = (ListView) view.findViewById(R.id.posts_list);
list_order = (Spinner) view.findViewById(R.id.list_order);
search = (SearchView) view.findViewById(R.id.search);
posts_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
holder = (ViewHolder) view.getTag();
Temp temp = new Temp();
temp.name = holder.name.getText().toString();
temp.highest = holder.highest.getText().toString();
temp.dname = holder.dname.getText().toString();
temp.date = holder.date.getText().toString();
temp.category = holder.category;
temp.sdesc = holder.sdesc;
temp.ddesc = holder.ddesc;
Intent i = new Intent(c, ProfileActivity.class);
i.putExtra("holder", temp);
startActivity(i);
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
c = context;
}
#Override
public void onResume() {
super.onResume();
searchResultses = new ArrayList<>();
new Server(this.getActivity(), "posts").execute(category, date);
}
public static final String TAG ="ahmed";
static void removeCommas() {
StringBuilder word = new StringBuilder();
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data.get(i).length(); j++) {
char c = data.get(i).charAt(j);
if (c != ',') {
word.append(c);
}else {
words.add(word.toString());
word.delete(0, word.length());
}
}
}
}
#Override
public void onPause() {
super.onPause();
searchResultses = null;
adapter = null;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
static void addToClass() {
SearchResults s;
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}
static ArrayList<SearchResults> searchResultses = null;
static ArrayList<String> words = new ArrayList<>();
static MyCustomBaseAdapter adapter = null;
public static void fillList() {
removeCommas();
addToClass();
ArrayList<SearchResults> empty = new ArrayList<>();
adapter = new MyCustomBaseAdapter(c, empty);
adapter = new MyCustomBaseAdapter(c, searchResultses);
posts_list.setAdapter(adapter);
}
}
NOTE:
the fillList is a func that is being called by the asynctask when it finished retrieving data . which use the data variable and remove commas from data and add words to searchResult class
package psychrating.psychrating;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/10/2017.
*/
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList = null;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
super();
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(searchArrayList.get(position).getName());
holder.highest.setText(searchArrayList.get(position).getHighest());
holder.dname.setText(searchArrayList.get(position).getDName());
holder.date.setText(searchArrayList.get(position).getDate());
holder.category = searchArrayList.get(position).getCategory();
holder.sdesc = searchArrayList.get(position).getSdesc();
holder.ddesc = searchArrayList.get(position).getDdesc();
convertView.setTag(holder);
return convertView;
}
}
Server class
package psychrating.psychrating;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/6/2017.
*/
public class Server extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
private AlertDialog.Builder builder;
private String type;
private static ArrayList<String> data = null;
Server(Context context, String type) {
this.context = context;
this.type = type;
}
private void createPreDialog(String message) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressDialog.create();
}
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
createPreDialog("hold on");
}
#Override
protected String doInBackground(String... params) {
switch (type) {
case "login":
String personName = params[0];
String personEmail = params[1];
String id = params[2];
//
OutputStreamWriter outputStreamWriter = null;
BufferedWriter writer = null;
BufferedReader bufferedReader = null;
HttpURLConnection connection = null;
String line;
String result = null;
try {
URL url = new URL("http://192.168.1.64/blabla/sign_in.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(8000);
outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer = new BufferedWriter(outputStreamWriter);
String parameters = "name=" + personName + "&email=" + personEmail + "&id=" + id;
writer.write(parameters);
writer.flush();
if (connection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
} else {
result = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (connection != null) {
connection.disconnect();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
case "posts":
String category = params[0];
String date = params[1];
//
OutputStreamWriter outputStreamWriter1 = null;
BufferedWriter writer1 = null;
BufferedReader bufferedReader1 = null;
HttpURLConnection connection1 = null;
String line1 = "";
String result1 = null;
try {
URL url1 = new URL("http://192.168.1.64/blabla/posts.php");
connection1 = (HttpURLConnection) url1.openConnection();
connection1.setRequestMethod("POST");
connection1.setDoOutput(true);
connection1.setDoInput(true);
connection1.setConnectTimeout(8000);
outputStreamWriter1 = new OutputStreamWriter(connection1.getOutputStream(), "UTF-8");
writer1 = new BufferedWriter(outputStreamWriter1);
String parameters1 = "category="+category+"&date="+date;
writer1.write(parameters1);
writer1.flush();
data = new ArrayList<>();
if (connection1.getResponseCode() == 200) {
bufferedReader1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
while ((line1 = bufferedReader1.readLine()) != null) {
data.add(line1);
}
} else {
result1 = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter1 != null) {
outputStreamWriter1.close();
}
if (connection1 != null) {
connection1.disconnect();
}
if (bufferedReader1 != null) {
bufferedReader1.close();
}
if (writer1 != null) {
writer1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result1;
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
switch (type) {
case "login":
switch (s) {
case "Connect Error":
createDialog(s);
break;
case "Done":
Toast.makeText(context, s, Toast.LENGTH_LONG).show();
MainActivity.updateUI(true);
break;
case "Already Exist":
MainActivity.updateUI(true);
break;
case "Server Error":
createDialog(s);
break;
}
break;
case "posts":
if (data != null) {
PostsFragment.data = data;
PostsFragment.fillList();
data = null;
}
}
}
private void createDialog(String message) {
builder = new AlertDialog.Builder(context);
builder.setTitle("Error");
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
Your words in PostsFragment.java makes you element duplicate, In removeCommas() method first clears the words and then add the values to the words from data.
try this. searchResultses.clear(); at the start of addToClass()
static void addToClass() {
SearchResults s;
searchResultses.clear();
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}

When I tap the refresh button the images never appear

I have been trying too hard to get around this problom, when I tap the refresh button in my app, the images doesn't load on the screen.
This the DataFragment file, when i build this app there are no errors.
package com.example.popularmovis;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
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.GridView;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.jar.JarException;
/**
* A placeholder fragment containing a simple view.
*/
public class DataFragment extends Fragment {
public ImageAdapter display;
public DataFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.datafragment_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
FetchMovieData movieData = new FetchMovieData();
movieData.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
display = new ImageAdapter(rootView.getContext());
GridView gridView = (GridView) rootView.findViewById(R.id.gridView_movies);
gridView.setAdapter(display); // uses the view to get the context instead of getActivity().
return rootView;
}
public class FetchMovieData extends AsyncTask<Void, Void, String[]>{
private final String LOG_TAG = FetchMovieData.class.getSimpleName();
private String[] extractdisplayFromJason(String jasnData)
throws JSONException{
//These jason display need to be extracted
final String movie_results = "results";
final String movie_poster = "poster_path";
JSONObject movieData = new JSONObject(jasnData);
JSONArray movieArray = movieData.getJSONArray(movie_results);
String[] posterAddreess = new String[movieArray.length()];
//Fill ther posterAddreess with the URL to display
for(int j=0; j < movieArray.length(); j++){
String posterPath;
JSONObject movieArrayItem = movieArray.getJSONObject(j);
posterPath = movieArrayItem.getString(movie_poster);
posterAddreess[j] = "http://image.tmdb.org/t/p/w185/" + posterPath;
}
for (String s : posterAddreess) {
Log.v(LOG_TAG, "Thumbnail Links: " + s);
}
return posterAddreess;
}
#Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String JsonData = null;
String country = "US";
String rating = "R";
String sort = "popularity.desc";
String apiKey = "";
//building the URL for the movie DB
try {
//building the URL for the movie DB
final String MovieDatabaseUrl = "https://api.themoviedb.org/3/discover/movie?";
final String Country_for_release = "certification_country";
final String Rating = "certification";
final String Sorting_Order = "sort_by";
final String Api_Id = "api_key";
Uri buildUri = Uri.parse(MovieDatabaseUrl).buildUpon()
.appendQueryParameter(Country_for_release, country)
.appendQueryParameter(Rating, rating)
.appendQueryParameter(Sorting_Order, sort)
.appendQueryParameter(Api_Id, apiKey)
.build();
//Converting URI to URL
URL url = new URL(buildUri.toString());
Log.v(LOG_TAG, "Built URI = "+ buildUri.toString());
//Create the request to the Movie Database
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input from the database into string
InputStream inputStream = urlConnection.getInputStream();
//StringBuffer for string Manipulation
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
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) {
// Stream was empty. No point in parsing.
return null;
}
JsonData = buffer.toString();
Log.v(LOG_TAG,"Forecaast Jason String" + JsonData );
} catch (IOException e) {
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
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 extractdisplayFromJason(JsonData);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String[] posterAddreess) {
for (String poster : posterAddreess) {
display.addItem(poster);
}
}
}
}
This the ImageAdapter code
package com.example.popularmovis;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.example.popularmovis.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ArrayList<String> images = new ArrayList<String>();
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount(){
return images.size();
}
#Override
public Object getItem(int position){
return images.get(position);
}
public long getItemId(int position){
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageview;
if (convertView == null){
imageview = new ImageView(mContext);
imageview.setPadding(0, 0, 0, 0);
//imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageview.setAdjustViewBounds(true);
} else {
imageview = (ImageView) convertView;
}
Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview);
return imageview;
}
/*
Custom methods
*/
public void addItem(String url){
images.add(url);
}
public void clearItems() {
images.clear();
}
}
When you use this in your onCreate method like this, it means that the object is local to the method and can't be use in other methods.
ImageAdapter display = new ImageAdapter(rootView.getContext());
First create a global class member variable
private ImageAdapter display;
then inside your onCreate method do this
display = new ImageAdapter(rootView.getContext());

Endless recyclerview on load more scrolls to start of the list

I have got onload more functionality in my app, but when I reach the end of list new items are loaded but the list automatically scrolls to the start of the list.
This is the onload function:
recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int current_page, int position) {
// do something...
Log.d("Yaeye!", "HElloyoyo");
SuperHeroes superHero = listSuperHeroes.get(position);
Log.d("we want url", superHero.getImageUrl());
imgoffset = superHero.getImageUrl();
// Do something
getData(0);
}
});
Here is the parsing of the data received from the server:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
// loading.dismiss();
//calling method to parse json array
parseData(response);
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
public int z;
//This method will parse json data
private int parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
SuperHeroes superHero = new SuperHeroes();
CardAdapter car = new CardAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
superHero.setProUrl(json.getString("pro_pic"));
Img =json.getString(Config.TAG_IMAGE_URL);
superHero.setName(json.getString(Config.TAG_NAME));
superHero.setRank(json.getInt(Config.TAG_RANK));
superHero.setstat(false);
Log.d("test",Img);
car.setImageUrl(Img);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyItemInserted(listSuperHeroes.size());
listSuperHeroes.add(superHero);
// adapter.notifyDataSetChanged();
loading=false;
}
EndlessRecyclerOnScrollListener is taken from here
package com.example.tatson.bila;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.tatson.bila.Register;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private String imageUrl;
private ImageLoader imageLoader,imageLoader1;
private Context context;
String Load;
private static ClickListener c;
public static final String uu = "uu";
String number;
public static final String UserNum = "UserNum";
SharedPreferences sharedPref;
private String[] pos;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
// JSON parser class
JSONParser jsonParser = new JSONParser();
String url,imgoffset;
//testing from a real server:
private static final String LIKE_URL = "**";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
List<SuperHeroes> superHeroes1;
//List of superHeroes
List<SuperHeroes> superHeroes;
private RecyclerView recyclerView;
public CardAdapter() {
}
public CardAdapter(List<SuperHeroes> superHeroes, Context context) {
super();
//Getting all the superheroes
this.superHeroes = superHeroes;
superHeroes1= superHeroes;
this.context = context;
sharedPref =context.getSharedPreferences(UserNum, 0);
number = sharedPref.getString(uu, "");
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.superheroes_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
SuperHeroes superHero = superHeroes.get(position);
Log.d("position", String.valueOf(position));
Log.d("url", superHero.getImageUrl());
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
imageLoader1 = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader1.get(superHero.getProurl(), ImageLoader.getImageListener(holder.thumbNail, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
Log.d("i am ob", "ob");
holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
holder.thumbNail.setImageUrl(superHero.getProurl(), imageLoader1);
holder.textViewName.setText(superHero.getName());
holder.textViewRank.setText(String.valueOf(superHero.getRank()));
if(superHero.getstat())
{
Log.d("i am g","g");
Log.d("i am value", String.valueOf(superHero.getstat()));
holder.like.setImageResource(R.drawable.plike);
}
else
{
Log.d("i am p","p");
holder.like.setImageResource(R.drawable.glike);
}
// holder.textViewPowers.setText(powers);
holder.like.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.d("i m in like","i m in like");
if(dudo!=null) {
Log.d("i m in like1", "i m in like1");
dudo.onlike(v, position);
}} });
}
public void refresh(List<SuperHeroes> superHeroes){
Log.d("Refresh","Refresh is called ");
this.superHeroes=superHeroes;
// notifyDataSetChanged();
}
#Override
public int getItemCount() {
return superHeroes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public NetworkImageView imageView;
public CircularNetworkImageView thumbNail;
public TextView textViewName;
public TextView textViewuserName;
public TextView textViewRank;
public ImageButton like;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.username_row);
//textViewuserName = (TextView) itemView.findViewById(R.id.username_row);
textViewRank = (TextView) itemView.findViewById(R.id.textViewRank);
thumbNail = (CircularNetworkImageView) itemView.findViewById(R.id.thumbnail);
like = (ImageButton) itemView.findViewById(R.id.button_like);
// itemView.setOnClickListener( this);
}
#Override
public void onClick(View v) {
if (dudo != null) {
Log.d("i m in like1", "i m in like1");
dudo.onlike(v, 2);
}
}
}
class LikeIt extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String Imgurl = Load;
Log.d("request!", number);
// try {
// Building Parameters
HashMap<String, String> Params = new HashMap<String, String>();
Params.put("Imgurl", Imgurl);
Params.put("user", number);
Log.d("request!", "starting");
String encodedStr = getEncodedData(Params);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(LIKE_URL);
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString(); //Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check","The values :");
Log.i("custom_check", line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
return null;
}
}
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute() {
// dismiss the dialog once product deleted
}
private static ClickListener dudo ;
public interface ClickListener{
void onlike(View v,int pos);
}
public void setClickListener(ClickListener dudo){
this.dudo=dudo;
Log.d("i m in interface","i m in interface");
}
}
modify your for loop and try again
for(int i = 0; i<array.length(); i++) {
SuperHeroes superHero = new SuperHeroes();
CardAdapter car = new CardAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
superHero.setProUrl(json.getString("pro_pic"));
Img =json.getString(Config.TAG_IMAGE_URL);
superHero.setName(json.getString(Config.TAG_NAME));
superHero.setRank(json.getInt(Config.TAG_RANK));
superHero.setstat(false);
Log.d("test",Img);
car.setImageUrl(Img);
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
loading=false;
adapter.notifyDataSetChanged();
//adapter.notifyItemInserted(listSuperHeroes.size());
My guess is that you are refreshing each time the item is added in the for loop which might be the problem in your case.
private int parseData(JSONArray array){
//temporary List to store all the new data from the json
List<SuperHeroes> tempList=new ArrayList<>();
//get start position to use later
int startPos=listSuperHeroes.size()-1;
for(int i = 0; i<array.length(); i++) {
SuperHeroes superHero = new SuperHeroes();
CardAdapter car = new CardAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
superHero.setProUrl(json.getString("pro_pic"));
Img =json.getString(Config.TAG_IMAGE_URL);
superHero.setName(json.getString(Config.TAG_NAME));
superHero.setRank(json.getInt(Config.TAG_RANK));
superHero.setstat(false);
Log.d("test",Img);
car.setImageUrl(Img);
} catch (JSONException e) {
e.printStackTrace();
//You do not want to add the item incase there is a json exception
continue;
}
tempList.add(superHero);
// adapter.notifyDataSetChanged();
loading=false;
}
listSuperHeroes.addAll(tempList)
adapter.notifyItemRangeInserted(startPos,tempList.size());
}
You want to add all the items and call notifyDatasetChanged() once. If you call the notifyDatasetChanged() at every addition,there is a possibility that you will face a Inconsistency Detected exception soon enough.
RecyclerView has several helper methods to inform changes in the dataset.
notifyDatasetChanged() is the one which would refresh the entire dataset which will be an overkill in your scenario.
Consider using the other methods like notifyItemRangeInserted which will add items to the bottom of the list.
This has 2 major advantages
- Your list does not jump to positions on adding data
- The RecyclerView automatically animates the addition(this can be overriden)
You will face issues with the Inconsistency Detected error if your positions/itemcount are incorrect.
In that case you could use notifyDatasetChanged() .
Try this,
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mRecyclerView.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
Log.i("Yaeye!", "end called");
// Do something
loading = true;
}
}
});
LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

update data in listview using swipeRefreshLayout

I am trying to update the data using swipeRefreshLayout, but every time I swipe down to refresh it is only circling but not refreshing.
Can you please help me how to fix it.
package com.reader.ashishyadav271.hackernewsreader;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
SwipeRefreshLayout mSwipeRefreshLayout;
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
ArrayList<Integer> articleIds = new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<String> titles = new ArrayList<>();
ArrayAdapter arrayAdapter;
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> content = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.red, R.color.green, R.color.blue, R.color.yellow);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshContent();
}
});
ListView listView = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
i.putExtra("content", content.get(position));
startActivity(i);
}
});
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleId INTEGER, url VARCHAR, title VARCHAR, content VARCHAR)");
updateListView();
DownloadTask task = new DownloadTask();
try {
task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} catch (Exception e) {
e.printStackTrace();
}
}
private void refreshContent() {
arrayAdapter.notifyDataSetChanged();
titles.clear();
updateListView();
mSwipeRefreshLayout.setRefreshing(false);
}
public void updateListView() {
try {
Log.i("UI UPDATED", "DONE");
Cursor c = articlesDB.rawQuery("SELECT * FROM articles", null);
int contentIndex = c.getColumnIndex("content");
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
c.moveToFirst();
titles.clear();
urls.clear();
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
content.add(c.getString(contentIndex));
c.moveToNext();
}
arrayAdapter.notifyDataSetChanged();
}catch (Exception e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM articles");
for (int i = 0; i < 20; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleContent = "";
/*
url = new URL(articleURL);
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
*/
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
String sql = "INSERT INTO articles (articleId, url, title, content) VALUES (? , ? , ? , ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleContent);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
refreshContent();
}
}
}
It look like synchronism problem. I can see you load data from DownloadTask and put all of data to database. RefreshMethod query data from database.
I assume if DownloadTask do not finish yet, database isn't updated and RefreshMethod would get nothing from database. So, It is only circling but not refreshing.
To solve synchronism problem, the right application flow should be: Raise PullToRefresh Event -> execute DownloadTask -> Wait until DownloadTask finish, RefreshMethod query database for data.
Code looks like:
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
DownloadTask task = new DownloadTask();
try {
task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} catch (Exception e) {
e.printStackTrace();
}
}
});

How to add onClickListener to a ListView

I've three values which I extract them from mysql database using JSON and displayed them in a ListView. What I want is I wanna add a click listener. I've a global string variable called urlPageNumHolder to hold the ID from the clicked ListView, so when the list is clicked I want loadPage() function to be called to display Toast of the item ID clicked in the ListVew. I tried it, but whenever I clicked the item in the list, it only toasts ID of the last item in the ListView. Please F1? Below is the full code.
MainActivity.java
package com.myapp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private ListView lstView;
private ImageAdapter imageAdapter;
public int currentPage = 1;
public int TotalPage = 0;
public Button btnNext;
public Button btnPre;
public String urlPageNumHolder;
public ProgressDialog dialog;
ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setClipToPadding(false);
imageAdapter = new ImageAdapter(getApplicationContext());
lstView.setAdapter(imageAdapter);
// Next
btnNext = (Button) findViewById(R.id.btnNext);
// Perform action on click
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage + 1;
ShowData();
}
});
// Previous
btnPre = (Button) findViewById(R.id.btnPre);
// Perform action on click
btnPre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage - 1;
ShowData();
}
});
// Show first load
ShowData();
// OnClick
lstView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
loadPage();
}
});
}
public void ShowData() {
btnNext.setEnabled(false);
btnPre.setEnabled(false);
new LoadContentFromServer().execute();
dialog = ProgressDialog.show(this, "News", "Loading...", true, false);
}
public void loadPage() {
Toast.makeText(this, urlPageNumHolder, Toast.LENGTH_LONG).show();
}
class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {
#Override
protected Object doInBackground(Object... params) {
String url = "http://10.0.2.2/android/Pagination/getAllData.php";
JSONArray data;
try {
data = new JSONArray(getJSONUrl(url));
MyArrList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
int displayPerPage = 7; // Per Page
int TotalRows = data.length();
int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);
if (TotalRows <= displayPerPage) {
TotalPage = 1;
} else if ((TotalRows % displayPerPage) == 0) {
TotalPage = (TotalRows / displayPerPage);
} else {
TotalPage = (TotalRows / displayPerPage) + 1;
TotalPage = (int) TotalPage;
}
int indexRowEnd = displayPerPage * currentPage;
if (indexRowEnd > TotalRows) {
indexRowEnd = TotalRows;
}
for (int i = indexRowStart; i < indexRowEnd; i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("ImageID", (String) c.getString("ImageID"));
map.put("ItemID", (String) c.getString("ItemID"));
// Thumbnail Get ImageBitmap To Object
map.put("ImagePath", (String) c.getString("ImagePath"));
Bitmap newBitmap = loadBitmap(c.getString("ImagePath"));
map.put("ImagePathBitmap", newBitmap);
MyArrList.add(map);
publishProgress(i);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Integer... progress) {
imageAdapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Object result) {
// Disabled Button Next
if (currentPage >= TotalPage) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
// Disabled Button Previos
if (currentPage <= 1) {
btnPre.setEnabled(false);
} else {
btnPre.setEnabled(true);
}
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
}
}
class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context context) {
mContext = context;
}
public int getCount() {
return MyArrList.size();
}
public Object getItem(int position) {
return MyArrList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColImagePath
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImagePath);
imageView.getLayoutParams().height = 100;
imageView.getLayoutParams().width = 100;
imageView.setPadding(5, 5, 5, 5);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
try {
imageView.setImageBitmap((Bitmap) MyArrList.get(position).get("ImagePathBitmap"));
} catch (Exception e) {
// When Error
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
// ColImageID
TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImageID);
txtImgID.setPadding(10, 0, 0, 0);
txtImgID.setText(MyArrList.get(position).get("ImageID").toString());
// ColItemID
TextView txtItemID = (TextView) convertView.findViewById(R.id.ColItemID);
txtItemID.setPadding(10, 0, 0, 0);
txtItemID.setText(MyArrList.get(position).get("ItemID").toString());
//Hold Detail's URL
urlPageNumHolder = MyArrList.get(position).get("ImageID").toString();
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
/***** Get Image Resource from URL (End) *****/
}
urlPageNumHolder is only being set in one line urlPageNumHolder = MyArrList.get(position).get("ImageID").toString(), which has nothing to with the item being clicked.
Modify public void loadPage() {...} to
public void loadPage(long id) {
Toast.makeText(this, String.valueOf(id), Toast.LENGTH_LONG).show();
}
and invoke it as :
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
loadPage(id);
}
});
Basically, onItemClickListener tells you which item was clicked with the id parameter that you were originally ignoring. This parameter should be used to identify the item that was clicked.
EDIT:
The id may not be enough to identify the data for you case. In that case, loadPage can be modified as shown below.
public void loadPage(long id) {
Toast.makeText(this, MyArrList.get(position).get("ImageID").toString(), Toast.LENGTH_LONG).show();
}
NOTE: my code may not work as is, you might have to do some int to long conversions (or vice versa)
it looks like you're calling loadPage on click, you need to pass in the index clicked to the loadPage method, then call MyArrList.get(position); to get the location you clicked, then do whatever you want with it.
I see you found onitemclicklistner which is great but with a listview of buttons the buttons consume the click.the easy solution is replace buttons with textview or image icon.the other solution would be,and you can't use findviewbyid because you have to create an array of buttons and onitemclick listeners on each button in the array. So it would be done programaticly not in xml (the buttons anyway)
Also I am not sure about your list adapter so YouTube slidenerd 89 custombaseadapterhttp://m.youtube.com/watch?v=ka5Tk7J9rG0

Categories

Resources