当我尝试启动新活动(uploadLocation.class)时,我的应用程序一直崩溃。 没有突出显示错误,我无法在uploadLocation类中进行调试。
我已为我的清单添加了权限
<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
当执行MainActivity的这部分代码时,应用程序崩溃。
public void uploadMyLocation (View view){
startActivity(new Intent(this, uploadLocation.class));
}
除了这个类之外,它应该正常工作(完成下面的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
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文件
<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" />
编译日志:
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
答案 0 :(得分:0)
请告知您每个活动都需要根据文档
覆盖This方法在活动开始时调用此方法。这是大多数初始化应该去的地方:调用
setContentView(int)
来扩展活动的UI,使用findViewById(int)
以编程方式与UI中的小部件进行交互
我建议您覆盖必要的方法,也不要忘记在super.onCreate()
方法中调用onCreate()
。
更新:
我发现了你的错误,那是因为这个属性
android:onClick="uploadInfo"
因为您提供的XML
是activity_main.xml
。而你正在另一个Activity中创建方法uploadInfo
。因此,我建议您删除此属性,或在uploadInfo
中创建MainActivity
方法而不是uploadLocation
活动内的方法。
要获得提示,您可以在该属性上按 Alt + Enter ,并按照Android Studio的建议创建方法uploadInfo。
答案 1 :(得分:0)
我认为您尚未将新活动添加到Android清单文件中。 尝试添加此内容。
<activity android:name=".uploadLocation">
</activity>
答案 2 :(得分:-1)
当我在Android上开始开发时,我遇到了同样的问题,我使用它来修复我的应用程序崩溃:
尝试扩展Activity而不是扩展AppCompatActivity。
如果不起作用,也许你有一个Component null,请检查你是否实例化了XML中声明的所有组件。