java - 在 ListView 中不显示任何项目

标签 java android listview adapter

我使用 ListView 显示数据库中的自行车列表。我还使用过适配器 AdapterBike。现在,以下代码在 logcat 中完美运行。执行时没有出现错误。但它在 ListView 中不显示任何项目。

BikeSelection.java的代码文件

package com.example.mjla;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class BikeSelection extends Activity {

  ListView lv;
  ProgressDialog pDialog;
  JSONParser jsonParser = new JSONParser();
  private static final String LOGIN_URL = "http://192.168.231.2/bikeSelection.php";
  private static final String TAG_SUCCESS = "success";
  private static final String TAG_MESSAGE = "message";
  Map<String,Object> abc = new HashMap<String,Object>();

  int[] imagesBike = {};
  String[] namesBike = {};
  String[] brandsBike = {};
  String[] typesBike = {};
  String[] avgsBike = {};
  String[] ratingsBike = {};
  String[] idBike = {};
  String[] descriptionBike = {};
  String[] availableCity = {};
  String[] availabilityBike = {};
  String[] pricekmBike = {};
  String[] pricedayBike = {};

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bike_selection);

    try{
    lv = (ListView) findViewById(R.id.listViewId);

    new FetchingBikeData().execute();

    if(abc.get("size") != null)
    {
      int size = (Integer) abc.get("size");
      imagesBike = new int[size];
      namesBike = new String[size];
      brandsBike = new String[size];
      typesBike = new String[size];
      avgsBike = new String[size];
      ratingsBike = new String[size];
      idBike = new String[size];
      descriptionBike = new String[size];
      availableCity = new String[size];
      availabilityBike = new String[size];
      pricekmBike = new String[size];
      pricedayBike = new String[size];


      if(abc.get("imagesBike")!=null && abc.get("namesBike")!=null && abc.get("brandsBike")!=null && abc.get("typesBike")!=null && abc.get("avgsBike")!=null && abc.get("ratingsBike")!=null && abc.get("idBike")!=null && abc.get("descriptionBike")!=null && abc.get("availableCity")!=null && abc.get("availabilityBike")!=null && abc.get("pricekmBike")!=null && abc.get("pricedayBike")!=null) {
        this.imagesBike = (int[]) abc.get("imagesBike");
        this.namesBike =  (String[]) abc.get("namesBike");
        this.brandsBike = (String[]) abc.get("brandsBike");
        this.typesBike =  (String[]) abc.get("typesBike");
        this.avgsBike = (String[]) abc.get("avgsBike");
        this.ratingsBike =  (String[]) abc.get("ratingsBike");
        this.idBike =  (String[]) abc.get("idBike");
        this.descriptionBike = (String[]) abc.get("descriptionBike");
        this.availableCity =  (String[]) abc.get("availableCity");
        this.availabilityBike = (String[]) abc.get("availabilityBike");
        this.pricekmBike =  (String[]) abc.get("pricekmBike");
        this.pricedayBike =  (String[]) abc.get("pricedayBike");    
      }
    }

    Log.d("final", namesBike[1]);
    //ADAPTER
    AdapterBike adapter = new AdapterBike(this, imagesBike, namesBike, brandsBike, typesBike, avgsBike, ratingsBike, idBike, descriptionBike, availableCity, availabilityBike, pricekmBike, pricedayBike);
    lv.setAdapter(adapter);
    Log.d("final", namesBike[1]);
    }
    catch(Exception e)
    {
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
      Log.d("exception",errors.toString());
    }
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          // TODO Auto-generated method stub
          Toast.makeText(getApplicationContext(), namesBike[position], Toast.LENGTH_SHORT).show();
        }
    });
  }

  class FetchingBikeData extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      pDialog = new ProgressDialog(BikeSelection.this);
      pDialog.setMessage("fetching bike data");
      pDialog.setIndeterminate(false);
      pDialog.setCancelable(true);
      pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
      int success;
      String query = "select * from tblbike";

      try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("query", query));

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

        JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

        // checking  log for json response
        Log.d("query Executed", json.toString());

        JSONArray jsonArray = json.getJSONArray("bikes");


        int size = jsonArray.length();
        imagesBike = new int[size];
        namesBike = new String[size];
        brandsBike = new String[size];
        typesBike = new String[size];
        avgsBike = new String[size];
        ratingsBike = new String[size];
        idBike = new String[size];
        descriptionBike = new String[size];
        availableCity = new String[size];
        availabilityBike = new String[size];
        pricekmBike = new String[size];
        pricedayBike = new String[size];

        for(int i = 0; i<jsonArray.length(); i++){
          JSONObject jsonObject = jsonArray.getJSONObject(i);

          namesBike[i] = jsonObject.getString("bike_name");
          imagesBike[i] = getResources().getIdentifier(namesBike[i], "drawable", getPackageName());
          brandsBike[i] = jsonObject.getString("bike_brand");
          typesBike[i] = jsonObject.getString("bike_type");
          avgsBike[i] = jsonObject.getString("bike_avg");
          ratingsBike[i] = jsonObject.getString("rating");
          idBike[i] = jsonObject.getString("bike_id");
          descriptionBike[i] = jsonObject.getString("description");
          availableCity[i] = jsonObject.getString("available_city");
          availabilityBike[i] = jsonObject.getString("availability");
          pricekmBike[i] = jsonObject.getString("pricekm");
          pricedayBike[i] = jsonObject.getString("priceday");


          Log.d("Bike Name Fteched", namesBike[i]);
          Log.d("Bike Image",""+imagesBike[i]) ;


        }

        abc.put("size", size);
        abc.put("imagesBike", imagesBike);
        abc.put("namesBike", namesBike);
        abc.put("brandsBike", brandsBike);
        abc.put("typesBike", typesBike);
        abc.put("avgsBike", avgsBike);
        abc.put("ratingsBike", ratingsBike);
        abc.put("idBike", idBike);
        abc.put("descriptionBike", descriptionBike);
        abc.put("availableCity", availableCity);
        abc.put("availabilityBike", availabilityBike);
        abc.put("pricekmBike", pricekmBike);
        abc.put("pricedayBike", pricedayBike);

        // success tag for json
        success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
          Log.d("Successfully Data fetched!", json.toString());

          return json.getString(TAG_MESSAGE);
        }else{
          return json.getString(TAG_MESSAGE);
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }

      return null;
    }

    protected void onPostExecute(String message) {
      pDialog.dismiss();
      if (message != null){
        Toast.makeText(BikeSelection.this, message, Toast.LENGTH_LONG).show();
      }
    }
  }

}

和我的适配器文件:AdapterBike.java

package com.example.mjla;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AdapterBike extends ArrayAdapter<String> {

    int[] ImagesBike = {};
    String[] namesBike = {};
    String[] brandsBike = {};
    String[] typesBike = {};
    String[] avgsBike = {};
    String[] ratingsBike = {};
    String[] idBike = {};
    String[] descriptionBike = {};
    String[] availableCity = {};
    String[] availabilityBike = {};
    String[] pricekmBike = {};
    String[] pricedayBike = {};
    Context c;
    LayoutInflater inflater;

    public AdapterBike(Context context, int[] imgs, String[] names, String[] brands, String[] types, String[] avgs, String[] ratings, String[] idBike, String[] descriptionBike, String[] availableCity, String[] availabilityBike, String[] pricekmBike, String[] pricedayBike) {
        super(context, R.layout.model,names);
        //TODO Auto-generated method stub
        this.c = context;
        this.ImagesBike = imgs;
        this.namesBike = names;
        this.brandsBike = brands;
        this.typesBike = types;
        this.avgsBike = avgs;
        this.ratingsBike = ratings;
        this.idBike = idBike;
        this.descriptionBike = descriptionBike;
        this.availableCity = availableCity;
        this.availabilityBike = availabilityBike;
        this.pricekmBike = pricekmBike;
        this.pricedayBike = pricedayBike;

    }

    //INNER CLASS SHALL HOLD OUR VIEWS FOR EACH ROW
    public class ViewHolder
    {
        ImageView imgBike;
        TextView nameBike;
        TextView brandBike;
        TextView typeBike;
        TextView avgBike;
        TextView ratingBike;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //TODO Auto-generated method stub

        if(convertView==null)
        {
            inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.model, null);
        }

        //OUR VIEWHOLDER OBJECT
        final ViewHolder holder = new ViewHolder();

        //INITIALIZE OUT VIEWS
        holder.imgBike = (ImageView)convertView.findViewById(R.id.imageBike);
        holder.nameBike = (TextView)convertView.findViewById(R.id.tvBikeName);
        holder.brandBike = (TextView)convertView.findViewById(R.id.tvBikeBrand);
        holder.typeBike = (TextView)convertView.findViewById(R.id.tvBikeType);
        holder.avgBike = (TextView)convertView.findViewById(R.id.tvBikeAvgValue);
        holder.ratingBike = (TextView)convertView.findViewById(R.id.tvBikeRatingValue);

        //ASSIGN DATA
        holder.imgBike.setImageResource(ImagesBike[position]);
        holder.nameBike.setText(namesBike[position]);
        holder.brandBike.setText(brandsBike[position]);
        holder.typeBike.setText(typesBike[position]);
        holder.avgBike.setText(avgsBike[position]);
        holder.ratingBike.setText(ratingsBike[position]);

        return convertView;
    }


}

最佳答案

new FetchingBikeData().execute(); 创建新线程并启动它。 因此,该行下面的所有代码都会在获取数据之前执行。您需要将所有这些代码移到一个方法中,并从 FetchingBikeData.onPostExecute()

调用该方法

这是您修改后的代码

package com.example.mjla;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class BikeSelection extends Activity {

    ListView lv;
    ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = "http://192.168.231.2/bikeSelection.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    Map<String,Object> abc = new HashMap<String,Object>();

    int[] imagesBike = {};
    String[] namesBike = {};
    String[] brandsBike = {};
    String[] typesBike = {};
    String[] avgsBike = {};
    String[] ratingsBike = {};
    String[] idBike = {};
    String[] descriptionBike = {};
    String[] availableCity = {};
    String[] availabilityBike = {};
    String[] pricekmBike = {};
    String[] pricedayBike = {};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bike_selection);

        try{
            lv = (ListView) findViewById(R.id.listViewId);

            new FetchingBikeData().execute();

        }
        catch(Exception e)
        {
            StringWriter errors = new StringWriter();
            e.printStackTrace(new PrintWriter(errors));
            Log.d("exception",errors.toString());
        }
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), namesBike[position], Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateList() {
        if(abc.get("size") != null)
        {
            int size = (Integer) abc.get("size");
            imagesBike = new int[size];
            namesBike = new String[size];
            brandsBike = new String[size];
            typesBike = new String[size];
            avgsBike = new String[size];
            ratingsBike = new String[size];
            idBike = new String[size];
            descriptionBike = new String[size];
            availableCity = new String[size];
            availabilityBike = new String[size];
            pricekmBike = new String[size];
            pricedayBike = new String[size];


            if(abc.get("imagesBike")!=null && abc.get("namesBike")!=null && abc.get("brandsBike")!=null && abc.get("typesBike")!=null && abc.get("avgsBike")!=null && abc.get("ratingsBike")!=null && abc.get("idBike")!=null && abc.get("descriptionBike")!=null && abc.get("availableCity")!=null && abc.get("availabilityBike")!=null && abc.get("pricekmBike")!=null && abc.get("pricedayBike")!=null) {
                this.imagesBike = (int[]) abc.get("imagesBike");
                this.namesBike =  (String[]) abc.get("namesBike");
                this.brandsBike = (String[]) abc.get("brandsBike");
                this.typesBike =  (String[]) abc.get("typesBike");
                this.avgsBike = (String[]) abc.get("avgsBike");
                this.ratingsBike =  (String[]) abc.get("ratingsBike");
                this.idBike =  (String[]) abc.get("idBike");
                this.descriptionBike = (String[]) abc.get("descriptionBike");
                this.availableCity =  (String[]) abc.get("availableCity");
                this.availabilityBike = (String[]) abc.get("availabilityBike");
                this.pricekmBike =  (String[]) abc.get("pricekmBike");
                this.pricedayBike =  (String[]) abc.get("pricedayBike");
            }
        }

        Log.d("final", namesBike[1]);
        //ADAPTER
        AdapterBike adapter = new AdapterBike(this, imagesBike, namesBike, brandsBike, typesBike, avgsBike, ratingsBike, idBike, descriptionBike, availableCity, availabilityBike, pricekmBike, pricedayBike);
        lv.setAdapter(adapter);
        Log.d("final", namesBike[1]);
    }

    class FetchingBikeData extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(BikeSelection.this);
            pDialog.setMessage("fetching bike data");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            int success;
            String query = "select * from tblbike";

            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("query", query));

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

                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

                // checking  log for json response
                Log.d("query Executed", json.toString());

                JSONArray jsonArray = json.getJSONArray("bikes");


                int size = jsonArray.length();
                imagesBike = new int[size];
                namesBike = new String[size];
                brandsBike = new String[size];
                typesBike = new String[size];
                avgsBike = new String[size];
                ratingsBike = new String[size];
                idBike = new String[size];
                descriptionBike = new String[size];
                availableCity = new String[size];
                availabilityBike = new String[size];
                pricekmBike = new String[size];
                pricedayBike = new String[size];

                for(int i = 0; i<jsonArray.length(); i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    namesBike[i] = jsonObject.getString("bike_name");
                    imagesBike[i] = getResources().getIdentifier(namesBike[i], "drawable", getPackageName());
                    brandsBike[i] = jsonObject.getString("bike_brand");
                    typesBike[i] = jsonObject.getString("bike_type");
                    avgsBike[i] = jsonObject.getString("bike_avg");
                    ratingsBike[i] = jsonObject.getString("rating");
                    idBike[i] = jsonObject.getString("bike_id");
                    descriptionBike[i] = jsonObject.getString("description");
                    availableCity[i] = jsonObject.getString("available_city");
                    availabilityBike[i] = jsonObject.getString("availability");
                    pricekmBike[i] = jsonObject.getString("pricekm");
                    pricedayBike[i] = jsonObject.getString("priceday");


                    Log.d("Bike Name Fteched", namesBike[i]);
                    Log.d("Bike Image",""+imagesBike[i]) ;


                }

                abc.put("size", size);
                abc.put("imagesBike", imagesBike);
                abc.put("namesBike", namesBike);
                abc.put("brandsBike", brandsBike);
                abc.put("typesBike", typesBike);
                abc.put("avgsBike", avgsBike);
                abc.put("ratingsBike", ratingsBike);
                abc.put("idBike", idBike);
                abc.put("descriptionBike", descriptionBike);
                abc.put("availableCity", availableCity);
                abc.put("availabilityBike", availabilityBike);
                abc.put("pricekmBike", pricekmBike);
                abc.put("pricedayBike", pricedayBike);

                // success tag for json
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Successfully Data fetched!", json.toString());

                    return json.getString(TAG_MESSAGE);
                }else{
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String message) {
            pDialog.dismiss();
            if (message != null){
                Toast.makeText(BikeSelection.this, message, Toast.LENGTH_LONG).show();
                updateList()
            }
        }
    }

}

关于java - 在 ListView 中不显示任何项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37093330/

相关文章:

android - 从 res/raw 读取文件 .txt 并将其显示到 ListView 中

java - 当我在代码中设置事务隔离级别时,它是在代码中还是在 DBMS 中强制执行?

java - 如何在android studio中导入zebra包?

java - 用java编写多表转置密码

android - 用于在 Google PlayStore 上获取应用程序版本的官方 API

Android:默认 AppTheme 背景颜色

android - 将 imageview 对齐到 listview 的末尾,当 listview 加载数据时 android

android - 如何禁用我的 ListView 中的项目

java - 如何在mouseDragged事件下的DRAG_LAYER上添加JLabel

java - 访问没有对象的字符串类的方法