2014-12-06 37 views
0

我有一個非常簡單的要求。我有一個登錄活動。一旦用戶輸入登錄信息並點擊提交按鈕,應用程序應該執行互聯網訪問檢查。如果設備未連接到互聯網,則應顯示「沒有互聯網訪問」的敬酒。如果可以訪問互聯網,那麼應用程序將執行認證並導航到主頁。Android:無源路徑

我已經寫了代碼片段來執行互聯網檢查在一個單獨的類爲可用性。該代碼片段如下:

package com.example.rinventory.Common; 

import android.content.Context; 
import android.net.NetworkInfo; 
import android.net.ConnectivityManager; 

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

    public boolean isConnectingToInternet() 
    { 
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    //Get all the active networks available. 
    NetworkInfo info = connectivity.getActiveNetworkInfo(); 

    //If it is connected to available networks return true else false. 
    if(info != null && info.isConnected()) 
     return true; 
    else 
     return false; 
    } 
} 

我的登錄作業的提交按鈕功能如下:

public class RInventoryLogin extends ActionBarActivity 
{ 
    boolean isInternetPresent = false; 
    ConnectionDetector detect; 

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

    Button btnLogin = (Button) findViewById(R.id.btnSubmit); 

    btnLogin.setOnClickListener(new OnClickListener() 
    { 

     @Override 
     public void onClick(View v) 
     { 
      //Throws error at this particular line 
      isInternetPresent = detect.isConnectingToInternet(); 

      if(isInternetPresent) 
      { 
      EditText editEmail = (EditText)findViewById(R.id.editEmail); 
      EditText editPassword = (EditText)findViewById(R.id.editPassword); 
      LoginData data = new LoginData(); 

      data.setEmail(editEmail.getText().toString()); 
      data.setPassword(editPassword.getText().toString()); 

      new CallJsonParserLogin().execute(data); 
      } 
      else 
      { 
      Toast.makeText(RInventoryLogin.this, "No Internet Access", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    }); 
    } 
} 

當我嘗試執行,它加載的活動。然而,一旦我進入登錄信息,並點擊提交應用程序關閉與「意外您的應用程序已停止工作」

我已經包括互聯網,清單文件,網絡狀態參數。

當我評論線

isInternetPresent = detect.isConnectingToInternet();

和隨後的if else塊,它只是正常工作。我在這裏失蹤的問題可能是什麼?

我嘗試過創建演示應用程序並且工作正常。

請幫

+0

堆棧跟蹤會說的錯誤是什麼和哪些行代碼造成的。請編輯您的問題並加入。 – Simon 2014-12-06 12:25:10

+0

你的意思是日誌貓的細節? – 2014-12-06 12:27:41

回答

0

你沒有初始化detect對象。

點擊監聽器設置你的按鈕之前加入這一行:

detect = new ConnectionDetector(this); 
+0

非常感謝,它解決了這個問題。但出於好奇,我沒有初始化另一個演示應用程序中的偵測對象,它只是工作正常。我不知道爲什麼? – 2014-12-06 12:32:26

+0

請接受我的答案是否能解決你的問題:) 後的代碼,我會看看爲你 – 2014-12-06 12:34:25

+0

我接受你的答案,它允許用戶僅在一定的時間分鐘後接受的答案...對不起,延遲,再次感謝:) – 2014-12-06 12:35:53