我应该在哪里设置我的代码的 listView?

Posted

技术标签:

【中文标题】我应该在哪里设置我的代码的 listView?【英文标题】:Where should I set the listView on my code? 【发布时间】:2015-09-06 18:44:24 【问题描述】:

我的应用程序运行正常,我从适配器获取数据,但ListView 只在屏幕上闪烁并返回到之前的Activity,没有显示数据! LogCat 中没有显示错误。我已经尝试了一切!我该怎么办?

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class CaronasBuscadasListActivity extends ListActivity 

    // Progress Dialog
    private ProgressDialog pDialog;

    ListView listView;
    String id_carona, _id_motorista, origem, destino, data, hora, nome;
    public Bitmap imagem;



    private LayoutInflater mInflater;

    //JSON IDS:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_ID = "_id_carona";
    private static final String TAG_ORIGEM = "origem_carona";
    private static final String TAG_DESTINO = "destino_carona";
    private static final String TAG_DATA = "data_carona";
    private static final String TAG_HORA = "hora_carona";
    private static final String TAG_NOME = "nome_usuario";
    private static final String TAG_IMAGEM = "imagem_usuario";
    private static final String TAG_MESSAGE = "mensagem";
    private static final String TAG_CARONAS = "caronas";
    private static final String TAG_ID_MOTORISTA = "_id_motorista";


    //An array of all of our comments
    private JSONArray mCaronas = null;
    private CarAdapter carAdapter;
    private JSONParser jsonParser = new JSONParser();
    private JSONObject json;


    //manages all of our comments in a list.
    private ArrayList<HashMap<String, Object>> mCaronasList;



    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buscadas_list);
        mCaronasList = new ArrayList<HashMap<String, Object>>();
        listView = getListView();
    

    @Override
    protected void onResume() 
        // TODO Auto-generated method stub
        super.onResume();
        new BuscarCarona().execute();
    

    /**
     * Retrieves json data of comments
     */
    public void updateJSONdata(JSONObject jsonObject) 

        json = jsonObject;
        Log.d("JSONOOBJECT", json.toString());

        //when parsing JSON stuff, we should probably
        //try to catch any exceptions:
        try 

            mCaronas = json.getJSONArray(TAG_CARONAS);

            // looping through all posts according to the json object returned
            for (int i = 0; i < mCaronas.length(); i++) 
                JSONObject c = mCaronas.getJSONObject(i);

                //gets the content of each tag

                _id_motorista = c.getString(TAG_ID_MOTORISTA);
                origem = c.getString(TAG_ORIGEM);
                destino = c.getString(TAG_DESTINO);
                data = c.getString(TAG_DATA);
                hora = c.getString(TAG_HORA);
                nome = c.getString(TAG_NOME);
                String image = c.getString(TAG_IMAGEM);
                byte[] img = Base64.decode(image, Base64.DEFAULT);
                ByteArrayInputStream img_user = new ByteArrayInputStream(img);
                imagem = BitmapFactory.decodeStream(new FlushedInputStream(img_user));

                HashMap<String, Object> map = new HashMap<String, Object>();

                map.put(TAG_ID, _id_motorista);
                map.put(TAG_ORIGEM, origem);
                map.put(TAG_DESTINO, destino);
                map.put(TAG_DATA, data);
                map.put(TAG_HORA, hora);
                map.put(TAG_NOME, nome);
                map.put(TAG_IMAGEM, imagem);

                mCaronasList.add(map);
                Log.d("map", map.toString());
            

            Log.d("mCaronasList", mCaronasList.toString());
            carAdapter = new CarAdapter(this, mCaronasList);

         catch (JSONException e) 
            Log.d("erro", e.toString());
            e.printStackTrace();
        
    

    static class FlushedInputStream extends FilterInputStream 
        public FlushedInputStream(InputStream inputStream) 
            super(inputStream);
        

        @Override
        public long skip(long n) throws IOException 
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < n) 
                long bytesSkipped = in.skip(n - totalBytesSkipped);
                if (bytesSkipped == 0L) 
                    int b = read();
                    if (b < 0) 
                        break;  // we reached EOF
                     else 
                        bytesSkipped = 1; // we read one byte
                    
                
                totalBytesSkipped += bytesSkipped;
            
            return totalBytesSkipped;
        
    

    class BuscarCarona extends AsyncTask<String, String, String> 

        @Override
        protected String doInBackground(String... args) 

            int success;
            String origem = getIntent().getExtras().getString("origem");
            String destino = getIntent().getExtras().getString("destino");
            String data = getIntent().getExtras().getString("data");

            try 
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // Building Parameters
                params.add(new BasicNameValuePair("origem", origem));
                params.add(new BasicNameValuePair("destino", destino));
                params.add(new BasicNameValuePair("data", data));

                Log.d("request!", "starting");

                //Posting user data to script
                JSONObject jsonObject = jsonParser.makeHttpRequest(
                        POST_COMMENT_URL, "POST", params);

                updateJSONdata(jsonObject);

                // full json response
                Log.d("Tentativa de adicionar carona!", jsonObject.toString());

                // json success element
                success = jsonObject.getInt(TAG_SUCCESS);
                if (success == 1) 
                    Log.d("Carona Disponivel!", jsonObject.toString());
                    finish();
                    return jsonObject.getString(TAG_MESSAGE);
                 else 
                    Log.d("Falha ao adicionar carona!", jsonObject.getString(TAG_MESSAGE));
                    return jsonObject.getString(TAG_MESSAGE);
                
             catch (JSONException e) 
                e.printStackTrace();
            

            return null;
        

        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            pDialog = new ProgressDialog(CaronasBuscadasListActivity.this);
            pDialog.setMessage("Posting Comment...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();        

        @Override
        protected void onPostExecute(String file_url) 
            // dismiss the dialog once product deleted
            pDialog.dismiss();


            if (file_url != null) 
                Toast.makeText(CaronasBuscadasListActivity.this, file_url, Toast.LENGTH_LONG).show();
            
        
    

【问题讨论】:

【参考方案1】:

当成功等于 1 时,您在 doInBackground 方法上调用 finish()。这就是它返回到上一个活动的原因。

【讨论】:

【参考方案2】:

见this链接

onPostExecute(Result),在后台计算完成后在 UI 线程上调用。后台计算的结果作为参数传递给这一步。

onPostExecute():-

在 UI 线程上进行操作的安全位置,因此您必须移动列表 初始化为onPostExecute()

carAdapter = new CarAdapter( CaronasBuscadasListActivity.this, mCaronaslist );
listview.serAdapter(carAdapter):

【讨论】:

【参考方案3】:

将以下代码从 updateJsondata 方法移动到 onPostexecute。

carAdapter = new CarAdapter( CaronasBuscadasListActivity.this, mCaronaslist );
listview.serAdapter(carAdapter):

【讨论】:

以上是关于我应该在哪里设置我的代码的 listView?的主要内容,如果未能解决你的问题,请参考以下文章

我应该在哪里设置 CORS 设置,这样我的画布才不会被污染?

搜索ListView不起作用 - 为什么?

在 Android 中实现自定义 ListView

使用 AWS Elastic Beanstalk 我应该在哪里存储我的应用程序代码?

为啥我的 ListView 项目重叠而不是滚动?

我应该在哪里编写代码以便 Composer 可以自动加载我的 PHP 类?