getSystemService(Context.CONNECTIVITY_SERVICE)导致崩溃

时间:2014-06-12 13:49:18

标签: java android xml crash connection

这对我来说太奇怪了!

我的应用程序在此行崩溃:

ConnectivityManager connectivity =  (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);

logcat显示此错误:

    06-12 13:27:57.755: E/AndroidRuntime(1431): FATAL EXCEPTION: AsyncTask #1
06-12 13:27:57.755: E/AndroidRuntime(1431): java.lang.RuntimeException: An error occured while executing doInBackground()
06-12 13:27:57.755: E/AndroidRuntime(1431):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.lang.Thread.run(Thread.java:1019)
06-12 13:27:57.755: E/AndroidRuntime(1431): Caused by: java.lang.NullPointerException
06-12 13:27:57.755: E/AndroidRuntime(1431):     at com.example.android.helper.ConnectionDetector.isConnectingToInternet(ConnectionDetector.java:21)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at com.example.android.helper.JSONParser.getJSONFromUrl(JSONParser.java:53)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at com.example.android.Login$1.doInBackground(Login.java:220)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at com.example.android.Login$1.doInBackground(Login.java:1)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
06-12 13:27:57.755: E/AndroidRuntime(1431):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
06-12 13:27:57.755: E/AndroidRuntime(1431):     ... 4 more

这是我的doInBackground:

    inside login.java:

   public class Login extends SherlockActivity{
   Activity mActivity;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.login);

    final Activity mActivity = this;
    }

   //and some irrelevant stuff till we get to doInBackground inside AsyncTask

    protected JSONObject doInBackground(String... params) {
        String phoneNo2 = params[0];
        uid = phoneNo2;
        publishProgress(20);

        jsonParser = new JSONParser(mActivity);

        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("param1", phoneNo2));
        nameValuePair.add(new BasicNameValuePair("retrieve", "login"));

        json = jsonParser.getJSONFromUrl(loginURL, nameValuePair);// <---- here is line number 220 inside login.java


        publishProgress(40);
        if(json!=null){
            return json;
        }
        else{

            MyToast mToast= new MyToast(mActivity);
            mToast.showText("Connection Failed", Toast.LENGTH_SHORT);
        }
        return null;

    }
 }

现在在jsonParser类中:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
Activity _Activity;

// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;

// constructor
public JSONParser(Activity act) {
    this._Activity = act;
}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    MyToast mToast = new MyToast(_Activity);
    // creating connection detector class instance
    cd = new ConnectionDetector(_Activity);
    // get Internet status
    isInternetPresent = cd.isConnectingToInternet();//<---- here is line number 53 inside JSONParser.java
    // check for Internet status
    if (isInternetPresent) {

        mToast.showText("Connection Present", Toast.LENGTH_SHORT);

        // Making HTTP request
        try {

            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 4000);
            HttpConnectionParams.setSoTimeout(httpParameters, 6000);
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            mToast.showText("connection failed", Toast.LENGTH_LONG);
         }catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);            
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;
    } else {
        mToast.showText("please check you internet connection", Toast.LENGTH_SHORT);
    }
    // return JSON String

    return null;
}
}

现在在ConnectionDetector类中:

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){

    //here is exactly where the app crashes: line number 21 inside ConnectionDetector.java 
    ConnectivityManager connectivity =  (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}
}

它完全崩溃在这一行:

ConnectivityManager connectivity =  (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);

这是在AndroidManifest.xml中:

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

    <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Avatheme" 
        android:uiOptions="splitActionBarWhenNarrow" android:supportsRtl="true">
        <!-- Splash screen -->
        <activity
            android:name="com.example.android.SplashScreen"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- Main activity -->
        <activity
            android:name="com.example.android.MainActivity"
            android:label="@string/app_name" >
        </activity>
        <activity android:name="com.example.android.Login"></activity>
    </application>

</manifest>

0 个答案:

没有答案