0

看似非常简单的练习,但这以某种方式使我的程序崩溃。试图检索用户在 EditText 字段中输入的字符串。当我点击提交按钮时,我崩溃了。再次感谢!

这是代码和 LogCat 信息:

public class FindEventsActivity extends Activity implements LocationListener {

    GeoPoint searchFrom;
    private static final int USE_CURRENT_COORDINATES = 0;
    private static final int ENTER_CITY = 1;
    private static final int ENTER_ZIP = 2;
    private static final int USE_MAP = 3;
    private static final int RESULT_FROM_MAP = 1;
    Context context;
    String cityState;
    Geocoder geocoder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_events);
        context = this;
        setClickListeners();
    }

private void setClickListeners() {

        RelativeLayout locationBox = (RelativeLayout) findViewById(R.id.locationBox);
        locationBox.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                final CharSequence[] methods = {"Use Current Location", "Enter City / State" , "Enter Zip Code", "Use Map"};

                AlertDialog.Builder chooser = new AlertDialog.Builder(FindEventsActivity.this);

                chooser.setTitle("Choose Your Search Location Method").setItems(methods, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int position) {
                        switch (position) {
                            case USE_CURRENT_COORDINATES:
                                searchFrom = getCurrentCoordinates();
                                break;
                            case ENTER_CITY:
                                searchFrom = getFromCityState();
                                break;

                        }
                    }

                });

                chooser.show();
            }
        });
    }

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

    private GeoPoint getCurrentCoordinates() {

        if (isGooglePlay()) {
            Location lastKnownLocation = getLastKnownLocation();
            int lat = (int) (lastKnownLocation.getLatitude() * 1E6);
            int lng = (int) (lastKnownLocation.getLongitude() * 1E6);
            return new GeoPoint(lat, lng);
        }

        return null;
    }

    public void submitButtonOnClick(View view) {

        System.err.println("inside onTouch");   

        EditText city_entry = (EditText) view.findViewById(R.id.city_entry);
        Spinner state = (Spinner) findViewById(R.id.state_spinner);

        System.err.println("here"); 

        System.err.println(city_entry.getText().toString());
        System.err.println("city string captured");
        System.err.println(state.getSelectedItem().toString());

        cityState = city_entry.getText().toString() + ", " + state.getSelectedItem().toString();
        Toast.makeText(getApplicationContext(), cityState, Toast.LENGTH_LONG).show();

    }

    private GeoPoint getFromCityState() {

        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.city_state_entry, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);

        //setContentView(R.layout.city_state_entry);

        //Button submitButton = (Button) findViewById(R.id.submitButton);
        System.err.println("About to create onClickListener");

        // create alert dialog
        AlertDialog alertDialog = builder.create();

        alertDialog.show();

        return null;
    }


    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub
    }

    private Location getLastKnownLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        /* Verify that the gps is turned on */
        if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
            buildAlertMessageNoGps();
        }

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);

        String provider = locationManager.getBestProvider(criteria, true);

        if (provider == null) {
            onProviderDisabled(null);
        }

        Location location = locationManager.getLastKnownLocation(provider);

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, 5000, this);

        if (location != null) {
          System.out.println("Provider " + provider + " has been selected.");
          onLocationChanged(location);
          return location;
        } 

        return null;
    }

    private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                       startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                   }
               });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    private boolean isGooglePlay() {
        /* This function checks to make sure that the Google Play service is installed on the user's phone */
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (status != ConnectionResult.SUCCESS) {
            ((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
            //Toast.makeText(this, "Google Play Services is not available. Check your setup.", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }


}




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/city_state_entry"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/background"
    android:padding="10dp" >

    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/city_state_title"
        android:textColor="#000000"
        android:layout_gravity="center_horizontal"
        android:paddingBottom="10dip"
        />

    <TextView
        android:id="@+id/enter_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/enter_city" />

    <EditText
        android:id="@+id/city_entry"
        android:inputType="textCapWords"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/enter_state"
        android:layout_marginTop="10dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/select_state" />

    <Spinner
        android:id="@+id/state_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/state_abbreviations" />

    <LinearLayout 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginTop="20dip"
        android:layout_gravity="center_horizontal"
        android:paddingBottom="10dp">

        <Button
            android:id="@+id/submitButton"
            style="@style/ButtonText"
            android:onClick="submitButtonOnClick"
            android:layout_gravity="center_horizontal"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@drawable/blue_button"
            android:text="@string/submit" />

    </LinearLayout>

</LinearLayout>

05-19 19:23:56.703: W/System.err(4744): 内部 onTouch 05-19 19:23:56.703: W/System.err(4744): 这里 05-19 19:23:56.703: D/ AndroidRuntime(4744): 关闭 VM 05-19 19:23:56.703: W/dalvikvm(4744): threadid=1: 线程退出未捕获异常 (group=0x4001d5a0) 05-19 19:23:56.713: E/AndroidRuntime (4744):致命异常:主要05-19 19:23:56.713:E / AndroidRuntime(4744):java.lang.IllegalStateException:无法执行活动05-19 19:23:56.713的方法:E / AndroidRuntime( 4744): 在 android.view.View$1.onClick(View.java:2191) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 android.view.View.performClick(View.java:2532) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 android.view.View$PerformClick.run(View.java:9293) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在android.os.Handler.handleCallback(处理程序。java:587) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 android.os.Handler.dispatchMessage(Handler.java:92) 05-19 19:23:56.713: E/AndroidRuntime(4744) : 在 android.os.Looper.loop(Looper.java:150) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 android.app.ActivityThread.main(ActivityThread.java:4369) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 java.lang.reflect.Method.invokeNative(Native Method) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 java.lang.reflect。 Method.invoke(Method.java:507) 05-19 19:23:56.713: E/AndroidRuntime(4744): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:846) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 dalvik 。系统。NativeStart.main(Native Method) 05-19 19:23:56.713: E/AndroidRuntime(4744): 由: java.lang.reflect.InvocationTargetException 05-19 19:23:56.713: E/AndroidRuntime(4744): at java.lang.reflect.Method.invokeNative(Native Method) 05-19 19:23:56.713: E/AndroidRuntime(4744): at java.lang.reflect.Method.invoke(Method.java:507) 05-19 19 :23:56.713: E/AndroidRuntime(4744): at android.view.View$1.onClick(View.java:2186) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 11 更多 05 -19 19:23:56.713:E/AndroidRuntime(4744):引起:java.lang.NullPointerException 05-19 19:23:56.713:E/AndroidRuntime(4744):在 com.mobilenicity.find_events.FindEventsActivity.submitButtonOnClick( FindEventsActivity.java:85) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 14 更多E/AndroidRuntime(4744): 引起: java.lang.reflect.InvocationTargetException 05-19 19:23:56.713: E/AndroidRuntime(4744): at java.lang.reflect.Method.invokeNative(Native Method) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 java.lang.reflect.Method.invoke(Method.java:507) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 android.view .View$1.onClick(View.java:2186) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 11 更多 05-19 19:23:56.713: E/AndroidRuntime(4744): Caused作者:java.lang.NullPointerException 05-19 19:23:56.713: E/AndroidRuntime(4744): at com.mobilenicity.find_events.FindEventsActivity.submitButtonOnClick(FindEventsActivity.java:85) 05-19 19:23:56.713: E /AndroidRuntime(4744): ... 14 更多E/AndroidRuntime(4744): 引起: java.lang.reflect.InvocationTargetException 05-19 19:23:56.713: E/AndroidRuntime(4744): at java.lang.reflect.Method.invokeNative(Native Method) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 java.lang.reflect.Method.invoke(Method.java:507) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 android.view .View$1.onClick(View.java:2186) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 11 更多 05-19 19:23:56.713: E/AndroidRuntime(4744): Caused作者:java.lang.NullPointerException 05-19 19:23:56.713: E/AndroidRuntime(4744): at com.mobilenicity.find_events.FindEventsActivity.submitButtonOnClick(FindEventsActivity.java:85) 05-19 19:23:56.713: E /AndroidRuntime(4744): ... 14 更多在 java.lang.reflect.Method.invokeNative(Native Method) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 java.lang.reflect.Method.invoke(Method.java:507) 05-19 19:23:56.713: E/AndroidRuntime(4744): at android.view.View$1.onClick(View.java:2186) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 还有 11 个05-19 19:23:56.713:E/AndroidRuntime(4744):引起:java.lang.NullPointerException 05-19 19:23:56.713:E/AndroidRuntime(4744):在 com.mobilenicity.find_events.FindEventsActivity.submitButtonOnClick (FindEventsActivity.java:85) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 14 更多在 java.lang.reflect.Method.invokeNative(Native Method) 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 java.lang.reflect.Method.invoke(Method.java:507) 05-19 19:23:56.713: E/AndroidRuntime(4744): at android.view.View$1.onClick(View.java:2186) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 还有 11 个05-19 19:23:56.713:E/AndroidRuntime(4744):引起:java.lang.NullPointerException 05-19 19:23:56.713:E/AndroidRuntime(4744):在 com.mobilenicity.find_events.FindEventsActivity.submitButtonOnClick (FindEventsActivity.java:85) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 14 更多onClick(View.java:2186) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 11 更多 05-19 19:23:56.713: E/AndroidRuntime(4744): 引起:java。 lang.NullPointerException 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 com.mobilenicity.find_events.FindEventsActivity.submitButtonOnClick(FindEventsActivity.java:85) 05-19 19:23:56.713: E/AndroidRuntime(4744 ): ... 14 更多onClick(View.java:2186) 05-19 19:23:56.713: E/AndroidRuntime(4744): ... 11 更多 05-19 19:23:56.713: E/AndroidRuntime(4744): 引起:java。 lang.NullPointerException 05-19 19:23:56.713: E/AndroidRuntime(4744): 在 com.mobilenicity.find_events.FindEventsActivity.submitButtonOnClick(FindEventsActivity.java:85) 05-19 19:23:56.713: E/AndroidRuntime(4744 ): ... 14 更多

4

4 回答 4

1

edittext 是对话框的一部分,因此不是活动的子项,也不是按下按钮的子项(这是 onclick 方法的 View 参数。

因此,您需要获取/保留它,例如通过将其分配给您的活动领域(快速和肮脏)。这反过来会给你一些旋转等问题,但这是另一个话题。让它成为一个领域应该能让你到达某个地方。

于 2013-05-20T14:19:00.823 回答
0

您在哪里以及如何调用该方法submitButtonOnClick?认为view没有找到。调用时将视图传递给方法submitButtonOnClick并尝试以下操作...

代替...

EditText city_entry = (EditText) findViewById(R.id.city_entry);

尝试...

EditText city_entry = (EditText) view.findViewById(R.id.city_entry); 
于 2013-05-20T01:43:16.663 回答
0

而不是使用这个

 System.err.println(city_entry.getText().toString());

试试这个方法

 System.err.println(""+city_entry.getText().toString());
于 2013-05-20T06:30:59.497 回答
0

我知道了。@mvds 提供的建议让我想到了 getFromCityState() 和 submitButtonOnClick() 之间的视图关系。这两个视图都显示了 AlertDialogs,并且它们之间似乎存在脱节。因此,当我尝试从 EditText 控件中检索文本时,出现了错误。

我通过创建一个名为 builderView 的全局视图解决了这个问题。我在 getFromCityState() 中分配了该视图。通过使该视图全局化,我就能够在 submitButtonClick() 方法中引用相同的视图,从而连接这两个函数。

(顺便说一句,我为我的 onClick 使用单独的函数的原因来自另一个问题,即我能够从内部函数引用和更改变量。)

这是这两个函数的代码。我已将旧行作为评论留下,以便人们可以看到我所做的更改。如果有更优雅的方法可以做到这一点,我会全力以赴。感谢大家的所有建议!

View builderView;
AlertDialog alert;

private void getFromCityState() {

    LayoutInflater inflater = LayoutInflater.from(this);
    //View view = inflater.inflate(R.layout.city_state_entry, null);
    builderView = inflater.inflate(R.layout.city_state_entry, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    //builder.setView(view);
    builder.setView(builderView);

    //AlertDialog alertDialog = builder.create();

    alert = builder.create();
    alert.show();

} 

public void submitButtonOnClick(View view) {

    EditText city_entry = (EditText) builderView.findViewById(R.id.city_entry);
    Spinner state = (Spinner) builderView.findViewById(R.id.state_spinner); 

    cityState = city_entry.getText().toString() + ", " + state.getSelectedItem().toString();

    System.err.println(cityState);

    alert.dismiss();

    geocoder = new Geocoder(this);
    try {
        List<Address> addresses = geocoder.getFromLocationName(cityState, 1);
        /* the point of all of this is to set this GeoPoint value */
        searchFrom = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6), (int) (addresses.get(0).getLongitude() * 1E6) );
        System.err.println("searchFrom: " + Integer.toString(searchFrom.getLatitudeE6()));
    } catch (IOException e) {
        e.printStackTrace();
    }

}
于 2013-05-20T16:25:28.453 回答