简体   繁体   English

使用AsyncTask更新ListView项目

[英]Updating ListView items with AsyncTask

I have the follow scenario: 我有以下情况:

One activity that consults values from internet and fills an object below: 一项从互联网咨询价值并填写以下对象的活动:

public class LPBean {

private Lin lin;
private Posted posted;
public Lin getLin() {
    return lin;
}
public void setLin(Lin lin) {
    this.lin = lin;
}
public Posted getPosted() {
    return posted;
}
public void setEstimativa(Posted p) {
    this.posted = p;
}
}

My activity fill the lin information in LPBean from internet and pass the object to CustomAdapter 我的活动从互联网上将LP信息填充到LPBean中,然后将对象传递给CustomAdapter

But the posted value from LPBean is populated with information from the internet and the search key is lin.id (form LPBean),so tho do this, I'm using a AsynkTask. 但是LPBean的发布值中填充了来自互联网的信息,搜索键是lin.id(来自LPBean),因此,我正在使用AsynkTask。

Thus, the listView is showing to user and the posted values (from LpBean) are displayed dynamically with listView opened. 因此,listView向用户显示,并且在打开listView的情况下动态显示了发布的值(来自LpBean)。

To do this, I make like below: 为此,我将如下所示:

public class ListaLinsAdapter extends BaseAdapter {
    private Context context;
    private List<LinPostedBean> lins;
    private LayoutInflater inflater;
    private ViewHolder holder;
    private String idLin;

public ListaLinsAdapter(Context context, List<LinPostedBean> listaLins) {
    this.context = context;
    this.lins = listaLins;
    this.inflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
    return lins.size();
}

@Override
public Object getItem(int position) {
    return lins.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    // Recupera o estado da posição atual
    LinPostedBean lpBean = lins.get(position);
    Lin lin = lpBean.getLin();
do somthing.....

and at the end of the getView method from adapter, is verified if has value to posted attribute to show the information 并在适配器的getView方法结尾处,验证是否具有对posted属性的值以显示信息

        if((lpBean.getPosted() != null) && (lpBean.getPosted().getPonto() != null))
    {
        if(lpBean.getPosted().getPonto().size() > 0)
            holder.fillPosted(lpBean.getPosted());
        else
            holder.showMsg(context.getResources().getString(R.string.msgEmptyPosted));
    }


    return view;
}

In my activity I have implemented the AsyncTask inner class like below: 在我的活动中,我实现了AsyncTask内部类,如下所示:

private class ConsultaPostedBackGround extends AsyncTask<Object, Void, Object[]> {

    @Override
    protected Object[] doInBackground(Object... objs) {
            try {
                LinPostedBean lpBean = (LinPostedBean)objs[0];
                Context context = (Context)objs[3];
                String linId = lpBean.getLin().getLin();
                int indice = linId.indexOf("-");
                linId = linId.substring(0,indice).trim();
//GET INFORMATION FROM INTERNET
                PostedUtil pUtil = new PostedUtil(pontoId.trim(), linId,
                        context);

//PUT INTERNET RESULT IN Posted ATTRUBUTE IN ADAPTER
                Integer position = (Integer)objs[1];
                ((LinPostedBean)((ListaLinsAdapter)objs[2]).getItem(position)).setEstimativa(pUtil.getPosted());

            } catch (Exception e) {
                objs[3] = null;
            }
        return objs;
    }

    @Override
    protected void onPostExecute(Object[] result) {
//REFRESH LISTVIEW
        if(result[3] != null)
            ((ListaLinsAdapter)result[2]).notifyDataSetChanged();
    }

In the activity I'm call the AsyncTask one time to each lin, like below: 在活动中,我每次都向每个lin调用AsyncTask,如下所示:

ListView lista = (ListView) findViewById(R.id.listView);
    lista.setAdapter(listaLinsAdapter);
    lista.setOnItemClickListener(this);

    int cont = 0;
    for (LinPostedBean lpBean : listaLPBean) {
        Object[] params = new Object[4];
        params[0] = lpBean;
        params[1] = new Integer(cont);
        params[2] = listaLinsAdapter;
        params[3] = this;
//CALL TO AsyncTask
        new ConsultaPrevisaoBackGround().execute(params);
        cont++;
    }

I think that this strategy are correct, but not working. 我认为这种策略是正确的,但没有用。 The values of posted is not showing in listview. 列表视图中未显示发布的值。

What is wrong?? 怎么了??

UPDATED 更新

My class Adapter: 我的班级适配器:

public class ListaLinsAdapter extends BaseAdapter {
private Context context;
private List<LinPostedBean> lins;
private LayoutInflater inflater;
private ViewHolder holder;
private String idLin;

public ListaLinsAdapter(Context context, List<LinPostedBean> listaLins) {
    this.context = context;
    this.lins = listaLins;
    this.inflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
    return lins.size();
}

@Override
public Object getItem(int position) {
    return lins.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    // Recupera o estado da posição atual
    LinPostedBean lpBean = lins.get(position);
    Lin lin = lpBean.getLin();

    if (view == null) {
        view = inflater.inflate(R.layout.listadadoslins, null);
        holder = new ViewHolder(context);
        // Número da lin
        holder.txtIdLin = (TextView) view.findViewById(R.id.txtIdLin);
        // Nome da lin
        holder.txtNomeLin = (TextView) view
                .findViewById(R.id.txtNomeLin);

        // Seta campo de informação sem parada
        holder.txtMsgSemParada = (TextView) view
                .findViewById(R.id.msgSemParada);

        // seta layouts de previsão
        holder.llLin1 = (LinearLayout) view
                .findViewById(R.id.linearPrevisoes1);
        holder.llLin2 = (LinearLayout) view
                .findViewById(R.id.linearPrevisoes2);
        holder.llLin3 = (LinearLayout) view
                .findViewById(R.id.linearPrevisoes3);

        // Seta campos de previsão
        holder.txtPrev1 = (TextView) view.findViewById(R.id.txtPrev1);
        holder.txtPrev2 = (TextView) view.findViewById(R.id.txtPrev2);
        holder.txtPrev3 = (TextView) view.findViewById(R.id.txtPrev3);
        holder.txtPrev4 = (TextView) view.findViewById(R.id.txtPrev4);
        holder.txtPrev5 = (TextView) view.findViewById(R.id.txtPrev5);
        holder.txtPrev6 = (TextView) view.findViewById(R.id.txtPrev5);

        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
        holder.reset();
    }

    String lin = lin.getLin().trim();
    StringTokenizer stk = new StringTokenizer(lin, "-");

    // Número da lin
    idLin = stk.nextToken();
    holder.txtIdLin.setText(idLin);

    // Nome da lin
    holder.txtNomeLin.setText(stk.nextToken());

    //new ConsultaPostedBackGround().execute("");
    if((lpBean.getPosted() != null) && (lpBean.getPosted().getPonto() != null))
    {
        if(lpBean.getPosted().getPonto().size() > 0)
            holder.fillPosted(lpBean.getPosted());
        else
            holder.showMsg(context.getResources().getString(R.string.msgSemPosted));
    }


    return view;
}

static class ViewHolder {
    Context context;
    TextView txtIdLin;
    TextView txtNomeLin;
    TextView txtMsgSemParada;

    LinearLayout llLin1;
    LinearLayout llLin2;
    LinearLayout llLin3;

    TextView txtPrev1;
    TextView txtPrev2;
    TextView txtPrev3;
    TextView txtPrev4;
    TextView txtPrev5;
    TextView txtPrev6;

    public ViewHolder(Context cont) {
        this.context = cont;
    }

    public void reset() {
        txtIdLin.setText(null);
        txtNomeLin.setText(null);
        limpaPrevisoes();
    }

    private void limpaPrevisoes() {
        llLin1.setVisibility(View.GONE);
        llLin2.setVisibility(View.GONE);
        llLin3.setVisibility(View.GONE);
        txtMsgSemParada.setVisibility(View.GONE);

        txtPrev1.setText(null);
        txtPrev2.setText(null);
        txtPrev3.setText(null);
        txtPrev4.setText(null);
        txtPrev5.setText(null);
        txtPrev6.setText(null);
    }

    public void showError() {
        showMsg(context.getResources().getString(R.string.msgErroPosted));
    }

    public void showMsg(String msg) {
        limpaPrevisoes();
        txtMsgSemParada.setText(msg);
    }

    public void fillPosted(Posted p) {
        Collections.sort(p.getPonto());

        if (p.getPonto().size() > 6) {
            for (int i = 6; i < p.getPonto().size(); i++)
                p.getPonto().remove(i);
        }

        int cont = 1;
        for (Estimativa estimativa : p.getPonto()) {
            setPosted(cont, estimativa, p);
            cont++;
        }

        if (p.getPonto().size() <= 2) {
            llLin2.setVisibility(View.GONE);
            llLin3.setVisibility(View.GONE);
        }

        if ((p.getPonto().size() > 2) && (p.getPonto().size() <= 4))
            llLin3.setVisibility(View.GONE);

    }

    // Preenche o campo referente à estimativa
    private void setPosted(int id, Estimativa estimativa,
            Posted posted) {

        switch (id) {
        case 1:
            txtPrev1.setText(getgetPostedFormatedPosted(posted, estimativa));
            setBackGroundColor(estimativa, txtPrev1);
            break;
        case 2:
            txtPrev2.setText(getgetPostedFormatedPosted(posted, estimativa));
            setBackGroundColor(estimativa, txtPrev2);
            break;
        case 3:
            txtPrev3.setText(getgetPostedFormatedPosted(posted, estimativa));
            setBackGroundColor(estimativa, txtPrev3);
            break;
        case 4:
            txtPrev4.setText(getgetPostedFormatedPosted(posted, estimativa));
            setBackGroundColor(estimativa, txtPrev4);
            break;
        case 5:
            txtPrev5.setText(getgetPostedFormatedPosted(posted, estimativa));
            setBackGroundColor(estimativa, txtPrev5);
            break;
        case 6:
            txtPrev6.setText(getgetPostedFormatedPosted(posted, estimativa));
            setBackGroundColor(estimativa, txtPrev6);
            break;
        default:
            break;
        }

    }

    private String getgetPostedFormatedPosted(Posted posted,
            Estimativa estimativa) {
        String hourStr;
        String minutoStr;
        long hourAtual = Long.parseLong(posted.getHorarioAtual());
        long seconds = (estimativa.getHorarioPacote() - hourAtual) / 1000;
        int week = (int) Math.floor(seconds / 604800);
        seconds -= week * 604800;
        int dias = (int) Math.floor(seconds / 86400);
        seconds -= dias * 86400;
        int hours = (int) Math.floor(seconds / 3600);
        seconds -= hours * 3600;
        int minutes = (int) Math.floor(seconds / 60);
        seconds -= minutes * 60;

        minutes += 1;

        if (hours < 10)
            hourStr = "0" + hours;
        else
            hourStr = String.valueOf(hours);

        if (minutes < 10)
            minutoStr = "0" + minutes;
        else
            minutoStr = String.valueOf(minutes);

        String tempo;
        if (hours > 0)
            tempo = hourStr + "h " + minutoStr + "min";
        else
            tempo = minutoStr + "min";

        SimpleDateFormat spf = new SimpleDateFormat("HH:mm:ss");
        tempo = tempo + " às "
                + spf.format(estimativa.getHorarioEstimado());
        return tempo;
    }

    private void setBackGroundColor(Estimativa estimativa, TextView txtView) {
        // Imagem a ser exibida
        switch (estimativa.getStatus()) {
        case 0:
            txtView.setBackgroundColor(context.getResources().getColor(
                    R.color.postedVerde));
            break;
        case 1:
            txtView.setBackgroundColor(context.getResources().getColor(
                    R.color.postedLaranja));
            break;
        case 2:
            txtView.setBackgroundColor(context.getResources().getColor(
                    R.color.postedVermelha));
            break;
        default:
            break;
        }
    }
}
}

My xml of a item in listView 我在listView中的项目的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/txtIdLinha"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingLeft="6dp"
        android:paddingRight="4dp"
        android:paddingTop="4dp"
        android:text="184"
        android:textColor="@color/blue_nightsky"
        android:textSize="20sp"
        android:textStyle="bold" />

    <LinearLayout
        android:id="@+id/llPrevisoes"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/linearTit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/txtNomeLinha"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="7dp"
                android:text="FFFFFF"
                android:textColor="@drawable/dialog_itemtextlist_selector"
                android:textStyle="bold" >
            </TextView>

            <TextView
                android:id="@+id/msgSemParada"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="7dp"
                android:text="@string/msgSemPrevisao"
                android:textColor="@drawable/dialog_itemtextlist_selector"
                android:textSize="12sp"
                android:textStyle="bold"
                android:visibility="gone" >
            </TextView>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearPrevisoes1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp">

            <TextView
                android:id="@+id/txtPrev1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text=""
                android:textColor="@color/white"
                android:textSize="12dp" >
            </TextView>

            <TextView
                android:id="@+id/txtPrev2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text=""
                android:textColor="@color/white"
                android:textSize="12dp" >
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearPrevisoes2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp" >

            <TextView
                android:id="@+id/txtPrev3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text=""
                android:textColor="@color/white"
                android:textSize="12dp" >
            </TextView>

            <TextView
                android:id="@+id/txtPrev4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text=""
                android:textColor="@color/white"
                android:textSize="12dp" >
            </TextView>


        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearPrevisoes3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp">

            <TextView
                android:id="@+id/txtPrev5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text=""
                android:textColor="@color/white"
                android:textSize="12dp" >
            </TextView>

            <TextView
                android:id="@+id/txtPrev6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text=""
                android:textColor="@color/white"
                android:textSize="12dp" >
            </TextView>

        </LinearLayout>
    </LinearLayout>

</LinearLayout>

UPDATED 更新

Solved, the problem was in my adapter. 解决了,问题出在我的适配器上。

Try adding the following to your ListaLinsAdapter. 尝试将以下内容添加到ListaLinsAdapter中。

public void add(LinPostedBean lpb){
    lins.add(lpb);
    notifyDataSetChanged();
}

Then call that in doInBackground and you don't need to use onPostExecute in this case. 然后在doInBackground调用它,在这种情况下您不需要使用onPostExecute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM