从数据库填充Spinner时的奇怪行为

时间:2015-03-01 18:22:35

标签: php android json android-spinner

我试图通过JSON从Mysql Databse填充一个微调器。问题是数据导出正常。但是,当我单击Spinner显示下拉菜单时,应用程序崩溃。

数据库的JSON输出:Output

错误:

03-01 18:12:42.966    3214-3214/com.order.app.order E/ArrayAdapter﹕ You must supply a resource ID for a TextView
03-01 18:12:42.966    3214-3214/com.order.app.order D/AndroidRuntime﹕ Shutting down VM
03-01 18:12:42.967    3214-3214/com.order.app.order E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.order.app.order, PID: 3214
    java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
            at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
            at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:415)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
            at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:379)
            at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:415)

我的适配器:

public class SpiritsListAdapter extends ArrayAdapter<SpiritList> {

    public SpiritsListAdapter(Context context, int layoutId, List<SpiritList> items) {
        super(context, layoutId, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        SpiritHolderItems holder;

        if(convertView == null){
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            convertView = vi.inflate(R.layout.spinner_item, parent, false);

            holder = new SpiritHolderItems();
            holder.spiritName = (TextView)convertView.findViewById(R.id.spirit_name);
            holder.spiritPrice = (TextView)convertView.findViewById(R.id.spirit_price);
            convertView.setTag(holder);
        }else{
            holder = (SpiritHolderItems) convertView.getTag();
        }
            SpiritList current = getItem(position);
            holder.spiritName.setText(current.getName());
            holder.spiritPrice.setText(current.getPrice() + " €");
        return convertView;
    }

    static class SpiritHolderItems {
        TextView spiritName, spiritPrice;
    }
}

我的AsyncTask:

public class JsonReadTask extends AsyncTask<String , Void, List<SpiritList>> {
        public JsonReadTask() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Gins.this, ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setIndeterminate(true);
            pDialog.setMessage(getString(R.string.get_stocks));
            pDialog.setCancelable(false);
            pDialog.setInverseBackgroundForced(true);
            pDialog.show();
        }

        @Override
        protected List<SpiritList> doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
                customList = new ArrayList<>();

                JSONObject jsonResponse = new JSONObject(jsonResult);
                JSONArray jsonMainNode = jsonResponse.optJSONArray("gins");
                for (int i = 0; i < jsonMainNode.length(); i++) {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    String name = jsonChildNode.optString("name");
                    String price = jsonChildNode.optString("price");
                    customList.add(new SpiritList(name, price));
                }
                return customList;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
            return answer;
        }

        @Override
        protected void onPostExecute(List<SpiritList> customList) {
            if(customList == null){
                Log.d("ERORR", "No result to show.");
                return;
            }
            ListDrawer(customList);
            pDialog.dismiss();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        task.execute(new String[]{url});
    }

    public void ListDrawer(List<SpiritList> customList) {
        adapterGins = new SpiritsListAdapter(getApplicationContext(), R.layout.spinner_item, customList);
        adapterGins.notifyDataSetChanged();
        spDrinks.setAdapter(adapterGins);
        Log.d("Spinner Count", "The Spinner count is " + spDrinks.getCount());
    }

我的布局如下:

enter image description here

任何想法为什么会发生这种情况?我正在膨胀自定义布局,但它将其视为ArrayAdapter<String>

2 个答案:

答案 0 :(得分:0)

您正在使用this page上的第五个构造函数列表,这需要您的第二个参数

  

包含在实例化视图时使用的TextView的布局文件的资源ID。

你没有收录你的xml,R.layout.spinner_item中有TextView吗?

您的堆栈跟踪中包含ArrayAdapter,因为您SpiritsListAdapter扩展了ArrayAdapter,因此每次调用super()或其中一个ArrayAdapter的方法时,如果没有覆盖,则使用ArrayAdapter类中的代码。

编辑:您是否尝试过使用此构造函数:ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)(它是链接到上面的页面上的第六个),您在其中为其提供要填充的TextView的ID?布局中有两个TextView可能会导致问题(如评论中所述)。

答案 1 :(得分:0)

你可以使用BaseAdapter做同样的事情:

public class SpiritsListAdapter extends BaseAdapter

像这样修改你的构造函数:

    private List<SpiritList> objects;
    private Context context;

    public SpiritsListAdapter(Context context ,List<SpiritList> objects) {
        this.context = context;
        this.objects = objects;
    }

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

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

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

并添加未实现的方法,并保持getView方法不变。

希望它有所帮助!!!