Android Spinner适配器无法正常工作

时间:2016-09-29 04:59:27

标签: android android-spinner

在Android中,我想从url创建微调器和解析数据并将其注入我的微调器中,For Info:我在Home Activity中的所有活动和选项卡中都有菜单,所以我为常用菜单创建基类活动请如果你我的代码有增强功能请通知我主要问题:Spinner不显示我的数据并给我设置适配器的异常错误

此处基本活动:

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public class BaseActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    protected LinearLayout fulllayout;
    protected FrameLayout actContent;

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        //For make Menu RTL
        getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

        fulllayout = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_base, null);    
        actContent = (FrameLayout) fulllayout.findViewById(R.id.act_content);    
        getLayoutInflater().inflate(layoutResID, actContent, true);

        super.setContentView(fulllayout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        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();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.END)) {
            drawer.closeDrawer(GravityCompat.END);
        } else {
            super.onBackPressed();
        }
    }    

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.END);
        return true;
    }
}

此处主页活动:

package com.arabnewtech.a22.zoodrealstate;

import android.app.ProgressDialog;
import android.net.Uri;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.arabnewtech.a22.zoodrealstate.Adapters.CityAdapter;
import com.arabnewtech.a22.zoodrealstate.Beans.CityBeans;
import com.arabnewtech.a22.zoodrealstate.customviews.WrapContentViewPager;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;    
import cz.msebera.android.httpclient.Header;

public class Home extends BaseActivity {

    /**
     * The {@link PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link FragmentStatePagerAdapter}.
     */    

    private ProgressDialog dialog;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private TextView tap1, tap2;
    private String cityUrl = "http://arabnewtech.org/zoodre/public/api/locations/city/3";
    private Spinner citySpinner;
    public  ArrayList<CityBeans> cityBeansList = new ArrayList<CityBeans>();
    TextView output = null;
    CityAdapter adapter;
    Home activity = null;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private WrapContentViewPager mViewPager;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client2;

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

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (WrapContentViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // Create Tabs Handelation
        tabsHandel();

        // Initialize Views
        initViews();

        // City Spinner
        setListData();    

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public void initViews() {
        activity = this;
        citySpinner = (Spinner) findViewById(R.id.cityID);
        output = (TextView) findViewById(R.id.output);   
    }
     public void setListData() {

    // Now I have taken static values by loop.
    // For further inhancement we can take data by webservice / json / xml;

    for (int i = 0; i < 11; i++) {

        final CityBeans sched = new CityBeans();

        /******* Firstly take data in model object ******/
        sched.setId("id " + i);
        sched.setName("Name" + i );

        /******** Take Model Object in ArrayList **********/
        cityBeansList.add(sched);
    }

          /******** Take Model Object in ArrayList **********/
        adapter = new CityAdapter(activity, R.layout.spinner_rows, cityBeansList);
        // Set adapter to spinner
        citySpinner.setAdapter(adapter);
        // Listener called when spinner item selected
        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                // Get selected row data to show on screen
                String Company = ((TextView) v.findViewById(R.id.company)).getText().toString();
                String CompanyUrl = ((TextView) v.findViewById(R.id.sub)).getText().toString();

                String OutputMsg = "Selected Company : \n\n" + Company + "\n" + CompanyUrl;
                output.setText(OutputMsg);

                Toast.makeText(
                        getApplicationContext(), OutputMsg, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });
}


    public void tabsHandel() {
        tap1 = (TextView) findViewById(R.id.tap1);
        tap2 = (TextView) findViewById(R.id.tap2);

        tap1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(0);
            }
        });

        tap2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(1);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Home Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.arabnewtech.a22.zoodrealstate/http/host/path")
        );
        AppIndex.AppIndexApi.start(client2, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Home Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.arabnewtech.a22.zoodrealstate/http/host/path")
        );
        AppIndex.AppIndexApi.end(client2, viewAction);
        client2.disconnect();
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_home, container, false);
            //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            // textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Case 0";
                case 1:
                    return "Case 1";
            }
            return null;
        }
    }
}

这里的城市豆:

package com.arabnewtech.a22.zoodrealstate.Beans;

import java.io.Serializable;

/**
 * Created by abozaid on 27/09/16.
 */
public class CityBeans implements Serializable {

    private String id;
    private String name;

    public String getId() {
            return id;
    }

    public void setId(String id) {
            this.id = id;
    }

    public String getName() {
            return name;
    }

    public void setName(String name) {
            this.name = name;
    }
}

这里的城市适配器:

package com.arabnewtech.a22.zoodrealstate.Adapters;

/**
 * Created by abozaid on 28/09/16.
 */
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.arabnewtech.a22.zoodrealstate.Beans.CityBeans;
import com.arabnewtech.a22.zoodrealstate.Home;
import com.arabnewtech.a22.zoodrealstate.R;

public class CityAdapter extends ArrayAdapter<String> {

    private Activity activity;
    private ArrayList data;
    CityBeans tempValues=null;
    LayoutInflater inflater;

    /*************  CustomAdapter Constructor *****************/
    public CityAdapter(
            Home activitySpinner,
            int textViewResourceId,
            ArrayList objects
    )
    {
        super(activitySpinner, textViewResourceId, objects);

        /********** Take passed values **********/
        activity = activitySpinner;
        data     = objects;

        /***********  Layout inflator to call external xml layout () **********************/
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

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

    // This funtion called for each row ( Called data.size() times )
    public View getCustomView(int position, View convertView, ViewGroup parent) {
        Log.i("Iammmmmmmmmmmmmmmmmm","Herrrrrrrrrrrrrrr");
        /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
        View row = inflater.inflate(R.layout.spinner_rows, parent, false);

        /***** Get each Model object from Arraylist ********/
        tempValues = null;
        tempValues = (CityBeans) data.get(position);

        TextView label        = (TextView)row.findViewById(R.id.company);
        TextView sub          = (TextView)row.findViewById(R.id.sub);

        if(position==0){
            // Default selected Spinner item
            label.setText("Please select Name");
            sub.setText("");
        }
        else
        {
            // Set values for spinner each row
            label.setText(tempValues.getId());
            sub.setText(tempValues.getName());

        }

        return row;
    }
}

这里是Fragment_home.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.arabnewtech.a22.zoodrealstate.Home$PlaceholderFragment">

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

        <Spinner
            android:id="@+id/cityID"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"></Spinner>

        <Spinner
            android:id="@+id/zoneID"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:layout_height="wrap_content"></Spinner>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/spinner2"
        android:layout_below="@id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Spinner
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"></Spinner>

        <Spinner
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:layout_height="wrap_content"></Spinner>
    </LinearLayout>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/ColorYellow"
        android:layout_below="@+id/spinner2"
        android:text="بحث"/>    

    <TextView
        android:paddingTop="20dip"
        android:paddingLeft="20dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/output" />

</RelativeLayout>

这里Spinner_Row:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="3dip"
    >
    <TextView
        android:padding="3dip"
        android:layout_marginTop="2dip"
        android:textColor="@color/colorPrimary"
        android:textStyle="bold"
        android:id="@+id/company"
        android:layout_marginLeft="5dip"
        android:text="sfsdf"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:padding="2dip"
        android:textColor="@color/ColorYellow"
        android:layout_marginLeft="5dip"
        android:id="@+id/sub"
        android:text="sfsf"
        android:layout_below="@+id/company"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

Log Cat Out put:

  FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arabnewtech.a22.zoodrealstate/com.arabnewtech.a22.zoodrealstate.Home}: java.lang.NullPointerException                                                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
                                                                                     at android.app.ActivityThread.access$700(ActivityThread.java:159)
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                     at android.os.Looper.loop(Looper.java:176)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5419)
                                                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                     at java.lang.reflect.Method.invoke(Method.java:525)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
                                                                                     at dalvik.system.NativeStart.main(Native Method)
                                                                                  Caused by: java.lang.NullPointerException
                                                                                     at com.arabnewtech.a22.zoodrealstate.Home.setListData(Home.java:123)
                                                                                     at com.arabnewtech.a22.zoodrealstate.Home.onCreate(Home.java:89)
                                                                                     at android.app.Activity.performCreate(Activity.java:5372)
                                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
                                                                                     at android.app.ActivityThread.access$700(ActivityThread.java:159) 
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                                                     at android.os.Looper.loop(Looper.java:176) 
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5419) 
                                                                                     at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                                     at java.lang.reflect.Method.invoke(Method.java:525) 
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 
                                                                                     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

我想我在复制你的代码后发现了这个问题。在您的代码的public View getCustomView(int position, View convertView, ViewGroup parent)方法中......

你正在膨胀

View row = inflater.inflate(R.layout.fragment_home, parent, false);

但必须是

View row = inflater.inflate(R.layout.spinner_row, parent, false);