Unfortunately after listView is full it does not scroll. why?
Everything else just works fine.
I feel I'm gonna break down and cry.
listview is not scrolling individually.
I have following class:
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import co.uk.aq.application.R;
import co.uk.aq.application.core.ApplicationGlobalState;
import co.uk.aq.application.core.WifiDataSets;
import co.uk.aq.application.ui.qActivity;
import com.google.inject.Inject;
import roboguice.inject.InjectView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class WifiFeedbackActivity extends qActivity {
#Inject private ApplicationGlobalState applicationGlobalState;
private RealtimeUpdateScreenCS realtimeUpdateCurrentState;
#InjectView(R.id.list_of_strings) private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_feedback);
setTitle(getString(R.string.wifi_current_connection));
}
#Override
public void onResume() {
super.onResume();
realtimeUpdateCurrentState = new RealtimeUpdateScreenCS();
realtimeUpdateCurrentState.execute();
}
#Override
public void onPause() {
super.onPause();
if (realtimeUpdateCurrentState != null){
realtimeUpdateCurrentState.cancel(true);
realtimeUpdateCurrentState = null;
}
}
private class RealtimeUpdateScreenCS extends AsyncTask{
String [] from = new String[]{"Details"};
int [] to = new int []{R.id.wan_details_text};
List<HashMap<String, String>> fillMaps;
#Override
protected Object doInBackground(Object... arg0) {
while(!isCancelled()){
fillMaps = new ArrayList<HashMap<String, String>>();
try {
for(String line: WifiDataSets.currentStateStrings){
if(!line.equals("\n")&& !line.equals(" ") && !line.equals("")){
HashMap<String, String> map = new HashMap<String, String>();
map.put("Details", line);
fillMaps.add(map);
}
}
publishProgress(fillMaps);
} catch (Exception e) {
Log.e("","",e);
}
try{Thread.sleep(50L);}catch(Exception e){}
}
return null;
}
protected void onProgressUpdate (Object...objects ){
SpecialAdapter adapter = new SpecialAdapter(getApplicationContext(), (List)objects[0], R.layout.grid_item, from, to);
lv.setClickable(false);
lv.setAdapter(adapter);
}
}
private class SpecialAdapter extends SimpleAdapter {
private int[] colors = new int[] {/*DARK_BLUE*/ new Color().rgb(14,41,179), /*RED*/ new Color().rgb(224,0,0), /*LIGHT_BLUE*/ new Color().rgb(0,153,255), /*GREEN*/ new Color().rgb(81,191,17)};
private List<HashMap<String, String>> the_list;
public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
this.the_list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int colorPos = 2 ;
if(the_list.get(position).get("Details").contains("successfully")
|| the_list.get(position).get("Details").contains("succeeded")
|| the_list.get(position).get("Details").contains("local IP address")
|| the_list.get(position).get("Details").contains("remote IP address")
|| the_list.get(position).get("Details").trim().contains("primary DNS address")
|| the_list.get(position).get("Details").trim().contains("secondary DNS address")
|| the_list.get(position).get("Details").trim().contains(applicationGlobalState.getString(R.string.wan_authentication_not_needed)))
colorPos = 3;
if(the_list.get(position).get("Details").contains("sent"))
colorPos = 2;
if(the_list.get(position).get("Details").contains("rcvd"))
colorPos = 0;
view.setBackgroundColor(colors[colorPos]);
return view;
}
}
}
And Layout is:
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_of_strings"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#000000"
android:dividerHeight="1px"/>
You are in a loop inside the AsyncTask by while(!isCancelled()) where call publishProgress every 50ms, then onProgressUpdate sets the adapter every single 50ml to the listview and so the listview is reseted. This is why you cannot scroll. For me, this code is all wrong, for example you should query the item inside the getView once the_list.get(position), not for every single check.
Related
I have been searching about this issue but still I am not very clear on how to use a click listener with an array adapter.
I need a click listener for each item of the list.
Codes:
The Area item:
package fogames.tamagomonsters;
public class Area {
public String name;
public String number;
public Area(String name, String number) {
this.name = name;
this.number = number;
}
}
The array adapter:
package fogames.tamagomonsters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class AreasAdapter extends ArrayAdapter<Area> {
public AreasAdapter(Context context, ArrayList<Area> Areas) {
super(context, 0, Areas);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Area Area = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_area, parent, false);
}
// Lookup view for data population
TextView tvname = (TextView) convertView.findViewById(R.id.tvName_area);
TextView tvnumber = (TextView) convertView.findViewById(R.id.tvNumber_of_beasts);
// Populate the data into the template view using the data object
tvname.setText(Area.name);
tvnumber.setText(Area.number);
// Return the completed view to render on screen
return convertView;
}
}
The activity:
package fogames.tamagomonsters;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import java.util.ArrayList;
public class PlayMenuActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
FrameLayout fl = new FrameLayout(this);
fl.setBackgroundColor(Color.argb(255, 0, 0, 0));
// Construct the data source
ArrayList<Area> arrayOfAreas = new ArrayList<Area>();
// Create the adapter to convert the array to views
AreasAdapter adapter = new AreasAdapter(this, arrayOfAreas);
// Attach the adapter to a ListView
ListView lv = new ListView(this);
lv.setAdapter(adapter);
// Restore preferences
SharedPreferences prefs = getSharedPreferences(PreferenceConstants.PREFERENCE_NAME, MODE_PRIVATE);
int mlen = prefs.getInt(PreferenceConstants.MLEN, 0);
long money = prefs.getLong(PreferenceConstants.MONEY, 0);
int mall = 6; //hay que ver que hacer con esto...
int eqall = 3; //igual
boolean[] mgot = new boolean[mall];
int[] exp = new int[eqall];
int[] lvl = new int[eqall];
int[] at = new int[eqall];
int[] en = new int[eqall];
for (int i = 0; i < mall; i++) {
mgot[i] = prefs.getBoolean(PreferenceConstants.MGOT[i], false);
}
for (int i = 0; i < eqall; i++) {
exp[i] = prefs.getInt(PreferenceConstants.EXP[i], 0);
lvl[i] = prefs.getInt(PreferenceConstants.LVL[i], 0);
at[i] = prefs.getInt(PreferenceConstants.AT[i], 0);
en[i] = prefs.getInt(PreferenceConstants.EN[i], 0);
}
String name[] = {getString(R.string.a001)};
int prado_got = 0;
if (mgot[0]) {
prado_got += 1;
}
if (mgot[3]) {
prado_got += 1;
}
String prado = String.valueOf(prado_got) + " / 2";
String number[] = {prado};
// Add item to adapter
Area a001 = new Area(name[0], number[0]);
adapter.add(a001);
this.setContentView(fl);
}
}
Thank you in advance.
You can do something like that:
•First insert in your adapter this method
#Override
public Area getItem(int position) {
return [yourArrayAreas].get(position);
}
•Then, in your Activity...
final AreasAdapter adapter = new AreasAdapter(this, arrayOfAreas);
ListView lv = new ListView(this);
lv.setAdapter(adapter);
mListStopsMuni.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id{
Area yourClickArea = adapter.getItem(position);
//Rest of code...
}
});
Good luck ;)
Something like this:
ArrayList<Area> arrayListAreas;
public AreasAdapter(Context context, ArrayList<Area> Areas) {
super(context, 0, Areas);
this.arrayListAreas = Areas;
}
//And then....
#Override
public Area getItem(int position) {
return arrayListAreas.get(position);
}
main xml containing horizontallistview
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
>
<com.example.newomolistview.HorizontalScrollView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ddd"
/>
</LinearLayout>
contain three textviews-for product name,original rate and offer rate
app_custom_list.xml
I think in this java class i have gone wrong
ApplicationAdapter.java
package com.example.newomolistview;
import java.text.NumberFormat;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.newomolistview.R;
import com.example.newomolistview.HorizontalScrollView;
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
// private BaseAdapter mAdapter = new BaseAdapter() {
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_custom_list, null); //new code
// LayoutInflater li = LayoutInflater.from(getContext()); //original
// v = li.inflate(R.layout.app_custom_list, null); //original
// LayoutInflater li = (LayoutInflater) this._context
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = li.inflate(R.layout.app_custom_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.textView1);
TextView originalRate = (TextView)v.findViewById(R.id.textView2);
TextView offerRate = (TextView)v.findViewById(R.id.textView3);
if(productName != null) productName.setText(app.getProductName());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app.getOfferRate());
}
return v;
// View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem, null);
// TextView title = (TextView) retval.findViewById(R.id.title);
// title.setText(dataObjects[position]);
//
// return retval;
}
// };
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
in this section also, i have gone wrong
MainActivity.java
package com.example.newomolistview;
import java.util.List;
import com.example.newomolistview.HorizontalScrollView;
import com.example.newomolistview.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener{
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview);
// listview.setAdapter(mAdapter);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String cityid="1";
String url = "http://www.gooffers.in/omowebservices/index.php/webservice/Public_User/homePagepoffers?";
FetchDataTask task = new FetchDataTask(this);
task.execute(url,key,cityid);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview); //new code
// create new adapter
ApplicationAdapter mAdapter = new ApplicationAdapter(this, data);
listview.setAdapter(mAdapter); //new code
// set the adapter to list
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
You can learn it from these tutorials :-
Populating a ListView from JSON
Loading Text in listview from http json data
I am writing a code in Android to refresh a Gridview in every 2 mins. I searched a lot in the web but i don't find any specific technique to do it.
Java Code
MainActivity.java
package com.example.mycustomgridrefresh;
import java.util.ArrayList;
import android.os.Bundle;
import android.widget.GridView;
import android.app.Activity;
public class MainActivity extends Activity
{
GridView gd;
MyGrid mg;
ArrayList<String> abc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gd = (GridView)findViewById(R.id.gd);
abc = new ArrayList<String>();
for(int i=0;i<100;i++)
{
abc.add(String.valueOf(i));
}
mg = new MyGrid(this,this,abc);
gd.setAdapter(mg);
}}
MyGrid.java
package com.example.mycustomgridrefresh;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyGrid extends BaseAdapter
{
ArrayList<String> abc;
Activity activity;
public MyGrid(Activity activity , Context cont,ArrayList<String> abc)
{
super();
this.abc = abc;
this.activity = activity;
}
#Override
public int getCount()
{
return abc.size();
}
#Override
public Object getItem(int arg0)
{
return abc.get(arg0);
}
#Override
public long getItemId(int arg0)
{
return 0;
}
public class ViewHolder
{
public TextView txt;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2)
{
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(arg1==null)
{
view = new ViewHolder();
arg1 = inflator.inflate(R.layout.mygrid, null);
view.txt = (TextView) arg1.findViewById(R.id.txt);
arg1.setTag(view);
}
else
{
view = (ViewHolder) arg1.getTag();
}
view.txt.setText(abc.get(arg0));
return arg1;
}
}
This above Grid is printing 100 numbers is 10 rows & columns. I want to change the value of the grid cells for each 2mins. The value should to change to +1.
Please suggest me some good solution.
Thanks in Advance !!!
To refresh the values you need to call in MyGrid:
notifyDataSetChanged()
To do any task each 2 mins you need to create other thread, something like this:
public void startRunnable(){
Runnable r = new Runnable() {
#Override
public void run() {
while(needToRefresh){
//add one...
this.notifyDataSetChanged();
Thread.sleep(2000);
}
}
};
this.activity.runOnUiThread(r);
}
Don't forget to stop the needToRefresh condition onPause, onStop.
EDIT: Because notifyDataSetChanged() need to be call in UI thread, you need to call runnable using this.activity.runOnUiThread
See there: How to use notifyDataSetChanged() in thread
I have a ListFragment that contains a list of items. I would like to load say 9 items at a time and when i scroll and reach the bottom of the listview i want to load another 9 items in background.
I make 2 request to my web server:
1) to get all the item id's of the items, by a searh() method
2) to get all the item details of a specific item though its id, by getId(id) method
The version i have implemented gets all the ids and then loads all the items at once in the doInBackground method of AsyncTask and it works. and it takes very long (i dont want a button because its really ugly).
I'd like to introduce this thing about the onScrollListener so that when i first open my app, in background i get all the ids, and then i get the first 9 items and show them. then when i scroll to the end i want to load the next 9 items. How do i do this?
I have read a few posts but it not clear to me, especially due to the fact that i have 2 functions that need to be run in background, 1 function needs to be run once while the other many times and i need to keep track of which id's i getting.
I would also if possible like to add the function that if i pull the ListView a little then it should update my view.
Here is my code:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
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.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.adapter.ListViewAdapter;
import com.prjma.lovertech.util.MVPFunctions;
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void) null);
return rootView;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog progressDialog;
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
//Here i get all the id's
ArrayList<Long> ids = MVPFunctions.getMioSingolo().search();
//for each id get all its details and put it in a map
items = new ArrayList<HashMap<String, Object>>();
for(int i=0; i < ids.size(); i++){
items.add(MVPFunctions.getMioSingolo().getItem(ids.get(i)));
}
return true;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
}
#Override
protected void onPostExecute(final Boolean success) {
mDownloadTask = null;
// dismiss the dialog after getting all products
progressDialog.dismiss();
//showProgress(false);
if (items.get(0).get("status error")!= null){
Toast.makeText(getActivity(), "status error = " + items.get(0).get("status error"), Toast.LENGTH_LONG).show();
Log.i("status error put toast", (String) items.get(0).get("status error"));
//fai qualcosa, tipo torna indietro, ecc
}
// updating UI from Background Thread
ListViewAdapter adapter = new ListViewAdapter(getActivity(),R.layout.listview_item_row, items, icon);
// updating listview
listView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
mDownloadTask = null;
//showProgress(false);
}
}
}
Adapter class:
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.activity.DettagliActivity;
import com.prjma.lovertech.model.Item;
public class ListViewAdapter extends ArrayAdapter<String> {
private static LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
//public ImageLoader imageLoader;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<HashMap<String, Object>> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder = new ViewHolder();
if (row == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listview_item_row, null);
viewHolder.ic_thumbnail = (ImageView)row.findViewById(R.id.ic_thumbnail);
viewHolder.scadenza = (TextView)row.findViewById(R.id.tvScadenza);
viewHolder.prezzo = (TextView)row.findViewById(R.id.tvPrezzo);
viewHolder.followers = (TextView)row.findViewById(R.id.tvFollowers);
viewHolder.hProgressBar = (ProgressBar)row.findViewById(R.id.hProgressBar);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)row.getTag();
}
HashMap<String, Object> item = items.get(position);
viewHolder.ic_thumbnail.setImageBitmap((Bitmap) item.get("pic1m"));
viewHolder.scadenza.setText((CharSequence) item.get("scadenza"));
viewHolder.prezzo.setText((CharSequence) item.get("prezzo"));
viewHolder.followers.setText((CharSequence) item.get("followers"));
viewHolder.hProgressBar.setProgress((Integer) item.get("coefficient"));
//row.onListItemClick(new OnItemClickListener1());
row.setOnClickListener(new OnItemClickListener(position));
return row;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
static class ViewHolder {
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
}
}
In your adapter, check how close the user is from the bottom of the data set. When they get to the end, call a method that fetches more items from the network. I normally use a "REFRESH_THRESHOLD" integer to prefetch items before they're needed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item current = getItem(position);
//Pre-fetch
if(getCount() - position <= REFRESH_THRESHOLD){
//If there are more items to fetch, and a network request isn't already underway
if(is_loading == false && has_remaining_items == true){
getItemsFromNetwork();
}
}
I have a problem with a listView that I made that has a ratingbar and a texview element.Its a very simple program that is meant to displays the list and stores the value of the stars that the user enters into the ratingBar. Unfortunately for some reason when I scroll up and down the rows that go out of the screen, when scrolled back in have their stars changed back to their intial value.The code is below. If anyone could help that would be great. Thanks.
package com.example.test;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
public class MainActivity extends Activity implements RatingBar.OnRatingBarChangeListener {
private String[] textList = {"Pikachu","Raichu","Raticate","Ratata","Absol","Abra","Kadabra","Pidgey","Mime","Meowth","Mew","Squirtle","Blastoise","Goop","Kilobyte","Armada"};
private ArrayList<String> list = new ArrayList<String>();
ListView listView;
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.activity_main);
for(int i=0; i<textList.length; i++)
{
list.add(i,textList[i]);
}
listView = (ListView)findViewById(R.id.listRow);
listView.setAdapter(new setListView(list));
}
class setListView extends ArrayAdapter<String>
{
public setListView(ArrayList<String> list)
{
super(MainActivity.this, R.layout.custom_layout, R.id.text, list);
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.custom_layout, parent, false);
}
RatingBar ratingBar = (RatingBar)row.findViewById(R.id.rating);
RatingBarInfo rating;
rating = (RatingBarInfo)ratingBar.getTag();
if(rating == null)
{
rating = new RatingBarInfo(position);
ratingBar.setTag(rating);
}
ratingBar.setRating(rating.getRating());
TextView text = (TextView)row.findViewById(R.id.text);
text.setText(list.get(position));
return(row);
}
}
class RatingBarInfo
{
float rating;
int position;
public RatingBarInfo(int positionTemp)
{
rating = 2.0f;
position = positionTemp;
}
public void setRating(float ratingTemp)
{
rating = ratingTemp;
}
public float getRating()
{
return rating;
}
public int getPosition()
{
return position;
}
}
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser)
{
RatingBarInfo ratingChange = (RatingBarInfo)ratingBar.getTag();
ratingChange.setRating(rating);
ratingBar.setTag(ratingChange);
((ArrayAdapter<String>)listView.getAdapter()).notifyDataSetChanged();
}
}
You forgot to set OnRatingBarChangeListener on your RatingBar.
Just add this line into your getView() method and it should works well.
ratingBar.setOnRatingBarChangeListener(MainActivity.this)