java - Android 应用程序在启动新 Intent 时崩溃

标签 java android android-studio button android-button

我正在编写一个程序,单击此按钮后将启动另一个程序。

但是,当我点击相应的按钮时,程序强制关闭。

这是代码。

package com.example.pc.multi_functionapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = (Button)findViewById(R.id.button_1);
        Button button2 = (Button)findViewById(R.id.button_2);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent int1 = new Intent(MainActivity.this, Accelerometer.class);
                startActivity(int1);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent int2 = new Intent(MainActivity.this, Locator.class);
                startActivity(int2);
            }
        });
    }
}

这是 XML 代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:layout_gravity="center_horizontal"

    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:id="@+id/button_1"
        android:text="Android Accelerometer"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:id="@+id/button_2"
        android:text="Android Current Location"
        />
    </LinearLayout>

这是 Android list 代码

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

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</man

对于程序本身,如果我一一运行它,加速计和定位器可以正常工作。

我是故意创建这个程序的,这两个程序可以在一个应用程序中运行,无需在不同的应用程序中打开它。

我期望单击第一个按钮后,将启动加速度计程序,单击第二个按钮时,将启动定位器程序。

发生的事情是,当我单击它时,程序只是强制关闭。

请帮助我,以便该按钮在单击时正常工作。

编辑: 加速度计代码

package com.example.pc.multi_functionapp;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class Accelerometer extends AppCompatActivity implements SensorEventListener {
    private static final String TAG = "MainActivity";
    private SensorManager sensorManager;
    Sensor accelerometer;

    TextView xValue, yValue, zValue;

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

        xValue = (TextView) findViewById(R.id.xValue);
        yValue = (TextView) findViewById(R.id.yValue);
        zValue = (TextView) findViewById(R.id.zValue);
        Log.d(TAG, "onCreate: initializing Sensor Services");
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(Accelerometer.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        Log.d(TAG, "onCreate: Registered accelerometer listener");
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Log.d(TAG, "onSensorChanged: X: " + sensorEvent.values[0] + "Y: " + sensorEvent.values[1] + "Z: " + sensorEvent.values[2]);

        xValue.setText("xValue: " + sensorEvent.values[0]);
        yValue.setText("yValue: " + sensorEvent.values[1]);
        zValue.setText("xValue: " + sensorEvent.values[2]);
    }
}

定位器代码

package com.example.pc.multi_functionapp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class Locator extends AppCompatActivity {
    TextView textView1, textView2, textView3, textView4, textView5;
    FusedLocationProviderClient fusedLocationProviderClient;
    Button btLocation;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btLocation = findViewById(R.id.bt_location);
        textView1 = findViewById(R.id.text_view1);
        textView2 = findViewById(R.id.text_view2);
        textView3 = findViewById(R.id.text_view3);
        textView4 = findViewById(R.id.text_view4);
        textView5 = findViewById(R.id.text_view5);

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        btLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(Locator.this
                        , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                    getLocation();
                }
                else {
                    ActivityCompat.requestPermissions(Locator.this
                            , new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
                }
            }
        });
    }
    private void getLocation() {
        fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
                if (location != null){
                    try {
                        Geocoder geocoder = new Geocoder(Locator.this, Locale.getDefault());
                        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1 );
                        textView1.setText(Html.fromHtml("<font color='#6200EE'><B>Latitude :</b><br></font>" + addresses.get(0).getLatitude()));
                        textView2.setText(Html.fromHtml("<font color='#6200EE'><B>Longitude :</b><br></font>" + addresses.get(0).getLongitude()));
                        textView3.setText(Html.fromHtml("<font color='#6200EE'><B>Country Name :</b><br></font>" + addresses.get(0).getCountryName()));
                        textView4.setText(Html.fromHtml("<font color='#6200EE'><B>Locality :</b><br></font>" + addresses.get(0).getLocality()));
                        textView5.setText(Html.fromHtml("<font color='#6200EE'><B>Address :</b><br></font>" + addresses.get(0).getAddressLine(0)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

Before CLicked

After Clicked

最佳答案

哦,你的错误很简单。

我认为您已经复制了 Activity ,并且忘记了更改所有 Activity 的 setContentView() 中的布局。它们都是R.layout.activity_main,因此应用程序正在启动activity_main.xml,但 View 从其真实资源中获取findViewById()

关于java - Android 应用程序在启动新 Intent 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61421699/

相关文章:

java - 无法开始 Activity 。由 : android. view.InflateException 引起:

java - 使用 .clear() 后 ArrayList 未更新

安卓工作室 : 407 Proxy Authentication Required

java - 创建 Dom4J SaxReader 对象池有什么值(value)吗?

java - ImageIcon 的 getResources() - java

java - 我的 for 循环似乎没有在我的绘制方法中运行

android - 应用程序图标周围有白色圆圈,适用于 phonegap/cordova 上的 android

token "int"上的 Android R.java 语法错误,此 token 后应为 VariableDeclaratorId

android-studio - 如何将 List<String> 保存到 Kotlin 中的 SharedPreferences?

android-studio - AndroidStudio 3.1.2 突然将导入显示为未解析