Multi Downloader With ListView Asynctask - java

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.

Related

Android ListViewItem update Progressbar in row

I'm using ListView with custom list rows,where every ListItem has ProgressBar in it.
When the user click the ImageView,the app starts an AsyncTask to download a file from a remote server,and update the progress in progress bar.
I'm using Parallel async tasks,which mean app can launch multiple downloads and update them in the ProgressBar of each row.
This is the code
static class ViewHolder {
protected TextView title;
protected TextView size;
protected TextView version;
protected ImageView appIcon;
protected ProgressBar progressBar;
}
public class UpdateAdapter extends ArrayAdapter<UpdateItem> {
public UpdateAdapter(Context context, ArrayList<UpdateItem> users) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
UpdateItem updateItem = getItem(position);
View v = convertView;
ViewHolder viewHolder;
LayoutInflater mInflater = LayoutInflater.from(getContext());
if (convertView == null) { // if convertView is null
convertView = mInflater.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.apptitlelabel);
viewHolder.version = (TextView) convertView.findViewById(R.id.versionlabel);
viewHolder.size = (TextView) convertView.findViewById(R.id.sizelabel);
viewHolder.appIcon = (ImageView) convertView.findViewById(R.id.appicon);
viewHolder.progressBar = (ProgressBar) convertView.findViewById(R.id.downloadProgressBar);
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) v.getTag();
viewHolder.progressBar.setProgress(0);
View finalConvertView = convertView;
viewHolder.appIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadFileFromURL task = new DownloadFileFromURL();
task.position = position;
task.v = finalConvertView;
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, updateItem.downloadlink);
}
});
return convertView;
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
**/
int position;
View v;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
**/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
String fileExtenstion = MimeTypeMap.getFileExtensionFromUrl(url.getPath());
String fname = URLUtil.guessFileName(url.getPath(), null, fileExtenstion);
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString() + "/" + fname);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
**/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// Log.w(TAG, progress[0]);
updateStatus(position, Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
Log.w(TAG, "onPostExecute: ");
removeListItem(v, position);
}
}
public void updateStatus(int index, int Status) {
int in = index - updateLv.getFirstVisiblePosition();
View v = updateLv.getChildAt(in);
ProgressBar progress = (ProgressBar) v.findViewById(R.id.downloadProgressBar);
progress.setProgress(Status);
}
The problem is ,when the user starts two downloads(say hit the first the second imageviews),and the first task has been completed,and the first row getting removed from the list,in onPostExecute,now,the second row turns into the first row,but the task updates the current second row(which was the third before the first item removed...)
I know it happens because I pass into updateStatus,the position of the item to be updated,but in the meantime the ListView Changes and removes items(because their download has been completed),but I have no current solution for this...
I even tried passing a ProgressBar object reference to updateStatus method ,instead of using item position,and I thought it would solve the problem...but no luck :)

How to get color of time table on events?

I am creating an events. Also I am creating time tables. Events are created based on time table id. Dynamic event view I have created to show events.
I have created two tables for this events and time table. And loaded events from database.
Now I have loaded the events from time table witch is enabled. I have set color to time tables. This color I want to show on events with respected time table id.
I tried to load this color using Time table's object.
But I have used for loop so it's showing color of last time table to all events.
How can I set color to event's with respected time table id?
Monday fragment :
public class Mon extends Fragment {
private EventTableHelper mDb;
private Intent i;
private ViewGroup dayplanView;
private int minutesFrom,minutesTo;
private List<EventData> events;
private List<View> list;
private List<TimeTable> tables;
private LayoutInflater inflater;
public boolean editMode;
private RelativeLayout container;
private View eventView;
private TimeTableHelper tableHelper;
int color;
private boolean mCheckFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mon, container, false);
list = new ArrayList<View>();
dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout);
showEvents();
mCheckFragment = true;
return view;
}
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,final int id,int color,String notification) {
eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
list.add(eventView);
ImageView notify = (ImageView) eventView.findViewById(R.id.notify);
((GradientDrawable) eventView.getBackground()).setColor(color);
tvTitle.setTextColor(Color.parseColor("#FFFFFF"));
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
if(notification == null)
{
notify.setVisibility(View.GONE);
}
else {
notify.setVisibility(View.VISIBLE);
}
if(location.equals(""))
{
tvTitle.setText("Event : " + title);
} else {
tvTitle.setText("Event : " + title + " (At : " + location +")");
}
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(), AddEventActivity.class);
editMode = true;
i.putExtra("EditMode", editMode);
i.putExtra("id", id);
startActivityForResult(i, 1);
}
});
}
public void showEvents()
{
tableHelper = new TimeTableHelper(getActivity());
tables = tableHelper.getAllTables();
for (TimeTable table : tables) {
int tableId = table.getId();
int status = table.getStatus();
if(status == 1) {
color = table.getTableColor();
}
mDb = new EventTableHelper(getActivity());
events = mDb.getTimeTableEvents("Mon", tableId);
}
for (EventData eventData : events) {
int id = eventData.getId();
String datefrom = eventData.getFromDate();
if (datefrom != null) {
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
String title = eventData.getTitle();
String location = eventData.getLocation();
String dateTo = eventData.getToDate();
String notification = eventData.getNotificationTime();
if (dateTo != null) {
//times = dateTo.substring(11,16).split(":");
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id, color, notification);
id++;
}
}
public void removeView()
{
for(int i=0; i<list.size(); i++)
{
View view = (View)list.get(i);
dayplanView.removeView(view);
}
}
private int dpToPixels(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
#Override
public void onResume()
{
super.onResume();
if(mCheckFragment)
{
removeView();
showEvents();
}
}
}
EDIT:
public void showEvents()
{
tableHelper = new TimeTableHelper(getActivity());
tables = tableHelper.getAllTables();
int color = 0;
for (TimeTable table : tables) {
int tableId = table.getId();
int status = table.getStatus();
mDb = new EventTableHelper(getActivity());
events = mDb.getTimeTableEvents("Mon", tableId);
for (EventData eventData : events) {
int id = eventData.getId();
String datefrom = eventData.getFromDate();
if (datefrom != null) {
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
String title = eventData.getTitle();
String location = eventData.getLocation();
String dateTo = eventData.getToDate();
color = table.getTableColor();
String notification = eventData.getNotificationTime();
if (dateTo != null) {
//times = dateTo.substring(11,16).split(":");
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id, color, notification);
id++;
}
}
}
Thank you..
Try merging the two for loops together and see if that works..
as well as the color, it also looks like the events are set to the last table when it enters the second for loop.
for(TimeTable table : tables) {
// code from table for loop
// ...
for(EventData eventData : events) {
// code from event for loop.
// ...
}
}

Add data to listview using loadMore on scroll

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
}

Can't understand how insert data in list from adapter [closed]

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

How can I avoid calling of getView() method of adapter class when I tap on listitems?

I have implemented list view having buttons having background image changing effects.but, when I tap on any list item, that effect is no longer present there and get refreshed.
I checked that, when I tap on any list item, that getView() is calling...
How to avoid this???
please suggest any solution if anyone knows...
Thank you..
code is :
public class EventListAdapter extends BaseAdapter {
private static final int VISIBLE = 0;
private static final int GONE = 8;
private List<Events> dateForEventList;
private String eventsRetrived;
private String[] events;
boolean clickStatus = false;
private int status = 0;
public EventListAdapter(Context context)
{
mContext = context;
}
/**
* The number of items in the list is determined by the number of announcements
* in our array.
*
* #see android.widget.ListAdapter#getCount()
*/
public int getCount() {
DatabaseManager db = new DatabaseManager(mContext);
dateForEventList = db.getAllData1(CalendarAdapter.dateOfEventSingle);
for (Events l : dateForEventList) {
eventsRetrived = l.getEventData();
}
events = eventsRetrived.split(",");
return events.length;
}
/**
* Since the data comes from an array, just returning
* the index is sufficent to get at the data. If we
* were using a more complex data structure, we
* would return whatever object represents one
* row in the list.
*
* #see android.widget.ListAdapter#getItem(int)
*/
public Object getItem(int position) {
return position;
}
/**
* Use the array index as a unique id.
* #see android.widget.ListAdapter#getItemId(int)
*/
public long getItemId(int position) {
return position;
}
public View getView(final int position, View myView, ViewGroup parent) {
if(myView == null) {
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.activity_event_list, null);
}
TextView textViewTitle;
TextView textViewDialogue;
final ImageButton buttonForCheckMark;
final ImageButton buttonForDelete;
final ImageButton buttonForRemainder;
//Events event = new Events("11/2/2013","today, there is function in Shivajinagar");
// event.setDate("11 Jan,2013");
// String event1 = event.getDate();
//
// textViewForDateHeader = (TextView)myView.findViewById(R.id.textViewHeadingDate);
// textViewForDateHeader.setText(event1);
DatabaseManager db = new DatabaseManager(mContext);
dateForEventList = db.getAllData1(CalendarAdapter.dateOfEventSingle);
for (Events l : dateForEventList) {
eventsRetrived = l.getEventData();
}
events = eventsRetrived.split(",");
// TextView tv = (TextView)myView.findViewById(R.id.grid_item_text);
// tv.setText(events[position]);
textViewTitle = (TextView) myView.findViewById(R.id.textViewTitle);
textViewTitle.setText(events[position]);
textViewDialogue = (TextView) myView.findViewById(R.id.textViewDialog);
textViewDialogue.setText(events[position]);
textViewDialogue.setVisibility(mExpanded[position] ? VISIBLE : GONE);
// textViewHeader = (TextView)myView.findViewById(R.id.textViewHeader);
// textViewHeader.setText(mHeader[position]);
// textViewHeader.setVisibility(mExpanded[position] ? VISIBLE : GONE);
buttonForCheckMark = (ImageButton) myView.findViewById(R.id.buttonForCheckMark);
buttonForCheckMark.setVisibility(mExpanded[position] ? VISIBLE : GONE);
buttonForDelete = (ImageButton) myView.findViewById(R.id.buttonForDelete);
buttonForDelete.setVisibility(mExpanded[position] ? VISIBLE : GONE);
buttonForRemainder = (ImageButton) myView.findViewById(R.id.buttonForRemainder);
buttonForRemainder.setVisibility(mExpanded[position] ? VISIBLE : GONE);
buttonForRemainder.setOnClickListener(new OnClickListener() {
#SuppressWarnings("static-access")
#SuppressLint("SimpleDateFormat")
public void onClick(View v) {
try {
Toast.makeText(mContext, "remainder saved..", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Toast.makeText(mContext, "Exception in Remainder " + ex.toString(), Toast.LENGTH_SHORT).show();
}
//
}
});
buttonForCheckMark.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Toast.makeText(mContext, "tapped on checkMark", Toast.LENGTH_SHORT).show();
Toast.makeText(mContext, " current Position tapped : " + position, Toast.LENGTH_SHORT).show();
if(position == 0) {
buttonForCheckMark.setBackgroundResource(R.drawable.ic_launcher);
buttonForDelete.setBackgroundResource(R.drawable.ic_navigation_cancel);
buttonForCheckMark.setClickable(false);
buttonForDelete.setClickable(true);
}
// change the status to 1 so the at the second clic , the else will be executed
// else {
// button.setBackgroundResource(R.drawable.ic_navigation_accept);
// status =0;//change the status to 0 so the at the second clic , the if will be executed
// }
// buttonForCheckMark.setBackgroundResource(R.drawable.ic_drawer);
}
});
buttonForDelete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(mContext, "tapped on delete", Toast.LENGTH_SHORT).show();
if(position == 0) {
buttonForCheckMark.setBackgroundResource(R.drawable.ic_navigation_accept);
buttonForCheckMark.setClickable(true);
buttonForDelete.setBackgroundResource(R.drawable.ic_drawer);
buttonForDelete.setClickable(false);
// change the status to 1 so the at the second clic , the else will be executed
}
}
});
return myView;
}
public void toggle(int position) {
mExpanded[position] = !mExpanded[position];
notifyDataSetChanged();
}
/**
* Remember our context so we can use it when constructing views.
*/
private Context mContext;
/**
* Our data, part 1.
*/
private String[] mTitles =
{
"Event 1",
"Event 2",
"Event 3",
"Event 4",
"Event 5"
};
/**
* Our data, part 2.
*/
private String[] mDialogue =
{
"wuszuogwfuieffufuhuysugdueljwihadghgxdhgyhghsdgyigwuweyuqaGDHGYHGHGAdhgyhigxgxgeuyehu.",
"dgusduugyujguegytgujgdugwjhiuyg7wtqUYGYYgyijyiufufjguhgdugfhgfhgfgfhgfhghfghifgyi,dgwsdtgyfytfiuwt,",
"rtygygghtudggyjhgujtugdhhguyuaUUUUDJYUIDHUJHDIIDUJDHDUJHDIDIOUYhujtdugyhdgg",
"gjhuwjsgudggdudgjqhasdgdhgjdhushjaguhguwegagsdgygydgfgdcgycg",
"fhdgyhdfhfgdyhhwsddgyuduuufguugwugdfgugdgooduiuduiuduuduiuiuidudiiwdiou"
};
/**
* Our data, part 3.
*/
private boolean[] mExpanded =
{
false,
false,
false,
false,
false,
false,
false,
false
};
// private Integer[] mThumbIds = {
// R.drawable.remainder, R.drawable.remainder,
// R.drawable.remainder, R.drawable.remainder,
// R.drawable.remainder
//
// };
}
You cannot stop getView() method to be called automatically but you can solve your problem in alternative way.
You are inflating this layout to adapter
R.layout.activity_event_list
I am assuming your parent for this layout is Relative Layout with id as #+id/parent
Now in your getView method set the background color of row like this.
RelativeLayout parentLayout=(RelativeLayout)findViewById(R.id.parent);
parentLayout.setBackgroundColor(Color.WHITE);

Categories