Related
I have a sliding image that extends pageradapter. At first it was working. But when i open new activity then press the back button the app is crashing and i've got this error :
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 10, found: 0 Pager id: malate.denise.chelsie.igphthesisbfinal:id/pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class malate.denise.chelsie.igphthesisbfinal.SlidingImage_Adapter
Here's my SlidingImage_Adapter.class
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Pictures> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context,ArrayList<Pictures> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.slidingimage_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
new DownloadImageTask(imageView).execute(IMAGES.get(position).getPhotopath());
// imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
notifyDataSetChanged();
}
#Override
public Parcelable saveState() {
return null;
}
and my AttractionInfo.class
public class AttractionInfo extends ActionBarActivity implements View.OnClickListener {
TextToSpeech tts;
TextView nameofplace,location,exact_address,operatinghours,info;
String nameofplace_s,location_s,exact_address_s,operatinghours_s,info_s,latlang_s,path_s,category_s;
ImageView play,rate,addtoplan,map;
ArrayList<Pictures> records;
private static ViewPager mPager;
private static int currentPage = 0;
String line=null;
private static int NUM_PAGES = 0;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_info);
map = (ImageView)findViewById(R.id.map);
map.setOnClickListener(this);
records=new ArrayList<Pictures>();
nameofplace = (TextView) findViewById(R.id.nameofplace);
info = (TextView) findViewById(R.id.info);
exact_address = (TextView) findViewById(R.id.exact_address);
location = (TextView)findViewById(R.id.location);
operatinghours=(TextView)findViewById(R.id.operatinghours);
play = (ImageView) findViewById(R.id.play);
rate = (ImageView) findViewById(R.id.rate);
addtoplan = (ImageView)findViewById(R.id.addtoplan);
addtoplan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
play.setOnClickListener(this);
rate.setOnClickListener(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayShowTitleEnabled(false);
tts = new TextToSpeech(AttractionInfo.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
if (extras != null) {
nameofplace_s = extras.getString("name");
nameofplace.setText(nameofplace_s);
info_s = extras.getString("description");
info.setText(info_s);
exact_address_s = extras.getString("exactaddress");
exact_address.setText(exact_address_s);
location_s = extras.getString("location");
location.setText(location_s);
operatinghours_s=extras.getString("operatinghours");
operatinghours.setText(operatinghours_s);
latlang_s = extras.getString("latlang");
path_s=extras.getString("path");
category_s = extras.getString("category");
}
}
public void onStart() {
super.onStart();
fetchphoto bt = new fetchphoto();
bt.execute();
}
#Override
protected void onPause() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
if (v == play) {
String speech1 = nameofplace.getText().toString();
String speech2 = info.getText().toString();
String speech = speech1 + "." + speech2;
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
} else if (v==rate){
Intent myIntent = new Intent(this, ListOfReviews.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if(v==addtoplan){
Intent myIntent = new Intent(this, AddPlan.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if (v == map){
Intent myIntent = new Intent(this, Map.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
myIntent.putExtra("latlang",latlang_s);
myIntent.putExtra("address",exact_address_s);
myIntent.putExtra("path",path_s);
startActivity(myIntent);
}
}
private void init() {
SlidingImage_Adapter adapter = new SlidingImage_Adapter(this,records);
for(int i=0;i<records.size();i++){
Pictures pics = records.get(i);
String pic = pics.getPhotopath();
adapter.notifyDataSetChanged();
}
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
CirclePageIndicator indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES =records.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},5000, 5000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
private class fetchphoto extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("cityname", nameofplace_s));
try
{
records.clear();
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getphoto.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pictures p = new Pictures();
p.setPhotoname(json_data.getString("photo_name"));
p.setPlacename(json_data.getString("place_name"));
p.setCategory(json_data.getString("category"));
p.setPhotopath(json_data.getString("path"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
init();
}
}
}
I've red some similar problems and learned that adding notifychanged may solved the problem but i dont where to place it. Hope you can help m . thanks
public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "**";
private static String url_update_bet = "**";
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog tDialog;
private BetDisplayer currentitem;
private HashMap<String, String> userhash = new HashMap<>();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
private HashMap<String, String> useroutcomes = new HashMap<>();
private HashMap<String, String> finalhash = new HashMap<>();
private ArrayList<Map<String, String>> passtocheck = new ArrayList<>();
private HashMap<String, HashMap<String, String>> passtocheckver2 = new HashMap<>();
private String name;
private HashMap<String, String> allopens = new HashMap<>();
JSONParser jsonParser = new JSONParser();
// Creating JSON Parser object
JSONParsers jParser = new JSONParsers();
ArrayList<HashMap<String, String>> bet;
// url to get all products list
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BET = "bet";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_USER = "user";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray allgames = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
name = (getIntent().getExtras().getString("user")).toLowerCase();
Log.d("name", name);
// Hashmap for ListView
bet = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllGames().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Games. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
// *//**
// * getting All products from url
// *//*
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_games);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", name));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
if (status.equals("open")) {
useroutcomes.put(id.substring(0, 10), Teams);
}
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, Teams));
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
String ultparam = "";
int i = 0;
for (HashMap<String, String> a : bet) {
String teams = a.get(TAG_TEAMS);
Map<String, String> listofteams = new HashMap<>();
Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
Matcher m = p.matcher(teams);
Log.d("printa", teams);
while (m.find()) {
listofteams.put(m.group(1), m.group(2));
}
Log.d("dede", listofteams.toString());
String c = "";
for (String x : listofteams.keySet()) {
String b = x + ",";
c = c + b;
}
Log.d("C", c);
c = c.substring(0, c.lastIndexOf(","));
// Log.d("Cproc", c);
if (a.get(TAG_STATUS).equals("open")) {
ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
passtocheck.add(listofteams);
allopens.put(Integer.toString(i), a.get(TAG_STATUS));
i++;
}
i++;
}
ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
Log.d("ULTPARAM", ultparam);
CheckBet checker = new CheckBet(ultparam, passtocheck);
HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
Log.d("Finaloutcomes", finaloutcomes.toString());
for (String x : finaloutcomes.keySet()) {
for (int p = 0; p < listwriter.size(); p++) {
if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
for (int r = 0; r < finaloutcomearray.length; r++) {
Log.d("finaloutcomearray", finaloutcomearray[r]);
Log.d("useroutcomearray", useroutcomearray[r]);
String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
String[] induseroutcomearray = useroutcomearray[r].split("\\)");
for (int d = 0; d < indfinaloutcomesarray.length; d++) {
Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
Log.d("induseroutcome", induseroutcomearray[d]);
finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));
}
}
Log.d("FINALHASHfinal", finalhash.toString());
Log.d("USERHASHfinal", userhash.toString());
listwriter.get(p).setStatus("won");
for (String id : userhash.keySet()) {
if (finalhash.get(id).equals("null")){
listwriter.get(p).setStatus("open");
}
else if (!(finalhash.get(id).equals(userhash.get(id)))) {
listwriter.get(p).setStatus("lost");
break;
}
}
finalhash.clear();
userhash.clear();
currentitem = listwriter.get(p);
new UpdateBetStatus().execute();
}
}
}
Log.d("USEROUTCOMES", useroutcomes.toString());
PopulateList();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_all_bets, menu);
return true;
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class UpdateBetStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* *
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(DisplayAllBets.this);
tDialog.setMessage("Loading your bets! Good luck!");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
}
/**
* Creating product
* *
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", currentitem.getId()));
params.add(new BasicNameValuePair("stake", Integer.toString(currentitem.getStake())));
params.add(new BasicNameValuePair("user", name));
params.add(new BasicNameValuePair("returns", Integer.toString(currentitem.getReturns())));
params.add(new BasicNameValuePair("teams", currentitem.getSelections()));
params.add(new BasicNameValuePair("status", currentitem.getStatus()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_bet,
"POST", params);
// check log cat fro response
Log.d("Printing", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* * * *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
private class MyListAdapter extends ArrayAdapter<BetDisplayer> {
public MyListAdapter() {
super(DisplayAllBets.this, R.layout.activity_singletotalbet, listwriter);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.activity_singletotalbet, parent, false);
}
BetDisplayer currentwriter = listwriter.get(position);
Log.d("TESTING", currentwriter.getSelections());
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setTag(Integer.toString(position));
Log.d("TESTING2", currentwriter.getSelections());
String selections = currentwriter.getSelections();
int numberofselections = 0;
for (int i = 0; i < selections.length(); i++) {
if (selections.charAt(i) == '/') {
numberofselections++;
}
}
if (numberofselections == 1) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Single");
} else if (numberofselections == 2) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Double");
} else if (numberofselections == 3) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Treble");
} else {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Accumulator" + "(" + numberofselections + ")");
}
TextView status = (TextView) itemView.findViewById(R.id.status);
status.setText(currentwriter.getStatus());
return itemView;
}
}
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
}
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
I have a populated listview. Each item in the list contains a button and a few TextViews, in the following format.
I created a method which is run when any of the buttons is clicked. What I need it to do is to retrieve that particular itemView at that position in the listview so I can access the TextViews in that itemview. This is my code but it isn't working atm.
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
Assuming your ListView listener starts here.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
You don't have to write
View selItem = (View) list.getItemAtPosition(position);
since you already got reference to the particular View in ListView from the overridden onItemClick method.
So you can skip that line and directly access TextView
TextView status = (TextView) v.findViewById(R.id.status);
Finally the code will be like
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
//Already got reference to View v
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
To catch onListItemClick add listener in PopulateList() method:
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
// Change children of list item here
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
To catch click on button in your list item you need in your adapter's getView() method add click listener to button:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button click
}
});
}
EDIT:
To store data create fields in Activity and setters for it:
private String text1;
private String text2;
public void setText1(String text){
text1 = text;
}
public void setText2(String text){
text2 = text;
}
Then set it in button click listener:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv1 = (TextView) itemView.findViewById(R.id.textview1_id);
TextView tv2 = (TextView) itemView.findViewById(R.id.textview2_id);
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText1(tv1.getText());
setText2(tv2.getText());
}
});
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm wanting to put a search bar to act as a filter for the data displayed in the listview.I could not find any examples that do something like that.
If someone can show me how I can do this or demonstrate an example I am very grateful.
public class ListFragment extends Fragment {
//the GridView
GridView lv;
Bitmap bitmap;
//The list that contains the menuitems (sort)
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;
View btnLoadMore;
Spinner spinner;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
//The list that contains the wallappers
ArrayList<Wallpaper> productsList;
//The adapter of the WallPaperList
WallPaperAdapter adapter;
private final String baseurl = AppConstant.BASE_URL;
String list_url;
// url to get all products list
private String url_all_products = baseurl + "get_all_products.php";
private String get_tag_products = baseurl + "get_tag_products.php";
// Flag for current page
int current_page = 0;
int max_pages;
// Prevent loading more items to the GridView twice
boolean isLoading;
//
String sort_order;
String tag;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PAGE = "page";
private static final String TAG_ORDER = "order";
private static final String TAG_TAG = "tag";
private static final String TAG_THUMBURL = "url";
private static final String TAG_TOTAL_PAGE = "total_page";
// products JSONArray
JSONArray products = null;
// listener for sort order
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
Log.v("Selected: ", Integer.toString(position));
if (position == 0){
sort_order = "latest";
} else if (position == 1){
sort_order = "popular";
} else if (position == 2){
sort_order = "oldest";
} else if (position == 3){
sort_order = "alphabet";
}
//"resetting the GridView"
productsList.clear();
if (adapter != null){
adapter.clear();
}
current_page = 0;
isLoading = false;
//TODO footerview is not visible
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
new InitialLoadGridView().execute();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.no_internet), Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), ImageGridActivity.class);
startActivity(intent);
}
//}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_listfragment, null);
lv = (GridView)view.findViewById(R.id.listView);
setRetainInstance(true);
setHasOptionsMenu(true);
return view;
}
*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.pesquisa, menu);
super.onCreateOptionsMenu(menu,inflater);
//Pega o Componente.
SearchView mSearchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
//Define um texto de ajuda:
mSearchView.setQueryHint("teste");
// exemplos de utilização:
return;
}*
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar actions = getActivity().getActionBar();
actions.setDisplayShowTitleEnabled(false);
// Adapter
SpinnerAdapter spinadapter =
ArrayAdapter.createFromResource(getActivity(), R.array.actions,
//android.R.layout.simple_spinner_dropdown_item);
R.layout.actionbar_spinner_item);
Spinner navigationSpinner = new Spinner(getActivity());
navigationSpinner.setAdapter(spinadapter);
// Here you set navigation listener
navigationSpinner.setOnItemSelectedListener(itemSelectedListener);
actions.setCustomView(navigationSpinner);
if (getActivity().getActionBar().getCustomView().getVisibility() == View.INVISIBLE){
getActivity().getActionBar().getCustomView().setVisibility(View.VISIBLE);
}
actions.setDisplayShowCustomEnabled(true);
//ListFragment is created, so let's clear the imageloader cache
ImageLoader.getInstance().clearMemoryCache();
// Arraylist for GridView
productsList = new ArrayList<Wallpaper>();
//initialize the footer so it can be used
btnLoadMore = View.inflate(getActivity(), R.layout.footerview, null);
if ((getResources().getString(R.string.ad_visibility).equals("0"))){
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) getActivity().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
//TODO Implement and replace old
lv.setOnScrollListener(new OnScrollListener(){
int currentVisibleItemCount;
int currentScrollState;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentVisibleItemCount = visibleItemCount;
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(!isLoading){
isLoading = true;
if (max_pages != current_page){
new loadMoreGridView().execute();
} else {
Log.v("INFO", "Not loading more items because everything is already showing");
}
}
}
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
String pid = productsList.get(position).getPid();
boolean singlepane = MainActivity.getPane();
if(singlepane== true){
/*
* The second fragment not yet loaded.
* Load DetailFragment by FragmentTransaction, and pass
* data from current fragment to second fragment via bundle.
*/
DetailFragment detailFragment = new DetailFragment();
Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");
Bundle bundle = new Bundle();
bundle.putString("TAG_PID",pid);
detailFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction =
getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(
R.anim.fadein, R.anim.fadeout, R.anim.fadein, R.anim.fadeout);
//This could use some improvement, but it works, hide current fragment, show new one
fragmentTransaction.hide(myListFragment);
fragmentTransaction.add(R.id.phone_container, detailFragment);
//fragmentTransaction.show(myDetailFragment);
/*
* Add this transaction to the back stack.
* This means that the transaction will be remembered after it is
* committed, and will reverse its operation when later popped off
* the stack.
*/
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
});
}
/**
* Async Task that send a request to url
* Gets new list view data
* Appends to list view
* */
private class loadMoreGridView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
protected Void doInBackground(Void... unused) {
// increment current page
current_page += +1;
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PAGE, Integer.toString(current_page)));
params.add(new BasicNameValuePair(TAG_ORDER, (sort_order)));
if (tag != null){
params.add(new BasicNameValuePair(TAG_TAG, (tag)));
} else {
list_url = url_all_products;
}
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(list_url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String thumburl = c.getString(TAG_THUMBURL);
// adding items to arraylist
productsList.add(new Wallpaper(name, thumburl, id));
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
//OUTDATED - Listview seems to automatically keep up with the position
//get GridView current position - used to maintain scroll position
//int currentPosition = lv.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter.notifyDataSetChanged();
//OUTDATED - Setting new scroll position
//lv.setSelectionFromTop(currentPosition + 1, 0);
if (current_page == max_pages){
adapter.RemoveFooterView();
} else {
adapter.setFooterView(btnLoadMore);
}
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
isLoading = false;
}
}
/**
* Async Task that send a request to url
* Gets new list view data
* Appends to list view
* */
private class InitialLoadGridView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
getActivity());
pDialog.setMessage(getResources().getString(R.string.wait));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... unused) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_ORDER, (sort_order)));
try { tag = getActivity().getIntent().getExtras().getString("TAG"); } catch (Exception e){}
if (tag != null){
list_url = get_tag_products;
params.add(new BasicNameValuePair(TAG_TAG, (tag)));
} else {
list_url = url_all_products;
}
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(list_url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
max_pages = json.getInt(TAG_TOTAL_PAGE);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String thumburl = c.getString(TAG_THUMBURL);
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
// adding items to arraylist
productsList.add(new Wallpaper(name, thumburl, id));
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
// Getting adapter
adapter = new WallPaperAdapter(
getActivity(), productsList);
lv.setAdapter(adapter);
current_page = 0;
if (current_page == max_pages){
adapter.RemoveFooterView();
} else {
adapter.setFooterView(btnLoadMore);
}
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
lv.post(new Runnable() {
public void run() {
//check if last item is visible, in that case, load some more items
if (lv.getLastVisiblePosition() == lv.getAdapter().getCount() -1 &&
lv.getChildAt(lv.getChildCount() - 1).getBottom() <= lv.getHeight() )
{
if(!isLoading){
isLoading = true;
if (max_pages != current_page){
new loadMoreGridView().execute();
Log.v("INFO", "Last Item Visible and more available so loading more");
} else {
Log.v("INFO", "Already showing max pages");
}
}
} else {
Log.v("INFO", "Last Item Not Visible, not loading more");
}
}
});
}
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");
if (myListFragment != null && myListFragment.isVisible()) {
//VISIBLE! =)
Log.d("STATE", "Just became visible!");
getActivity().getActionBar().getCustomView().setVisibility(View.VISIBLE);
getActivity().getActionBar().setDisplayShowTitleEnabled(false);
}
}
public static int convertDpToPixels(float dp, Context context){
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
resources.getDisplayMetrics()
);
}
public interface MyFragInterface {
public void needsHide();
}
public static boolean isInVisible(GridView scrollView, View view, Rect region, boolean relative)
{
int top = scrollView.getScrollY() + region.top;
int bottom = scrollView.getScrollY() + region.bottom;
if(!relative)
{
// If given region is not relative to scrollView
// i.e 0,0 does not point to first child left and top
top -= scrollView.getTop();
bottom -= scrollView.getTop();
}
Rect rect = new Rect(region);
rect.top = top;
rect.bottom = bottom;
Rect childRegion = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
return Rect.intersects(childRegion, region);
}
}
Using AutoCompleteTextView for search bar is the simplest way for me, following is a sample code,hope that will help.
Layout Xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment" >
<AutoCompleteTextView
android:id="#+id/search_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search"
android:inputType="text"
android:lines="1"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/search_text"
android:background="#color/white"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<ListView
android:id="#+id/countries_list"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
Fragment:
public static class PlaceholderFragment extends Fragment implements AdapterView.OnItemClickListener {
AutoCompleteTextView searchTextview;
ListView capitalList;
ArrayAdapter searchTextviewAdapter;
private View rootView;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
getActivity().setTitle(" Letsgomo");
searchTextview= (AutoCompleteTextView) rootView.findViewById(R.id.search_text);
capitalList= (ListView) rootView.findViewById(R.id.countries_list);
searchTextviewAdapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,Constants.capitals);
searchTextview.setAdapter(searchTextviewAdapter);
ArrayAdapter capitalAdapter= (ArrayAdapter) searchTextview.getAdapter();
capitalList.setAdapter(capitalAdapter);
capitalList.setOnItemClickListener(this);
return rootView;
}
}
I am using viewpager with gridview and downloading json data into it and implemented gridview scroll listener but whenever i start activity again the current viewpager fragment in which sroll listener implemented shows blank.
Here is my code, please see and tell me my mistake.
//My Activity Fragment
private static String url = "http://--------/------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
//My Json Execution
new LoadData().execute(url);
//Scroll listener when gridview reaches at end
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 10) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//Loading new datas in gridview
new LoadData()
.execute("http://-----/-----");
mLoading = true;
}
}
});
return rootView;
}
private class LoadData extends AsyncTask<String, Void, Void> {
#Override
protected void onPostExecute(Void result) {
//checking whether adapter is null or not
if (adap == null) {
adap = new Grid_View_Adatper(getActivity()
.getApplicationContext(), arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
}
Thanks in advance...
I am developing one application. In my app I am using listview to display data from json. All the data display perfectly. But what I want is, to display first 10 objects and then loading items should show and then remaining 10 will display. My json response is as given below.
{
"interestsent":
[
{
"interestsent_user_id":369,
"name":"abc",
"profile_id":"686317",
"image":"",
},
{
"interestsent_user_id":369,
"name":"def",
"profile_id":"686318",
"image":"",
},
{
"interestsent_user_id":369,
"name":"ghi",
"profile_id":"686319",
"image":"",
},
{
"interestsent_user_id":369,
"name":"jkl",
"profile_id":"686320",
"image":"",
},
{
"interestsent_user_id":369,
"name":"mno",
"profile_id":"686321",
"image":"",
},
{
"interestsent_user_id":369,
"name":"pqr",
"profile_id":"686322",
"image":"",
},
.................
.................
]
}
Interestsent.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
INTEREST_SENT_URL = "http://fshdfh.com/webservice/interestsent?version=apps&user_login_id=00";
new GetData().execute("");
listview = (ListView) findViewById(R.id.listview);
Log.i("DATA", "page ::onCreate onCreate onCreate ");
mHandler = new Handler();
listview.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
Log.i("DATA", "page :: " + page + " totalItemsCount :: "
+ totalItemsCount);
mProgressbar = new ProgressDialog(MainActivity.this);
mProgressbar.setMessage("Loading...");
mProgressbar.show();
count++;
if (count < maindata.size()) {
if (adapter != null) {
if (!isLoadingMore) {
isLoadingMore = true;
mHandler.postDelayed(loadMoreRunnable, 1000);
}
}
}
}
});
}
Runnable loadMoreRunnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (count < maindata.size()) {
if (adapter != null) {
adapter.addAll(maindata.get(count));
mHandler.removeCallbacks(loadMoreRunnable);
isLoadingMore = false;
if (mProgressbar.isShowing())
mProgressbar.dismiss();
}
}
}
};
static <T> ArrayList<ArrayList<T>> chunkList(List<T> list, final int L) {
ArrayList<ArrayList<T>> parts = new ArrayList<ArrayList<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(list.subList(i, Math.min(N, i + L))));
}
return parts;
}
private ProgressDialog mProgressbar;
public class GetData extends AsyncTask<String, String, String> {
ArrayList<Integer> data = new ArrayList<Integer>();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mProgressbar = new ProgressDialog(MainActivity.this);
mProgressbar.setMessage("Loading...");
mProgressbar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<ArrayList<Integer>> data = new ArrayList<ArrayList<Integer>>();
ServiceHandler sh = new ServiceHandler();
/*try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
/*for (int i = 0; i < 500; i++) {
data.add(i);
}
return null;*/
String jsonStr = sh.makeServiceCall(INTEREST_SENT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
interestsent = jsonObj.getJSONArray(INTEREST_SENT);
// looping through All Contacts
for (int i = 0; i < interestsent.length(); i++) {
JSONObject c = interestsent.getJSONObject(i);
// creating new HashMap
// HashMap<ArrayList<Integer> map = new HashMap<Integer>();
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(INTEREST_USER_ID, c.getString(INTEREST_USER_ID));
map.put(INTEREST_SENT_NAME,c.getString(INTEREST_SENT_NAME));
map.put(INTEREST_SENT_PROFILE, c.getString(INTEREST_SENT_PROFILE));
map.put(INTEREST_SENT_IMAGE, c.getString(INTEREST_SENT_IMAGE));
map.put(INTEREST_SENT_CAST, c.getString(INTEREST_SENT_CAST));
map.put(INTEREST_SENT_AGE, c.getString(INTEREST_SENT_AGE)+" years");
map.put(INTEREST_SENT_LOCATION, c.getString(INTEREST_SENT_LOCATION));
// adding HashList to ArrayList
data.addAll(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
maindata = chunkList(data, 50);
Log.i("DATA", "maindata :: " + maindata.size());
adapter = new CustomAdapterSent(maindata.get(count),
MainActivity.this);
listview.setAdapter(adapter);
if (mProgressbar.isShowing())
mProgressbar.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
EndlessScroolListener.java
public abstract class EndlessScrollListener implements OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
this.startingPageIndex = startPage;
this.currentPage = startPage;
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
#Override
public void onScroll(AbsListView view,int firstVisibleItem,int visibleItemCount,int totalItemCount)
{
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) { this.loading = true; }
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
currentPage++;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
if (!loading && (totalItemCount - visibleItemCount)<=(firstVisibleItem + visibleThreshold)) {
onLoadMore(currentPage + 1, totalItemCount);
loading = true;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount);
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
CustomAdapterSent.java
public class CustomAdapterSent extends BaseAdapter{
private ArrayList<Integer> mData = new ArrayList<Integer>();
private Context mContext;
private LayoutInflater inflater = null;
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
public CustomAdapterSent(ArrayList<Integer> mData, Context mContext) {
this.mContext = mContext;
this.mData = mData;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addAll(ArrayList<Integer> mmData) {
this.mData.addAll(mmData);
this.notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return mData.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
public TextView txtView;
TextView txtproname;
}
#Override
public View getView(int postion, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.row_layout, null);
holder = new ViewHolder();
///holder.propic = (ImageView) convertView.findViewById(R.id.propicsent);
// holder.txtproname = (TextView) convertView.findViewById(R.id.txtpronameintsent);
//holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidsent);
//holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecastintsent);
//holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileageintsent);
// holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplaceintsent);
holder.txtView = (TextView) view.findViewById(R.id.no_intsent);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Log.i("DATA", "mData.get(postion) :: " + mData.get(postion));
mData.get(postion);
// holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtView.setText("Index :: " + Integer.getInteger(TAG_NAME));
return view;
}
}
XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativemainss"
android:background="#drawable/backg"
>
<ListView android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:dividerHeight="1dp">
</ListView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/no_intsent"
android:textColor="#android:color/black"
android:background="#drawable/nomessaegborder" />
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Load More"
android:id="#+id/buttoloadmoreintsent"
android:layout_below="#android:id/list" />
</RelativeLayout>
To Show only 10 item first time in ListView and show more items on scroll follow following steps:
STEP 1: Create a chunkList method which divide ArrayList in parts of size 10:
static <T> List<ArrayList<T>> chunkList(List<T> list, final int L) {
List<ArrayList<T>> parts = new ArrayList<ArrayList<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}
STEP 2: Create ArrayList and a counter which show current part :
private boolean isLoadingMore=false;
Handler mHandler = new Handler();
List<ArrayList<HashMap<String,String>>> mainArrayList;
private int count=0;
STEP 3: In onPostExecute break result and show data in ListView:
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// your code here...
mainArrayList=chunkList(result,10);
isLoadingMore=false;
count=0;
adapter = new CustomAdapterSent(Interestsent.this,
mainArrayList.get(count));
setListAdapter(adapter);
}
}
STEP 4: Create addAll method in Adapter to append data in current data source :
public void addAll(ArrayList<HashMap<String,String>> moreData){
this.listData.addAll(moreData);
this.notifyDataSetChanged();
}
STEP 5: In onLoadMore load more data in ListView:
mHandler = new Handler();
listview.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
if(count<mainArrayList.size()-1)
{
if(adapter !=null){
count++;
if(!isLoadingMore){
isLoadingMore=true;
mHandler.postDelayed(loadMoreRunnable,1000);
}
}
}
}
});
}
Runnable loadMoreRunnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(count<mainArrayList.size())
{
if(adapter !=null){
count++;
adapter.addAll(mainArrayList.get(count));
mHandler.removeCallbacks(loadMoreRunnable);
isLoadingMore=false;
}
}
}
};
To have an AdapterView (such as a ListView or GridView) that automatically loads more items as the user scrolls through the items (aka infinite scroll). This is done by triggering a request for more data once the user crosses a threshold of remaining items before they've hit the end. Every AdapterView has support for binding to the OnScrollListener events which are triggered whenever a user scrolls through the collection. Using this system, we can define a basic EndlessScrollListener which supports most use cases by creating our own class that extends OnScrollListener.
You can find more about this in the below links :
Endless Scrolling ListView in Android
Endless Scrolling with AdapterViews
Infinite Scrolling List View
A simpler approach of adding data in a listview has been show in this SO answer: Android Endless List
Hope this helps ...