在 Android 中将 Json 填充到 Spinner

Populate Json to Spinner in Android

我正在尝试将 JSON 填充到微调器,但失败了。并且错误始终指向 KatArtcAdapter-> getView 并且致命错误始终显示 ArrayAdapter 要求资源 ID 为 TextView。你能帮我找出我的错误吗?提前谢谢你

KatArtcAdapter.java

public class KatArtcAdapter extends ArrayAdapter<KategoriArt> {
        private Activity context;
        ArrayList<KategoriArt> data = null;

        public KatArtcAdapter(Activity context, int resource,ArrayList<KategoriArt> data) {
            super(context, resource, data);
            this.context = context;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return super.getView(position, convertView, parent);
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            if (row == null) {
                LayoutInflater inflater = context.getLayoutInflater();
                row = inflater.inflate(R.layout.spinner_item, parent, false);
            }

            KategoriArt item = data.get(position);

            if (item != null) { // Parse the data from each object and set it.
                TextView KatId = (TextView) row.findViewById(R.id.item_id);
                TextView KatName = (TextView) row.findViewById(R.id.item_value);
                if (KatId != null) {
                    KatId.setText(item.getIdKat());
                }
                if (KatName != null) {
                    KatName.setText(item.getName());
                }

            }

            return row;
        }
    }

MainActivity.Java

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
        RecyclerItemClickListener.OnItemClickListener{
    artikelAdapter mGridadapter;
    JSONParser jParser= new JSONParser();
    JSONArray names=null;
    private static final String URL_READ_KAT= "http://amobipets.azurewebsites.net/readKategoriArticle.php";
    private static final String TAG_PESAN = "message";
    private static final String TAG_HASIL = "result";
    private static final String TAG_ID_KAT = "id";
    private static final String TAG_KAT= "kategori";

    Spinner katyField;
    ArrayList<KategoriArt> katList = new ArrayList<KategoriArt>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        katyField =(Spinner) findViewById(R.id.spinner);
         new buildKatDropDown().execute();

        katyField.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                KategoriArt selectedKat=katList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
public class buildKatDropDown extends AsyncTask<String,String,String> {

        int sukses=0;

        public buildKatDropDown() {
        }

        @Override
        protected void onPreExecute() {
        }

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

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            try
            {
                JSONObject json = jParser.makeHttpRequest(URL_READ_KAT, "GET", params);
                if(json != null)
                {
                    sukses = json.getInt(TAG_PESAN);
                    if(sukses == 1)
                    {
                        nameList = new ArrayList<HashMap<String,String>>();
                        Log.d("Semua Nama: ", json.toString());
                        names = json.getJSONArray(TAG_HASIL);

                        for(int i = 0; i < names.length();i++)
                        {
                            JSONObject c = names.getJSONObject(i);
                            String id = c.getString(TAG_ID_KAT);
                            String kategori = c.getString(TAG_KAT);

                            katList.add(new KategoriArt(id,kategori));

                        }

                    }
                }
            }catch(JSONException e)
            {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            if(sukses==1)
            {
                KatArtcAdapter ktAdapter=new KatArtcAdapter(MainActivity.this,R.layout.spinner_item,katList);
                katyField.setAdapter(ktAdapter);
            }
        }
    }
}

堆栈跟踪

06-19 21:26:44.328 21749-21904/com.amobi.newlomapodfix D/url:http://amobipets.azurewebsites.net/readKategoriArticle.php? 06-19 21:26:44.375 21749-21867/com.amobi.newlomapodfix E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaaaa97d0 06-19 21:26:44.428 21749-21749/com.amobi.newlomapodfix W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value. 06-19 21:26:44.493 21749-21904/com.amobi.newlomapodfix I/info: org.apache.http.client.methods.HttpGet@b2b1a82 06-19 21:26:44.494 21749-21904/com.amobi.newlomapodfix D/Semua Nama:: {"result":[{"id":"11","kategori":"Anjing"},{"id":"21","kategori":"Kucing"},{"id":"31","kategori":"Hamster"},{"id":"41","kategori":"Reptil"}],"message":1} 06-19 21:26:44.704 21749-21749/com.amobi.newlomapodfix E/ArrayAdapter: You must supply a resource ID for a TextView 06-19 21:26:44.709 21749-21749/com.amobi.newlomapodfix D/AndroidRuntime: Shutting down VM 06-19 21:26:44.728 21749-21749/com.amobi.newlomapodfix E/AndroidRuntime: FATAL EXCEPTION: main Process: com.amobi.newlomapodfix, PID: 21749 java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:393) at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369) at com.amobi.newlomapodfix.adapter.KatArtcAdapter.getView(KatArtcAdapter.java:30) at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:194) at android.widget.Spinner.onMeasure(Spinner.java:580) at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:418) at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:18788) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664) at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90) at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1149) at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:729) at android.view.View.measure(View.java:18788) at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075) at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135) at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643) at android.view.View.measure(View.java:18788) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) at android.view.Choreographer.doCallbacks(Choreographer.java:670) at android.view.Choreographer.doFrame(Choreographer.java:606) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

编辑

Spinner_item.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="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <TextView
        android:id="@+id/item_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.43">
    </TextView>

    <TextView
        android:id="@+id/item_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:layout_weight="0.10">
    </TextView>

</LinearLayout>

this所述,super.getView属于Adapter接口。它什么都不做。

自定义 ArrayAdapter 时,您应该 return 在 getView() 方法上查看。参考这个 example.

正如你在评论中提到的,即使只有一个 TextView,它仍然在提升 您可以像这样使用具有 4 个参数的 constructortextViewResourceId

ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)

不会有太大的变化,但您的代码将看起来像这样,

public KatArtcAdapter(Activity context, int resource,int textViewResourceId, ArrayList<KategoriArt> data) {
            ....
        }

有关详细信息,请参阅 doc,如果仍然出现错误,请尝试不要用其他布局围绕您的 TextView