java - Android - java.lang.RuntimeException :App is crashing as soon as it launches

标签 java android

我正在尝试将 GPS 坐标发送到 Android 中的服务器,但我的应用程序一运行就崩溃了,我是 Android 新手,所以我不知道如何解决此问题

这是我的 logcat 文件

01-23 14:03:40.220: E/AndroidRuntime(880): FATAL EXCEPTION: main
01-23 14:03:40.220: E/AndroidRuntime(880): Process: com.example.server2, PID: 880
01-23 14:03:40.220: E/AndroidRuntime(880): java.lang.RuntimeException: Unable to   start   activity ComponentInfo{com.example.server2/com.example.server2.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-23 14:03:40.220: E/AndroidRuntime(880):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Handler.dispatchMessage(Handler.java:102)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Looper.loop(Looper.java:136)
01-23 14:03:40.220: E/AndroidRuntime(880):  at android.app.ActivityThread.main(ActivityThread.java:5017)
01-23 14:03:40.220: E/AndroidRuntime(880):  at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880):  at java.lang.reflect.Method.invoke(Method.java:515)
01-23 14:03:40.220: E/AndroidRuntime(880):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-23 14:03:40.220: E/AndroidRuntime(880):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-23 14:03:40.220: E/AndroidRuntime(880):  at dalvik.system.NativeStart.main(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): Caused by: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880):  at android.location.LocationManager.checkProvider(LocationManager.java:1623)
01-23 14:03:40.220: E/AndroidRuntime(880):  at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1167)
01-23 14:03:40.220: E/AndroidRuntime(880):  at com.example.server2.MainActivity.onCreate(MainActivity.java:71)
01-23 14:03:40.220: E/AndroidRuntime(880):  at android.app.Activity.performCreate(Activity.java:5231)
01-23 14:03:40.220: E/AndroidRuntime(880):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-23 14:03:40.220: E/AndroidRuntime(880):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

这是我的 MainActivity.java:

public class MainActivity extends Activity implements LocationListener {

private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
String lat,lng;
EditText etResponse;
TextView tvIsConnected;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // get reference to the views
    etResponse = (EditText) findViewById(R.id.etResponse);
    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);

    // check if you are connected or not
    if(isConnected()){
        tvIsConnected.setBackgroundColor(0xFF00CC00);
        tvIsConnected.setText("You are conncted");
    }
    else{
        tvIsConnected.setText("You are NOT conncted");
    }
     latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);

        // Get the location manager
        locationManager = (LocationManager)     getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
    Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
          System.out.println("Provider " + provider + " has been selected.");
          onLocationChanged(location);
        } else {
          latituteField.setText("Location not available");
          longitudeField.setText("Location not available");
    }



    // call AsynTask to perform network operation on separate thread
    new HttpAsyncTask().execute("http://182.18.144.140:80");
}

public static String GET(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

  private static String convertInputStreamToString(InputStream inputStream) throws IOException{
      BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

public boolean isConnected(){
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) 
            return true;
        else
            return false;   
 }

@Override
public void onLocationChanged(Location location) {
    lat = Double.toString(location.getLatitude());
     lng = Double.toString (location.getLongitude());
    latituteField.setText(String.valueOf(lat));
    longitudeField.setText(String.valueOf(lng));
    // 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 class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://182.18.144.140:80");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    //      nameValuePairs.add(new BasicNameValuePair("android", editText1.getText().toString()));  
            nameValuePairs.add(new BasicNameValuePair("LAT", lat));
            nameValuePairs.add(new BasicNameValuePair("LON", lng));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            try {
                httpclient.execute(httppost);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }




        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.i("HTTP Failed", e.toString());
        }           

        return null;
    }



    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
        etResponse.setText(result);
   }
}

}

我的manifest.xml是这样的

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

 <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.server2.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>
   </application>

 </manifest>

最佳答案

providernull。您在这里声明

private String provider;

但你从未正确初始化它。

该行返回null

provider = locationManager.getBestProvider(criteria, false);

这导致了您在这一行的初始异常

Location location = locationManager.getLastKnownLocation(provider);

您可以通过退一步查看堆栈跟踪来看到这一点。

调试它并查看为什么提供程序为null

关于java - Android - java.lang.RuntimeException :App is crashing as soon as it launches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21317659/

相关文章:

java - 转换错误

java - 删除了 Linux 标识符

android - 如何在应用程序从最近的任务中被杀死后重新启动服务

安卓工作室 : Back Button for previous Activity

android - 通过 https 发送和接收 json 消息

java - Android TV Fragment(主 fragment )以垂直方向出现?

java - 使用排列查找字符串中所有可能的组合

java - 静态工厂 : Java Design Issue

java - FCM 数据消息无法正常工作

android - 有关 android.graphics.Camera 和 android.graphics.Matrix 的文档或教程?