I'm using this library: https://github.com/shontauro/android-pulltorefresh-and-loadmore to add items at my lisview when scrolling reach the end. Actually it works. It load new data but it doesn't "append" it to the listview. It simply reload a new list. I need add my new data at the old as the library do! This is what i done so far:
i declared these:
String[] provaArr;
private LinkedList<String> mList;
then:
mList = new LinkedList<String>();
provaArr = (titoli.toArray(new String[0]));
mList.addAll(Arrays.asList(provaArr));
lista = (LoadMoreListView)view.findViewById(R.id.main_lista);
lista.setOnLoadMoreListener(new OnLoadMoreListener() {
public void onLoadMore() {
new ParsingSecondPage().execute();
}
});
And the AsynkTask:
private class ParsingSecondPage extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute()
{
//prima di eseguire il parsing inizializzo gli arraylist
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Loading");
mProgressDialog.setMessage("please wait...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
mProgressDialog.setCanceledOnTouchOutside(false);
titoli = new ArrayList<String>();
data = new ArrayList<String>();
categoria = new ArrayList<String>();
Lurl = new ArrayList<String>();
}
#Override
protected String doInBackground(String... params) {
if (isCancelled()){
return null;
}
try {
current += 1;
BLOG_URL_SECOND = "http://www.page.it/articoli/?pagina="+current;
Document doc = Jsoup.connect(BLOG_URL_SECOND)
.get();
Elements sezioni = doc.getElementsByClass("archive_box");
for (Element riga : sezioni) {
Element info = riga.getElementsByClass("text").first();
// Title
titolo = riga.select("h2").text();
titoli.add(titolo);
// Url
String urltitle = riga.select("h2 a").first().attr("abs:href");
Lurl.add(urltitle);
// Date
String date = info.getElementsByClass("date").first().text();
System.out.println(date);
data.add(date);
// categoria
String category = info.getElementsByClass("category").first().text();
System.out.println(category);
categoria.add(category);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < provaArr.length; i++)
mList.add(provaArr[i]);
return null;
}
#Override
protected void onPostExecute(String result)
{
adapter.notifyDataSetChanged();
lista.onLoadMoreComplete();
new LogoSecond().execute();
mProgressDialog.dismiss();
}
}
So, when i reach the end of page it call the AsynkTask but instead add the items it reload the page with new datas.
ADAPTER:
public class ParsingArrayAdapter extends ArrayAdapter<String>{
private final static int LAYOUT = R.layout.riga_listview;
private final static int TITOLO = R.id.riga_listview_titolo;
private final static int DATA = R.id.riga_listview_data;
private final static int CATEGORIA = R.id.riga_listview_categoria;
private final static int IMMAGINE = R.id.imageView1;
ArrayList<Bitmap> bitmap;
ArrayList<String> links;
ArrayList<String> titoli;
ArrayList<String> data;
ArrayList<String> categoria;
Context c;
LayoutInflater inflater;
public ParsingArrayAdapter(Context context,ArrayList<String> titoli, ArrayList<Bitmap> bitmap, ArrayList<String> data, ArrayList<String> categoria)
{
super(context,TITOLO);
this.c = context;
this.titoli = titoli;
this.data = data;
this.categoria = categoria;
this.bitmap = bitmap;
this.inflater = LayoutInflater.from(c);
}
#Override
public int getCount()
{
return titoli.size();
}
//quando la lista richiede una view
#SuppressLint("NewApi")
#Override
public View getView(int pos,View view,ViewGroup parent)
{
CacheRiga cache;
if(view==null)
{
view = inflater.inflate(LAYOUT, parent,false);
cache = new CacheRiga(); //inizializzo la cache
cache.titolo = (TextView) view.findViewById(TITOLO); //collego titolo
cache.dateArticoli = (TextView) view.findViewById(DATA); //collego la data
cache.categoriatext = (TextView) view.findViewById(CATEGORIA); //collego la data
cache.immagini = (ImageView) view.findViewById(IMMAGINE);//collego descrizione
view.setTag(cache);//collego view con cache
}
else
{
cache = (CacheRiga) view.getTag();
}
if (this.titoli.size() > 0 && pos < this.titoli.size()){
cache.titolo.setText(titoli.get(pos)); //imposto il titolo
}
if (this.data.size() > 0 && pos < this.data.size()){
cache.dateArticoli.setText(data.get(pos));
}
cache.categoriatext.setText(categoria.get(pos));
cache.immagini.setImageBitmap(bitmap.get(pos));
if (bitmap!=null){
Log.d("Bitmap MP.it", "BitmapNOTnull");
}else{
Log.d("Bitmap null MP.it", "Bitmapnull");
}
if (data!=null){
Log.d("Data", "Data NOT null");
}else{
Log.d("Data", "Data null");
}
return view;
}
private class CacheRiga { // classe per la cache delle righe
public TextView titolo; // cache titolo
public TextView dateArticoli; // cache data
public TextView categoriatext; // cache categoria
public ImageView immagini; // cache descrizione
}
Related
I'm developing an Android app using Google Sheets as a database.
I have information about books in a Google Sheet (title, author, cover, date, etc). I want to retrieve this information and show it in a "Listview" in the "Spreadsheets" Activity. I created a "BookItem" object and an "BookAdapter" adapter. In the "Spreadsheets.java" I have the read method, called "getDataFromApi()". I know that this method works, but I don't know how to adapt it to my "BookAdapter" and show the information on the ListView.
This is mi code:
public class BookItem {
static String title_item;
static Drawable cover_item; //probar con String
public BookItem(String title, Drawable cover){
super();
this.title_item = title;
this.cover_item = cover;
}
public String getTitle() {
return title_item;
}
public void setTitle(String title){
this.title_item = title;
}
public static Drawable getCover() {
return cover_item;
}
public void setCover(Drawable cover) {
this.cover_item = cover;}
This is my BookAdapter:
public class BookAdapter extends BaseAdapter {
private ArrayList<BookItem> items;
List<BookItem> items;
private Context context;
public BookAdapter (Context context, List<BookItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public BookItem getItem(int position) {
return this.items.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
private static class ViewHolder {
public final ImageView cover_item;
public final TextView title_item;
public ViewHolder (ImageView cover_item, TextView title_item){
this.cover_item = cover_item;
this.title_item = title_item;
}
}
#Override
public View getView (int position, View view, ViewGroup viewGroup) {
ImageView cover_item;
TextView title_item;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.fila_lista_miestanteria, viewGroup, false); //se mete aqui en getView por ser baseAdapter
title_item = (TextView) view.findViewById(R.id.book_title_item);
cover_item = (ImageView) view.findViewById(R.id.book_cover_item);
view.setTag(R.id.book_title_item, title_item);
view.setTag(R.id.book_cover_item, cover_item);
}
else {
cover_item = (ImageView) view.getTag(R.id.book_cover_item);
title_item = (TextView)view.getTag(R.id.book_title_item);
}
BookItem bookItem = getItem(position);
cover_item.setImageDrawable(bookItem.getCover());
title_item.setText(bookItem.getTitle());
return view;
}
}
public class Spreadsheets extends Activity {
static String book_title, book_author, book_date, book_category, book_description, book_rating, book_cover;
static String read_only = "no";
static String book_favorite = "no";
static GoogleAccountCredential mCredential;
private ListView bookList;
private TextView mOutputText;
ProgressDialog mProgress;
Context context;
List<String> rst;
List<BookItem> resultados;
BookAdapter adapter;
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spread);
// mOutputText = (TextView) findViewById(R.id.outputText);
bookList = (ListView) findViewById(R.id.bookList);
// mOutputText.setText("");
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Google Sheets...");
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
System.out.print("read only es igual a "+ read_only);
new MakeRequestTask(mCredential).execute();
}
public void rellenar(){
System.out.println("VOY A HACER NEW BOOK ADAPTER ");
adapter = new BookAdapter(context, resultados);
bookList.setAdapter(adapter);
System.out.println("SETADAPTER");
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
}
#Override
protected List<String> doInBackground(Void... params) {
try {
if(read_only.equals("no")) {
setDataToApi();
return null;
}
else {
return getDataFromApi();
}
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private List<String> getDataFromApi() throws IOException {
String range = "Sheet1!A1:H";
List<String> results = new ArrayList<String>();
ValueRange response = CreateSpreadsheets.mService.spreadsheets().values()
.get(CreateSpreadsheets.spreadsheet_id, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
for (List row : values) {
results.add(row.get(0) + ", " + row.get(7));
}
}
//funcion();
return results;
}
private void setDataToApi() throws IOException {
String range = "Sheet1!A2:H";
List<List<Object>> values = new ArrayList<>();
List<Object> data1 = new ArrayList<>();
data1.add(book_title);
data1.add(book_author);
data1.add(book_date);
data1.add(book_category);
data1.add(book_description);
data1.add(book_rating);
data1.add(book_cover);
data1.add("a");
values.add(data1);
ValueRange valueRange = new ValueRange();
valueRange.setMajorDimension("ROWS");
valueRange.setRange(range);
valueRange.setValues(values);
ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse response =
CreateSpreadsheets.mService.spreadsheets().values().append(CreateSpreadsheets.spreadsheet_id, range, body)
.setValueInputOption("RAW")
.execute();
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
// mOutputText.setText("No results returned.");
} else {
if(read_only.equals("no")) {
Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
startActivity(intent);
// mOutputText.setText("Se ha añadido un libro a su lista");
}
else {
System.out.println("VOY A RELLENAR LA LISTA");
rellenar();
}
}
}
#Override
protected void onCancelled() {
}
}
}
The "spread.xml" is a list, and the "fila_list_miestanteria.xml" is a TextView&ImageView to show the book info.
Thank you so much!
I am fairly new to android programming and ran to a small problem. I have an activity that lets users select names from a muli-select listview. I can store it in an ArrayList fine but how do I pass that ArrayList as a bundle to be retrieved from the fragment? Thank you for any future answers.
MainActivity.java:
public class MainActivity extends Activity {
ListView myListView;
Button getResult;
ConnectionClass connectionClass;
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
MyArrayAdapter myArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
emp_names_list.add("LOL");
//PAGKUHA NG RESULTS SA DB
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
String query = "select * from users WHERE user_type=3";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
String fname =rs.getString("user_fname");
String lname =rs.getString("user_lname");
String name = String.valueOf(fname)+" "+String.valueOf(lname);
emp_names_list.add(fname);
}
Toast.makeText(getApplicationContext(), "FETCH SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "FETCH FAIL", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
myListView = (ListView)findViewById(R.id.list);
//PARA SA LAYOUT
myArrayAdapter = new MyArrayAdapter(
this,
R.layout.row,
android.R.id.text1,
emp_names_list
);
myListView.setAdapter(myArrayAdapter);
myListView.setOnItemClickListener(myOnItemClickListener);
getResult = (Button)findViewById(R.id.getresult);
getResult.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String result = "";
/*
//getCheckedItemPositions
List<Integer> resultList = myArrayAdapter.getCheckedItemPositions();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + " ";
}
*/
//getCheckedItems
List<String> resultList = myArrayAdapter.getCheckedItems();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + "\n";
}
myArrayAdapter.getCheckedItemPositions().toString();
//Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
//FOR INSERTION ITO USING ARRAYLIST
String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));
//data1.add(samp);
for(String name : data1)
{
names = name;
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
}});
}
OnItemClickListener myOnItemClickListener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
myArrayAdapter.toggleChecked(position);
}};
private class MyArrayAdapter extends ArrayAdapter<String>{
private HashMap<Integer, Boolean> myChecked = new HashMap<Integer, Boolean>();
public MyArrayAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
for(int i = 0; i < objects.size(); i++){
myChecked.put(i, false);
}
}
public void toggleChecked(int position){
if(myChecked.get(position)){
myChecked.put(position, false);
}else{
myChecked.put(position, true);
}
notifyDataSetChanged();
}
public List<Integer> getCheckedItemPositions(){
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public List<String> getCheckedItems(){
List<String> checkedItems = new ArrayList<String>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItems).add(emp_names_list.get(i));
}
}
return checkedItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
CheckedTextView checkedTextView = (CheckedTextView)row.findViewById(R.id.checkedTextView);
checkedTextView.setText(emp_names_list.get(position));
Boolean checked = myChecked.get(position);
if (checked != null) {
checkedTextView.setChecked(checked);
}
return row;
}
}
}
I have tried the following example but returns null:
Bundle bundle=new Bundle();
bundle.putBundle("bundle_DescriptioneTab",bundle_DescriptioneTab);
bundle.putBundle("bundle_User_Review",bundle_User_Review);
The first thing is that you have to declare your Class as Serializable
public class MyClass implements Serialisable{
}
and using
Bundle bundle = new Bundle();
bundle.putSerialisable("myclass",MyClass);
to send data of only class
And
If you want to send Arraylisyt use:
public class MyClass implements Parcelable{
}
Intent intent = new Intent(this,SecondaryActivity.class);
ArrayList<MyClass> mArrayList = new ArrayList<MyClass>();
and using
intent.putParcelableArrayListExtra("key", mArrayList);
You can store it in an object:
public class Thing implements Serializable {
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
[...]
}
And pass it like so:
bundle.putBundle("thing",object_thing);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a custom adapter:
public class SoluzioniAdapter extends ArrayAdapter<String>{
//riferimenti statici alle risorse e agli id
private final static int LAYOUT = R.layout.riga_soluzioni;
private final static int PARTENZA = R.id.partenza;
private final static int ARRIVO = R.id.arrivo;
private final static int DATA = R.id.data;
ArrayList<String> partenze; //lista delle partenze
ArrayList<String> arrivi; //lista degli arrivi
ArrayList<String> date; //lista delle date
Context c; //context
LayoutInflater inflater; //layout inflater
public SoluzioniAdapter(Context context,ArrayList<String> partenze,ArrayList<String> arrivi,ArrayList<String> date )
{
super(context,PARTENZA);
this.c = context;
this.partenze = partenze;
this.arrivi = arrivi;
this.date = date;
this.inflater = LayoutInflater.from(c);
}
#Override
public int getCount()
{
return partenze.size(); //ritorno lunghezza lista ( = numero dei titoli)
}
//quando la lista richiede una view
#Override
public View getView(int pos,View view,ViewGroup parent)
{
CacheRiga cache; //cache
if(view==null)//se è la prima volta che viene richiesta la view
{
// creo la view ma non l'attacco alla lista in quanto devo ancora modificare
// i testi delle textview
view = inflater.inflate(LAYOUT, parent,false);
cache = new CacheRiga(); //inizializzo la cache
cache.partenza = (TextView) view.findViewById(PARTENZA); //collego titolo
cache.arrivo = (TextView) view.findViewById(ARRIVO);//collego descrizione
cache.data = (TextView) view.findViewById(DATA);//collego descrizione
view.setTag(cache);//collego view con cache
}
else
{
cache = (CacheRiga) view.getTag(); //altrimenti prendo la cache dalla view
}
cache.partenza.setText(partenze.get(pos)); //imposto il titolo
cache.arrivo.setText(arrivi.get(pos)); // e la descrizione
cache.data.setText(date.get(pos)); // e la descrizione
return view;
}
private class CacheRiga { // classe per la cache delle righe
public TextView partenza; // cache titolo
public TextView arrivo; // cache descrizione
public TextView data; // cache descrizione
}
}
I have pass partenza,arrivo and data at my list.
private static class SoluzioniLoader extends AsyncTaskLoader<List<Soluzione>> {
private FermataComune partenza;
private FermataComune arrivo;
private String data;
public SoluzioniLoader(Context context, FermataComune partenza, FermataComune arrivo, String data) {
super(context);
this.partenza = partenza;
this.arrivo = arrivo;
this.data = data;
}
#Override
public List<Soluzione> loadInBackground() {
try {
List<Soluzione> soluzioni = Client.cercaCorseAndata(partenza, arrivo, data);
return soluzioni;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
private LoaderCallbacks<List<Soluzione>> mLoaderCallbacks = new LoaderCallbacks<List<Soluzione>>() {
private ProgressDialog pd;
#Override
public Loader<List<Soluzione>> onCreateLoader(int id, Bundle args) {
pd = new ProgressDialog(SoluzioniActivity.this);
pd.setTitle("Caricamento Soluzioni Trovate");
pd.setMessage("Attendi...");
pd.setIndeterminate(false);
pd.show();
return new SoluzioniLoader(SoluzioniActivity.this, partenza, arrivo, data);
}
#Override
public void onLoadFinished(Loader<List<Soluzione>> loader, List<Soluzione> data) {
try {
pd.dismiss();
} catch(Exception e){
}
if (data == null) {
// ERRORE
} else {
SoluzioniAdapter adapter = new SoluzioniAdapter(SoluzioniActivity.this, partenze, arrivi, date);
mListView.setAdapter(adapter);
}
and of course it doesn't work. I think because the array it's empty.. And i can't understand what i have to do right now. Thanks
In this sectcion you are using the adapter, but I don't see when you are filling "partenze", "arrivi" and "date".
#Override
public void onLoadFinished(Loader<List<Soluzione>> loader, List<Soluzione> data) {
try {
pd.dismiss();
} catch(Exception e){
}
if (data == null) {
// ERRORE
} else {
SoluzioniAdapter adapter = new SoluzioniAdapter(SoluzioniActivity.this, partenze, arrivi, date);
mListView.setAdapter(adapter);
}
I think those values are inside this List<Soluzione> soluzioni but you haver tu put the values in the other three arrays or maybe pass only the array of Soluzione in the adapter
I want to show some contacts information those are stored in a file in the list view.I want each contact to be shown in a separate cell rather than all together in a same place.Now all the contacts are showing in a single cell in the list view.I used a special character to check the end of a contact information.
Thanks in advance :)
Here is my code:
public void show_contacts()
{
final ListView listview = (ListView) findViewById(R.id.listview);
final ArrayList<String> list = new ArrayList<String>();
final ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
String data_read="";
String FILENAME = "myfile.txt";
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = null;
String s1="";
try {
fis = openFileInput("myfile.txt");
byte[] buffer = new byte[1];
while (fis.read(buffer) != -1) {
if(s1.endsWith("."))
{
data_read=fileContent.toString();
list.add(data_read);
}
else
s1+=buffer.toString();
fileContent.append(new String(buffer));
}
} catch (Exception e) {
e.printStackTrace();
}
data_read=fileContent.toString();
list.add(data_read);
listview.setAdapter(adapter);
}
public void Write_to_file(String cName2,String cNumber2)
{
String string=cName2+"--"+cNumber2;
String FILENAME="myfile.txt";
FileOutputStream fos = null;
Context c=this.getBaseContext();
try {
String s=".";
fos = c.openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(string.getBytes());
fos.write(s.getBytes());
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
My wish is you don't write the contact name into text file you Just write your Contacts in the custom Class like
public class Sample {
private String listitem1;
private String listitem2;
public String getListitem1() {
return listitem1;
}
public void setListitem1(String listitem1) {
this.listitem1 = listitem1;
}
public String getListitem2() {
return listitem2;
}
public void setListitem2(String listitem2) {
this.listitem2 = listitem2;
}
}
And use this custom adapter in your program...
public class CustomAdapter extends ArrayAdapter<Sample> {
public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;
public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
super(context, resource);
this.mlist = mlist;
this.context = context;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getPosition(Sample item) {
return super.getPosition(item);
}
#Override
public Sample getItem(int position) {
return mlist.get(position);
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.listitem, null);
TextView text1 = (TextView) convertView.findViewById(R.id.item1);
TextView text2 = (TextView) convertView.findViewById(R.id.item2);
text1.setText(mlist.get(position).getListitem1());
text2.setText(mlist.get(position).getListitem2());
return convertView;
}
}
And use this code into your Activity....
private ArrayList<Sample> mListItems;
private PullToRefreshListView mPullRefreshListView;
private CustomAdapter mAdapter;
private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler", "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_list);
mListItems= new ArrayList<Sample>();
mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
Calculation();
mPullRefreshListView.setAdapter(mAdapter);
}
private void Calculation() {
for(int i=0;i<mStrings.length;i++)
{
Sample sample = new Sample();
sample.setListitem1(mStrings[i]);
sample.setListitem2(mStrings[i]);
mListItems.add(sample);
}
}
And you just replace with you Contact Name and Number in the Above sample..
I'm trying to achieve as a downloader app for Android, only that I can not do a thing. I would like to download multiple files at a time and to display the status of under each in a listview.
I created an Adapter and configuring it all, but when I go to download the files first everything works when unloading the second, the first crashes, at least by the idea that, because the data on the listview of the first download are locked. I would like to manage multiple downloads using AsyncTask in a listview. I tried but I can not.
I also created arrays for the variables used in the AsyncTask.
If you want to place the pieces of the source. Let me know which part you want.
THis is my ArrayAdapter for Listview:
public class MYArrayAdapter extends ArrayAdapter<String>{
//riferimenti statici alle risorse e agli id
private final static int LAYOUT = R.layout.item_view;
private final static int IMMAGINE = R.id.ColImgPath;
private final static int NAMEFILE = R.id.txt_namef;
private final static int VELOCITA = R.id.txt_velocita;
private final static int TIME = R.id.txt_timerima;
private final static int DIMTOT = R.id.txt_dimtota;
private final static int DIMRIM = R.id.txt_dimrim;
private final static int PERCENTUALE = R.id.txt_percent;
private final static int Progress = R.id.prg_progressbar;
//private final static int TITOLO = R.id.riga_listview_titolo;
//private final static int DESCRIZIONE = R.id.riga_listview_descrizione;
//ArrayList<String> IMMAGINE; //lista dei titoli
ArrayList<String> namefile;
ArrayList<String> velocita;
ArrayList<String> time;
ArrayList<String> dimtot;
ArrayList<String> dimrim;
ArrayList<String> percentuale;
ArrayList<String> percento;
//ArrayList<String> descrizioni;
//lista delle descrizioni
Context c; //context
LayoutInflater inflater; //layout inflater
public MYArrayAdapter(Context context, ArrayList<String> namefile, ArrayList<String> velocita,ArrayList<String> time,ArrayList<String> dimtot,ArrayList<String> dimrim,ArrayList<String> percentuale)
{
super(context,NAMEFILE);
this.c = context;
this.namefile = namefile;
this.velocita = velocita;
this.time = time;
this.dimtot = dimtot;
this.dimrim = dimrim;
this.percentuale = percentuale;
this.percento = percento;
this.inflater = LayoutInflater.from(c);
}
#Override
public int getCount()
{
return namefile.size(); //ritorno lunghezza lista ( = numero dei titoli)
}
//quando la lista richiede una view
#Override
public View getView(int pos,View view,ViewGroup parent)
{
CacheRiga cache; //cache
if(view==null)//se � la prima volta che viene richiesta la view
{
// creo la view ma non l'attacco alla lista in quanto devo ancora modificare
// i testi delle textview
view = inflater.inflate(LAYOUT, parent,false);
cache = new CacheRiga(); //inizializzo la cache
cache.namefile = (TextView) view.findViewById(NAMEFILE);
cache.velocita = (TextView) view.findViewById(VELOCITA);
cache.time = (TextView) view.findViewById(TIME);
cache.dimtot = (TextView) view.findViewById(DIMTOT);
cache.dimrim = (TextView) view.findViewById(DIMRIM);
cache.percentuale = (TextView) view.findViewById(PERCENTUALE);
cache.immagine = (ImageView) view.findViewById(IMMAGINE);
cache.progress = (ProgressBar) view.findViewById(Progress);
view.setTag(cache);//collego view con cache
}
else
{
cache = (CacheRiga) view.getTag(); //altrimenti prendo la cache dalla view
}
cache.namefile.setText(namefile.get(pos)); //imposto il titolo
cache.velocita.setText(velocita.get(pos)); // e la descrizione
cache.time.setText(time.get(pos)); //imposto il titolo
cache.dimtot.setText(dimtot.get(pos)); // e la descrizione
cache.dimrim.setText(dimrim.get(pos)); //imposto il titolo
cache.percentuale.setText(percentuale.get(pos)); // e la descrizione
cache.immagine.setImageResource(R.drawable.file); //imposto il titolo
cache.progress.setProgress((int) Tab_Download.progresso[pos]); // e la descrizione
return view;
}
private class CacheRiga { // classe per la cache delle righe
public TextView namefile; // cache titolo
public TextView velocita; // cache descrizione
public TextView time; // cache titolo
public TextView dimtot;
public TextView dimrim; // cache titolo
public TextView percentuale;
public ImageView immagine; // cache titolo
public ProgressBar progress;
}
}
This is void onProgressUpdate (AsyncTask):
speed[cont] = NANOS_PER_SECOND / BYTES_PER_MIB * totalRead[cont] / (System.nanoTime() - start[cont] + 1);
dimrim[cont] = ((((file_sizes[cont] * 1024) * 1024) - ((int) (totalRead[cont]))) / 1024) / 1024;
timerimas[cont] = (int) ((dimrim[cont] ) / speed[cont]);
ore[cont] = timerimas[cont] / 3600;
minuti[cont] = (timerimas[cont] % 3600) / 60;
secondi[cont] = timerimas[cont] - (ore[cont] * 3600) - (minuti[cont] * 60);
progresso[cont] = (totalRead[cont] * 100) / lenghtOfFile[cont];
velocita.set(cont,"Velocita' Download:" + df.format(speed[cont]) + "Mbyte/s");
namefile.set(cont,"Nome File:"+file_name[cont]);
time.set(cont,"Tempo Rimanente:"+ore[cont]+"H| "+ minuti[cont] +"M| " + secondi[cont]+"S ");
dimtot.set(cont,"Dimensione file:"+(file_sizes[cont]) + "MB");
dimrimas.set(cont,"Dimensione Rimanente:" + dimrim[cont] + "MB");
percentuale.set(cont, "Percentuale:" + progresso[cont] + "%");
//list.setAdapter(adapter);
adapter.notifyDataSetChanged();
I have a AsyncHttpDownloader library on github, it is a very example to learn http downloads.
What this library does is exactly to manage multiple downloads using AsyncTask. You can have a look at the code.
First step is create an image download callback method and download the image inside your adapter.
/**
* This code is to update the progress bar in the listView
* #param view
* #param downloadUrl
* #param total
* #param progress
*/
public void updateDownloadProgress(View view, String downloadUrl, int total, int progress){
ViewHolder viewHolder = (ViewHolder)view.getTag();
DataItem dataItem = dataList.get(viewHolder.position);
// If the download urls not match, will not continue.
if (!dataItem.imageUrl.equals(downloadUrl)) return;
viewHolder.progressBar.setMax(total);
viewHolder.progressBar.setProgress(progress);
}
/**
* This code is to call to set the image to the view from the activity.
* #param view
* #param fileUrl
*/
public void setImageViewWhenDownloadFinished(View view, String downloadUrl, String fileUrl){
ViewHolder viewHolder = (ViewHolder)view.getTag();
// If the download urls not match, will not continue.
if (!dataItem.imageUrl.equals(downloadUrl)) return;
Bitmap bmp = BitmapFactory.decodeFile(fileUrl);
viewHolder.imageView.setImageBitmap(bmp);
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if (view == null){
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_layout, null);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView)view.findViewById(R.id.imageView);
viewHolder.progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)view.getTag();
}
viewHolder.position = position;
DataItem dataItem = dataList.get(position);
// Download the image file
AsyncHttpDownloader.getInstance().addDownloadTask(this, dataItem.imageUrl);
return view;
}
Second step is register a listener on your activity
//Instantiate a new listener
AsyncHttpDownloaderListener downloaderListener = new AsyncHttpDownloaderListener(
new AsyncHttpDownloaderListener.Callback() {
#Override
public void onProgressUpdate(String downloadUrl, int total, int completed) {
// Update to progress bar
for (int i = 0; i < listView.getChildCount(); i++){
adapter.updateDownloadProgress(listView.getChildAt(i), downloadUrl, total, completed);
}
}
#Override
public void onFailed(String downloadUrl, String errorMessage) {
}
#Override
public void onSuccess(String downloadUrl, File file) {
//When the download finished, the assign the image to the imageView
for (int i = 0; i < listView.getChildCount(); i++){
adapter.setImageViewWhenDownloadFinished(listView.getChildAt(i), file.getAbsolutePath());
}
}
});
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
downloaderListener.register(this);
}
and finally don't forget to unregister the listener on your activity destroy
#Override
public void onDestroy(){
downloaderListener.unregister(this);
// When the activity is destroyed, cancel all running tasks if you want.
// If you don't cancel, it will run in the background until all tasks are
// done, when you open the activity again, you can still see the running task.
AsyncHttpDownloader.getInstance().cancelAllRunningTasks();
super.onDestroy();
}
Writing codes on Stackoverflow is kind of hard huh.