如何在android中使用自动完成文本

时间:2015-06-03 06:47:31

标签: java android

我是android新手。我创建了简单的应用程序,其中包含自动完成文本字段。我写了一些代码但不幸的是,当我运行时应用程序停止了。没有错误,我如何解决...

请任何人帮忙!

我的代码:

Mainactivity.java

package com.h2o;

import android.app.Activity;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.support.v4.app.DialogFragment;
import android.os.Bundle;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.annotation.Nullable;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends FragmentActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    CustomDrawerAdapter adapter;

    List<DrawerItem> dataList;
    EditText mEdit;

    private String[] states;
    private Spinner spinner;

    AutoCompleteTextView autoTextView;




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

        String[] city= getResources().getStringArray(R.array.city);
        autoTextView = (AutoCompleteTextView) findViewById(R.id.city_autoCompleteTextView);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,city);

        autoTextView.setThreshold(1);
        autoTextView.setAdapter(arrayAdapter);

        // Initializing
        dataList = new ArrayList<DrawerItem>();
        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
                GravityCompat.START);

        // Add Drawer Item to dataList
        dataList.add(new DrawerItem(true)); // adding a spinner to the list - 0

        dataList.add(new DrawerItem("Wallet")); // adding a header to the list - 1
        dataList.add(new DrawerItem("Balance", R.drawable.ic_balance)); // - 2


        dataList.add(new DrawerItem("Profile"));// adding a header to the list - 3
        dataList.add(new DrawerItem("Personal", R.drawable.ic_account));
        dataList.add(new DrawerItem("Work", R.drawable.ic_account));
        dataList.add(new DrawerItem("Address", R.drawable.ic_account));
        dataList.add(new DrawerItem("Vehicle", R.drawable.ic_car));
        dataList.add(new DrawerItem("Preference", R.drawable.ic_pref));


        dataList.add(new DrawerItem("Other Option")); // adding a header to the list
        dataList.add(new DrawerItem("About", R.drawable.ic_action_about));
        dataList.add(new DrawerItem("Settings", R.drawable.ic_action_settings));
        dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));

        adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
                dataList);

        mDrawerList.setAdapter(adapter);

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open,
                R.string.drawer_close) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to
                // onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to
                // onPrepareOptionsMenu()
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);




    }

//Calendar picker
    public void selectDate(View view) {
        DialogFragment newFragment = new SelectDateFragment();
        newFragment.show(getSupportFragmentManager(), "DatePicker");
    }
    public void populateSetDate(int year, int month, int day) {
        mEdit = (EditText)findViewById(R.id.dobText);
        mEdit.setText(month + "/" + day + "/" + year);
    }
    public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
    {


        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), this, yy, mm, dd);
        }

        public void onDateSet(DatePicker view, int yy, int mm, int dd) {
            populateSetDate(yy, mm + 1, dd);
        }

    }



   //Spinner

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void SelectItem(String item, int possition) {
        Fragment fragment = null;
        Bundle args = new Bundle();

        switch(item) {
            case "Balance": fragment = new BalanceFragment(); break;
            case "Personal": fragment = new PersonalFragment(); break;
            case "Work": fragment = new WorkFragment(); break;
            case "Address": fragment = new AddressFragment(); break;
            case "Vehicle": fragment = new VehicleFragment(); break;
            case "Preference": fragment = new PreferenceFragment(); break;
            case "About": fragment = new AboutFragment(); break;
            case "Settings": fragment = new SettingsFragment(); break;
            case "Help": fragment = new HelpFragment(); break;
            default: fragment = new DefaultFragment(); break;
        }

        fragment.setArguments(args);
        FragmentManager frgManager = getFragmentManager();
        frgManager.beginTransaction().replace(R.id.content_frame, fragment)
                .commit();

        mDrawerList.setItemChecked(possition, true);
        setTitle(dataList.get(possition).getItemName());
        mDrawerLayout.closeDrawer(mDrawerList);


    }




    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return false;
    }

    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            if (dataList.get(position).getTitle() == null) {
                SelectItem(dataList.get(position).getItemName(), position);
            }
        }
    }


}

log cat:

&#13;
&#13;
06-03 12:23:32.446    2843-2843/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-03 12:23:32.637    2843-2843/com.h2o D/AndroidRuntime﹕ Shutting down VM
06-03 12:23:32.638    2843-2843/com.h2o E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.h2o, PID: 2843
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.h2o/com.h2o.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setThreshold(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setThreshold(int)' on a null object reference
            at com.h2o.MainActivity.onCreate(MainActivity.java:73)
            at android.app.Activity.performCreate(Activity.java:5937)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
&#13;
&#13;
&#13;

Layout file

&#13;
&#13;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="Address Details"
            android:id="@+id/address"
            android:textColor="#ff000000"
            android:textSize="20dp"
            android:layout_marginLeft="10dp"
            android:gravity="center" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.03">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="33dp"
            android:text="Tag Address"
            android:id="@+id/residential"
            android:textColor="#ff000000"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center"
            android:gravity="center" />

        <RadioGroup
            android:id="@+id/radioGroup"
            android:layout_width="276dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center"
            android:weightSum="1">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Home"
                android:id="@+id/home"
                android:layout_gravity="center"
                android:textColor="#FF000000"
                android:checked="false"
                android:layout_weight="0.22"
                android:layout_marginLeft="10dp" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Office"
                android:id="@+id/office"
                android:textColor="#FF000000"
                android:checked="false"
                android:layout_gravity="center" />
        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.06">

        <TextView
            android:layout_width="48dp"
            android:layout_height="wrap_content"
            android:text="Line 1"
            android:id="@+id/address1"
            android:textColor="#ff000000"
            android:layout_marginLeft="10dp"
            android:gravity="center" />

        <EditText
            android:layout_width="291dp"
            android:layout_height="wrap_content"
            android:inputType="textPostalAddress"
            android:ems="10"
            android:id="@+id/addressText"
            android:layout_marginLeft="50dp"
            android:textColor="#ff000000"
            android:layout_weight="1.04" /> />

    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.06">

        <TextView
            android:layout_width="48dp"
            android:layout_height="wrap_content"
            android:text="Line 2"
            android:id="@+id/address2"
            android:textColor="#ff000000"
            android:layout_marginLeft="10dp"
            android:gravity="center" />

        <EditText
            android:layout_width="291dp"
            android:layout_height="wrap_content"
            android:inputType="textPostalAddress"
            android:ems="10"
            android:id="@+id/address2Text"
            android:layout_marginLeft="50dp"
            android:textColor="#ff000000"
            android:layout_weight="1.04" /> />

    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.06">

        <TextView
            android:layout_width="48dp"
            android:layout_height="wrap_content"
            android:text="City"
            android:id="@+id/city"
            android:textColor="#ff000000"
            android:layout_marginLeft="5dp"
            android:gravity="center"
            android:layout_gravity="center" />

               <AutoCompleteTextView
            android:layout_width="112dp"
            android:layout_height="wrap_content"
            android:id="@+id/city_autoCompleteTextView"
            android:ems="10"
            android:layout_gravity="center" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="33dp"
            android:text="Zipcode"
            android:id="@+id/zipcode"
            android:textColor="#ff000000"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center"
            android:gravity="center" />

        <EditText
            android:layout_width="291dp"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/zipcodeText"
            android:layout_marginLeft="10dp"
            android:textColor="#ff000000"
            android:layout_weight="1.04" /> />

    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:weightSum="1"
        android:layout_weight="0.09">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Country"
            android:id="@+id/country"
            android:textColor="#ff000000"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center" />

    <Spinner
        android:layout_width="75dp"
        android:layout_height="31dp"
        android:id="@+id/countrySpinner"
        android:entries="@array/country_list"
        android:layout_marginLeft="40dp"
        android:spinnerMode="dropdown"
        android:outlineProvider="bounds"
        android:layout_gravity="center" />

        <TextView
            android:layout_width="51dp"
            android:layout_height="match_parent"
            android:text="State"
            android:id="@+id/state"
            android:textColor="#ff000000"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center"
            android:gravity="center" />

        <Spinner
            android:layout_width="75dp"
            android:layout_height="31dp"
            android:id="@+id/stateSpinner"
            android:entries="@array/state_list"
            android:spinnerMode="dropdown"
            android:outlineProvider="bounds"
            android:layout_weight="0.10"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp" />


    </LinearLayout>


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.06">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="33dp"
            android:text="Landmark"
            android:id="@+id/landmark"
            android:textColor="#ff000000"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center"
            android:gravity="center" />

        <EditText
            android:layout_width="291dp"
            android:layout_height="wrap_content"
            android:inputType="textPostalAddress"
            android:ems="10"
            android:id="@+id/landmarkText"
            android:layout_marginLeft="40dp"
            android:textColor="#ff000000"
            android:layout_weight="1.04" /> />

    </LinearLayout>
</LinearLayout>
&#13;
&#13;
&#13;

感谢您提前!!

1 个答案:

答案 0 :(得分:1)

检查布局 activity_main 文件

中下方行的ID
autoTextView = (AutoCompleteTextView) findViewById(R.id.city_autoCompleteTextView);

此处autoTextView提供 null