繁体   English   中英

从一个活动移动到另一个活动时,Android 应用程序崩溃

[英]Android App crashed when moving from one activity to another

现在我有两个活动,activity_bustracking 和 activity_main

当主活动中的按钮被按下时,它应该移动到巴士跟踪活动; 但是,现在当我单击按钮时,应用程序崩溃并显示错误:

05-28 16:34:32.680  26130-26130/com.example.robertloggia.test1 D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-28 16:34:32.770  26130-26130/com.example.robertloggia.test1 D/AndroidRuntime﹕ Shutting down VM
05-28 16:34:32.770  26130-26130/com.example.robertloggia.test1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.robertloggia.test1, PID: 26130
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
            at android.content.ComponentName.<init>(ComponentName.java:77)
            at android.content.Intent.<init>(Intent.java:4562)
            at com.example.robertloggia.test1.MainActivity$1.onClick(MainActivity.java:67)
            at android.view.View.performClick(View.java:5162)
            at android.view.View$PerformClick.run(View.java:20873)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5835)
            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:1388)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)

我的 MainActivity.class 看起来像:

package com.example.robertloggia.test1;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
//import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

public class MainActivity extends Activity implements LocationListener{

    //GPS Specific variables
    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Context context;
    TextView txtLat;
    String lat;
    String provider;
    protected String latitude,longitude;
    boolean gps_enabled, network_enabled;



    Spinner routeChoice;
    Button btnSubmit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        routeChoice = (Spinner) findViewById(R.id.route_choices);
        btnSubmit = (Button) findViewById(R.id.btn_submit);

        txtLat = (TextView) findViewById(R.id.textView1);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //get location and make sure it is enabled
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Toast.makeText(MainActivity.this, "Please enable GPS", Toast.LENGTH_LONG).show();
        }
        addListenerOnButton();
    }


    public void addListenerOnButton() {

        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

//                    Toast.makeText(MainActivity.this,
//                            "OnClickListener : " +
//                                    "\nSpinner 1 : " + String.valueOf(routeChoice.getSelectedItem()),
//                            Toast.LENGTH_SHORT).show();

                     Intent intent = new Intent(context, BusTrackingActivity.class);
                     startActivity(intent);

            }

        });
    }



    /*
    * METHODS FOR GETTING LOCATION
    */
    @Override
    public void onLocationChanged(Location location) {
        txtLat = (TextView) findViewById(R.id.textView1);
        txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d("Latitude", "disable");
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d("Latitude", "enable");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d("Latitude", "status");
    }


}

我的 BusTrackingActivity.class 看起来像:

package com.example.robertloggia.test1;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

/**
 * Created by RobertLoggia on 5/28/15.
 */
public class BusTrackingActivity extends Activity {

    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bustracking);
    }    
}

我的activity_main.xml:

<ImageView
    android:layout_width="330dp"
    android:layout_height="200.5dp"
    android:layout_marginTop="110dp"
    android:id="@+id/imageView"
    android:src="@drawable/ripta_logo"
    android:layout_gravity="center_horizontal"
    android:contentDescription="@string/logo" />

<Spinner
    android:layout_width="290dp"
    android:layout_height="50dp"
    android:id="@+id/route_choices"
    android:entries="@array/route_array"
    android:prompt="@string/route_prompt"
    android:layout_gravity="center_vertical"
    android:layout_below="@+id/imageView" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/submit_text"
    android:id="@+id/btn_submit"
    android:layout_gravity="center_vertical"
    android:layout_alignBottom="@+id/route_choices"
    android:layout_toRightOf="@id/route_choices"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Please make sure GPS is enabled"
    android:id="@+id/textView1"
    android:layout_below="@+id/route_choices"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

activity_bustracking.xml:

<?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">

</LinearLayout>

我的 android 清单看起来像:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.robertloggia.test1" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:label="@string/app_name"
            android:name=".BusTrackingActivity" >
        </activity>


    </application>

</manifest>

问题是你从来没有为this分配context

但是,没有理由在 Activity 中保存 Context,只需使用MainActivity.this而不是context

            @Override
            public void onClick(View v) {

//                    Toast.makeText(MainActivity.this,
//                            "OnClickListener : " +
//                                    "\nSpinner 1 : " + String.valueOf(routeChoice.getSelectedItem()),
//                            Toast.LENGTH_SHORT).show();

                     Intent intent = new Intent(MainActivity.this, BusTrackingActivity.class);
                     startActivity(intent);

            }

当您在此行中开始新意图时:

Intent intent = new Intent(context, BusTrackingActivity.class);

上下文对象尚未启动。 你之前声明过:

protected Context context;

在您的 onCreate() 方法中,使用以下代码:

context = this;

MainActivity 中的上下文为空。要么初始化它,要么使用 MainActivity.this 代替上下文。

在 MainActivity 中添加第 67 行的代码行,因为这是有错误的行。

但是没有这个,我猜按钮监听器出了问题。

话虽如此,请尝试删除所有这些:

 public void addListenerOnButton() {

    btnSubmit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                 Intent intent = new Intent(context, BusTrackingActivity.class);
                 startActivity(intent);

        }

    });
}

侦听器最好放在它们使用的方法中,或者在这种情况下放在创建中。 这可以通过放置以下代码行来完成:

    btnSubmit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                 Intent intent = new Intent(context, BusTrackingActivity.class);
                 startActivity(intent);

        }

    });

真的,如果这不起作用,我只需要喜欢错误的代码。 如果您单击 logcat 中的第一个蓝色内容(其余部分为灰色),我可以提供更多帮助。

这可能是因为在第一个活动中使用卡片视图或您的应用程序在运行时崩溃的那个活动。

使用此代码在依赖项中实现卡片视图

implementation 'androidx.cardview:cardview:1.0.0'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM