ListView in android not saving ratingBar stars - android

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)

Related

Dynamically adding data to listView which does not overwrite the previous data and permanently saving it

In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView.
There are a number of problems with his code.
1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews.
2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done.
I want the list to be automatically updated when new data is entered rather than over writing it.
3) The data vanishes away when i restart the app. I want the data to be saved permanently.
Code for Custom Adapter is:
package com.example.sakshi.dialogsandmenus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Data> list;
private LayoutInflater mLayoutInflator;
public CustomAdapter(Context context, ArrayList list){
this.context=context;
this.list=list;
mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
dob.setText(list.get(position).getDate());
return convertView;
}
}
Code for Main Activity is:
package com.example.sakshi.dialogsandmenus;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.R.id.list;
import static com.example.sakshi.dialogsandmenus.R.id.date;
public class MainActivity extends AppCompatActivity{
ListView listview;
ArrayList<Data> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.list_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==R.id.add){
filldialog();
}
return super.onOptionsItemSelected(item);
}
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
arrayList = new ArrayList<>();
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
//customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
}
}
1) you have to convert the value of age to String before setText
//age.setText(list.get(position).getAge());
age.setText(Integer.toString(list.get(position).getAge()));
2) Every time new Arraylist initilaization
intarrayList = new ArrayList<>();
ArrayList arrayList = new ArrayList<>();
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
enter code here
3) Use Sqlite or anyStorage Option for data saving
You are setting int value directly to setText of ageTextView. You need to convert int to String before you setting a text to TextView.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
age.setText(String.valueOf(list.get(position).getAge())); // use this it will work
dob.setText(list.get(position).getDate());
return convertView;
}
}
Move these lines outside the onClickListener
arrayList = new ArrayList<>();
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
Because whenever you are clicking the button arraylist is initializing again.

Increasing a number in a listview via button

I'm developing in Android Studio.
I have a ListView that every item in it contains number of elements including 2 Buttons:increase/decrease and a EditText filed:edit_txt .
I need that in each click on the button "increase" will increase the number in the edit_txt filed.
As well as in every click on the button "decrease" it will decrease the number in the edit_txt filed.
how do i make it work?
The class called "ProductList" and it expands AppCompatActivity.
package com.example.yuliaaa.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ProductList extends AppCompatActivity {
private List<myProductsView> myProducts_types = new ArrayList<myProductsView>();
ArrayAdapter<myProductsView> adapter;
private ArrayList<myProductsView> choosen_items = new ArrayList<myProductsView>();
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pop_productlist);
populateProductsList();
populateListView();
}
private void populateProductsList() {
myProducts_types.add(new myProductsView("p1", "d1", 1111, 12.90, R.drawable.cereal, 1));
myProducts_types.add(new myProductsView("p2", "dddd", 1112, 10.90, R.drawable.cereal, 2));
myProducts_types.add(new myProductsView("p3", "ffff", 1112, 30.00, R.drawable.cereal, 1));
myProducts_types.add(new myProductsView("p4", "kkkkk", 1112, 20.00, R.drawable.cereal, 3));
}
private void populateListView() {
adapter = new MyListAdapter();
list = (ListView) findViewById(R.id.product_list);
list.setAdapter(adapter);
}
public void StartCalck(View view){
Intent intent = new Intent(ProductList.this, SplitBuying.class);
startActivity(intent);
}
public void deleteItems(View view){
for(int i=0;i<choosen_items.size();i++){
adapter.remove(choosen_items.get(i));
}
}
public class MyListAdapter extends ArrayAdapter<myProductsView>{
public MyListAdapter(){
super(ProductList.this, R.layout.pop_productlist, myProducts_types);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//make sure we have a view to work with(may have been given null
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.product_item_view, parent, false);
}
//we need to populate the list
//find the product to work with
final myProductsView currentProduct = myProducts_types.get(position);
//fill the view
final CheckBox checkBox = (CheckBox)itemView.findViewById(R.id.product_checkBox);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosen_items.add(currentProduct);
}
});
TextView productname = (TextView) itemView.findViewById(R.id.product_name);
productname.setText(currentProduct.getProductName());
EditText quantity = (EditText)itemView.findViewById(R.id.edit_text);
quantity.setText(String.valueOf(currentProduct.getQuantity()));
Button increase = (Button)itemView.findViewById(R.id.btn_plus);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return itemView;
}
}
}
The class myProductsView is class that represent a product.
The productlist.xml contains the ListView with the id: mylist.
And the product_item_view.xml which is how every item in the list view would look like contains:
-Checkbox:"product_checkBox"
-TextView:"product_name"
-Button:"btn_plus"
-EditText:"edit_text"
-Button:"btn_minus"
thank you,
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myProducts_types.add(new myProductsView("p5", "abc", 100, 100.00, R.drawable.wheat, 4));
adapter.notifyDataSetChanged();
}
});

How to reset the whole View by clicking the delete Button

I have made a custom View which contains an ImageView, a TextView and a delete Button.
I want to reset the particular View when I click the delete Button associated with it.
Please tell how to implement this.
Here is my MainActivity.java
package com.khurana.nikhil.list1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ListView lv;
TextView tv1, tv2;
View v1;
public String[] s = {"nikhil", "mukul", "kunal"};
public int[] img = {R.drawable.rty, R.drawable.sf, R.drawable.rty};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
CustomAdapter cad = new CustomAdapter(MainActivity.this, s, img);
lv.setAdapter(cad);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View v,int position,long id)
{
Toast.makeText(MainActivity.this,"You clicked "+s[position],Toast.LENGTH_SHORT).show();
}
});
}
}
Here is CustomAdapter.java
package com.khurana.nikhil.list1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<String>{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
return v;
}
}
((LinearLayout)yourView.getParent()).removeView(yourView);
or you can call from the layout directly
yourRelativeLayout.removeView(yourView)
I would recommend to use an ArrayList instead of a String[] in your Adapter class. It makes it a lot easier to delete or edit a View and the associated data behind it. I used this post to convert your String[] to an ArrayList, delete the item and convert back to String[].
This should work on button click:
In your Adapter class:
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int positionToRemove = v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(i);
strings = new String[a.size()];
s1= a.toArray(strings);
notifyDataSetChanged(); //refresh your listview based on new data
}
#Override
public int getCount() {
return s1.length;
}
#Override
public String getItem(int position) {
return s1[position];
}
View visibility to GONE will not delete your view from memory as well. Please be specific, do you want to retain your view for future?
If you are working in a listview you should call notifyDataSetChanged() the adapter. your getView() method can be like:
action on button can be like this
Button bt=(Button)v.findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s1 = ArrayUtils.remove(s1, position);
s2 = ArrayUtils.remove(s2, position);
notifyDataSetChanged();
}
});
If you want the view to disappear:
yourView.setVisibility(View.GONE);
EDIT: To get the parent view of the button: Android: Making changes to a button's parent view

How to refresh Android GridView?

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

load a few json elements at a time by scrollview

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

Categories

Resources