Android - java.lang.RuntimeException:应用程序一启动就崩溃了

时间:2014-01-23 19:32:00

标签: 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>

2 个答案:

答案 0 :(得分:2)

providernull。你在这里声明

private String provider;

但你永远不会正确地初始化它。

此行返回null

provider = locationManager.getBestProvider(criteria, false);

导致此行的初始异常

Location location = locationManager.getLastKnownLocation(provider);

你可以通过回溯堆栈跟踪来看到它。

调试并查看提供者为null的原因。

答案 1 :(得分:0)

我可以在这里看到一些可能有问题的事情:

provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

提供程序此时为空,您还需要设置权限以获得精细或粗略的用户位置。