简体   繁体   English

为什么开始新活动时我的android应用程序崩溃?

[英]Why does my android application crash when starting a new activity?

My app keeps crashing as I try to start a new activity (uploadLocation.class). 尝试启动新活动(uploadLocation.class)时,我的应用程序不断崩溃。 No errors are highlighted and I can't debug within the uploadLocation class. 没有突出显示错误,并且我无法在uploadLocation类中进行调试。

I have added permissions to my Manifest 我已向清单添加权限

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

MainActivity 主要活动

As this section of code from the MainActivity is executed the application crashes. 当执行MainActivity的这段代码时,应用程序崩溃了。

public void uploadMyLocation (View view){
    startActivity(new Intent(this, uploadLocation.class));
}

Other than the this class works as it should (complete MainActivity.java below) 除了该类以外,其他类都应该工作(下面完整的MainActivity.java)

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

Button uploadButton;
TextView latitudeView, longitudeView, networkView;
Location lastKnownLocation;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
String latString1, lonString1;

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

    uploadButton = (Button) findViewById(R.id.uploadButton);
    networkView = (TextView) findViewById(R.id.networkView);

    latitudeView = (TextView)findViewById(R.id.latitudeView);
    longitudeView = (TextView)findViewById(R.id.longitudeView);

    buildGoogleApiClient();

    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()){
        networkView.setVisibility(View.INVISIBLE);
    } else {
        uploadButton.setEnabled(false);
    }


}

public void uploadMyLocation (View view){
    startActivity(new Intent(this, uploadLocation.class));
}

@Override
public void onConnected(Bundle bundle) {
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(100); // location updated every second

    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    if(lastKnownLocation != null){
        latString1 = String.valueOf(lastKnownLocation.getLatitude());
        lonString1 = String.valueOf(lastKnownLocation.getLongitude());
    }
    updateUI();
}

@Override
public void onLocationChanged(Location location) {
    latString1 = String.valueOf(location.getLatitude());
    lonString1 = String.valueOf(location.getLongitude());
    updateUI();
}



@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    buildGoogleApiClient();
}

synchronized void buildGoogleApiClient(){
    googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}

@Override
protected void onStart(){
    super.onStart();
    googleApiClient.connect();
}

@Override
protected void onDestroy(){
    super.onDestroy();
    googleApiClient.disconnect();
}

void updateUI(){
    latitudeView.setText(latString1);
    longitudeView.setText(lonString1);
}
}

uploadLocation uploadLocation

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

public class uploadLocation extends AppCompatActivity {

TextView myLatitudeView, myLongitudeView, latitudeView, longitudeView;
String latString, lonString;

public void uploadInfo(View view){
    latString = latitudeView.getText().toString();
    lonString = longitudeView.getText().toString();
    myLatitudeView = (TextView)findViewById(R.id.myLatitudeView);
    myLongitudeView = (TextView)findViewById(R.id.myLongitudeView);
    myLatitudeView.setText(latString);
    myLongitudeView.setText(lonString);
    BackgroundOp backgroundOp = new BackgroundOp();
    backgroundOp.execute(latString, lonString);
    finish();
}

class BackgroundOp extends AsyncTask<String, Void, String>{

    String myUrl;

    @Override
    protected void onPreExecute() {
        myUrl = "http://[web address]/[php script]";
    }

    @Override
    protected String doInBackground(String... data) {
        String latString, lonString;
        latString = data [0];
        lonString = data [1];

        try {
            URL url = new URL(myUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String myDataStream = URLEncoder.encode("Latitude", "UTF-8") + "=" + URLEncoder.encode(latString, "UTF-8") + "&" +
                    URLEncoder.encode("Longitude", "UTF-8") + "=" + URLEncoder.encode(lonString, "UTF-8");
            bufferedWriter.write(myDataStream);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            inputStream.close();
            httpURLConnection.disconnect();
            return "Upload Successful";

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    }
}
}

XML file XML文件

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Upload Location"
    android:id="@+id/uploadButton"
    android:layout_marginBottom="61dp"
    android:layout_above="@+id/networkView"
    android:layout_centerHorizontal="true"
    android:onClick="uploadInfo" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Data"
    android:id="@+id/getDataButton"
    android:onClick="uploadMyLocation"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="41dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[Latitude]"
    android:id="@+id/latitudeView"
    android:layout_centerVertical="true"
    android:layout_toStartOf="@+id/uploadButton" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[Longitude]"
    android:id="@+id/longitudeView"
    android:layout_alignTop="@+id/latitudeView"
    android:layout_toEndOf="@+id/uploadButton" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[My Latitude]"
    android:id="@+id/myLatitudeView"
    android:layout_below="@+id/getDataButton"
    android:layout_toStartOf="@+id/getDataButton" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[My Longitude]"
    android:id="@+id/myLongitudeView"
    android:layout_below="@+id/getDataButton"
    android:layout_toEndOf="@+id/getDataButton" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[Network Unavailable]"
    android:id="@+id/networkView"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="169dp" />

Compiler log: 编译器日志:

   03-24 16:11:26.893 17436-17436/? I/art: Late-enabling -Xcheck:jni
03-24 16:11:27.044 17436-17467/com.cityuni.sophie.locationapp I/GMPM: App measurement is starting up
03-24 16:11:27.058 17436-17467/com.cityuni.sophie.locationapp E/GMPM: getGoogleAppId failed with status: 10
03-24 16:11:27.059 17436-17467/com.cityuni.sophie.locationapp E/GMPM: Uploading is not possible. App measurement disabled
03-24 16:11:27.155 17436-17475/com.cityuni.sophie.locationapp D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-24 16:11:27.160 17436-17436/com.cityuni.sophie.locationapp D/Atlas: Validating map...
03-24 16:11:27.208 17436-17475/com.cityuni.sophie.locationapp I/Adreno: QUALCOMM build                   : 40d, I21dda
                                                                        Build Date                       : 08/24/15
                                                                        OpenGL ES Shader Compiler Version: E031.25
                                                                        Local Branch                     : 
                                                                        Remote Branch                    : quic/LA.4.1.1_r9
                                                                        Remote Branch                    : NONE
                                                                        Reconstruct Branch               : NOTHING
03-24 16:11:27.216 17436-17475/com.cityuni.sophie.locationapp I/OpenGLRenderer: Initialized EGL, version 1.4
03-24 16:11:27.225 17436-17475/com.cityuni.sophie.locationapp D/OpenGLRenderer: Enabling debug mode 0
03-24 16:11:27.388 17436-17436/com.cityuni.sophie.locationapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3563b026 time:407225888
03-24 16:11:45.883 17436-17436/com.cityuni.sophie.locationapp D/AndroidRuntime: Shutting down VM
03-24 16:11:45.902 17436-17436/com.cityuni.sophie.locationapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.cityuni.sophie.locationapp, PID: 17436
                                                                                java.lang.IllegalStateException: Could not find method uploadInfo(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'uploadButton'
                                                                                    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
                                                                                    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                                    at android.view.View.performClick(View.java:4861)
                                                                                    at android.view.View$PerformClick.run(View.java:19980)
                                                                                    at android.os.Handler.handleCallback(Handler.java:739)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                    at android.os.Looper.loop(Looper.java:211)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5373)
                                                                                    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:1020)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
03-24 16:12:19.041 17436-17436/com.cityuni.sophie.locationapp I/Process: Sending signal. PID: 17436 SIG: 9

To kindly inform you Every Activity needs to override onCreate() method as per doc 为了通知您,每个活动都需要根据文档覆盖onCreate()方法

This method is Called when the activity is starting. 活动开始时调用此方法。 This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI 这是大多数初始化应该去的地方:调用setContentView(int)来膨胀活动的UI,使用findViewById(int)与UI中的小部件进行编程交互

I suggest you to override necessary methods And also don't forget to call super.onCreate() inside onCreate() method. 我建议您重写必要的方法,也不要忘记在onCreate()方法中调用super.onCreate()

UPDATE : 更新:

I figured out your error, That is because of this attribute 我发现了您的错误,这是由于此属性

android:onClick="uploadInfo"

Because XML you provided is activity_main.xml . 因为您提供的XMLactivity_main.xml And you are making the method uploadInfo in another Activity. 然后在另一个Activity中创建方法uploadInfo So I suggest you either remove this attribute OR create uploadInfo method in MainActivity not inside uploadLocation Activity. 因此,我建议您要么删除此属性,要么在MainActivity而不是uploadLocation活动中创建uploadInfo方法。

To get hints you can press Alt + Enter on that attribute and create method uploadInfo as Android Studio suggests you. 要获取提示,您可以在该属性上按Alt + Enter并按照Android Studio的建议创建方法uploadInfo。

I think you have not added your new activity to the android manifest file. 我认为您尚未将新活动添加到android清单文件中。 Try adding this. 尝试添加它。

<activity android:name=".uploadLocation">
</activity>

When I've start the development on Android I've meet the same problem and i use this for fix my app crash : 当我开始在Android上进行开发时,我遇到了同样的问题,并使用它来修复我的应用崩溃:

Try extends Activity instead of extends AppCompatActivity. 请尝试扩展Activity,而不是扩展AppCompatActivity。

If don't work maybe you have an Component null, check you instanciate all component declared in your XML. 如果不起作用,也许您有一个Component null,请检查您实例化XML中声明的所有组件。

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

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