2014-05-01 87 views
0

我正在嘗試製作需要連接到本地服務器以提取數據的應用程序! 當有連接時,應用程序工作正常!但是當連接關閉時,應用程序等待大約15秒鐘然後崩潰!我已經看到了所有可能的解決方案!但沒有人爲我工作! 請幫忙解決這個問題 這裏是源代碼!Android:連接未建立時應用程序崩潰

package com.example.chap6_5; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.nio.channels.UnresolvedAddressException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.conn.ConnectTimeoutException; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

    EditText Username, Password; 
    TextView Error_Login; 
    Button Button_Login; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Username = (EditText) findViewById(R.id.username); 
     Password = (EditText) findViewById(R.id.password); 
     Error_Login = (TextView)findViewById(R.id.ErrorLogin); 
     Button_Login = (Button)findViewById(R.id.login); 

     Button_Login.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       new DownloadTextTask().execute("http://192.168.1.100/PHP_MVC/mobile/MLogin.php"); 

      } 
     }); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    // ---Connects using HTTP POST--- 
    public InputStream OpenHttpPOSTConnection(String url) { 
     InputStream inputStream = null; 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 


      // ---the key/value pairs to post to the server--- 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("username", Username.getText().toString() 
        .toString())); 
      nameValuePairs.add(new BasicNameValuePair("password", Password.getText().toString())); 
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse httpResponse = httpclient.execute(httpPost); 
      inputStream = httpResponse.getEntity().getContent(); 
     } 
     catch (ConnectTimeoutException e) 
     { 
      Log.d("OpenHttpPOSTConnection TIMEOUT", e.getLocalizedMessage()); 
     } 
     catch (Exception e) { 
      Log.d("OpenHttpPOSTConnection", e.getLocalizedMessage()); 
     } 
     return inputStream; 
    } 

    private String DownloadText(String URL) { 
     int BUFFER_SIZE = 2000; 
     InputStream in = null; 
     try { 
      in = OpenHttpPOSTConnection(URL); 

     } 

     catch (Exception e) { 
      Log.d("Networking", e.getLocalizedMessage()); 
      return ""; 
     } 
     InputStreamReader isr = new InputStreamReader(in); 
     int charRead; 
     String str = ""; 
     char[] inputBuffer = new char[BUFFER_SIZE]; 
     try { 
      while ((charRead = isr.read(inputBuffer)) > 0) { 
       // ---convert the chars to a String--- 
       String readString = String 
         .copyValueOf(inputBuffer, 0, charRead); 
       str += readString; 
       inputBuffer = new char[BUFFER_SIZE]; 
      } 
      in.close(); 
     } catch (IOException e) { 
      Log.d("DownloadText", e.getLocalizedMessage()); 
      return ""; 
     } 
     return str; 
    } 

    private class DownloadTextTask extends AsyncTask<String, Void, String> { 
     protected String doInBackground(String... urls) { 
      return DownloadText(urls[0]); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      try { 

       JSONObject jsonObject = new JSONObject(result); 
       String success = jsonObject.getString("Success"); 
       Toast.makeText(getBaseContext(), success, Toast.LENGTH_LONG).show(); 
       if (Integer.parseInt(success)==1) 
       { 
        Log.d("DownloadTextTask", "success"); 
        Intent i_Dashboard = new Intent(getApplicationContext(),Dashboard.class); 
        startActivity(i_Dashboard); 
        finish(); 
       } 
       else 
       { 
        Error_Login.setText("Error Login : Username/password are wrong !"); 
       } 
       Log.d("DownloadTextTask", result); 

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

     } 
    } 
} 

將帖子新onCreate方法

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Username = (EditText) findViewById(R.id.username); 
     Password = (EditText) findViewById(R.id.password); 
     Error_Login = (TextView)findViewById(R.id.ErrorLogin); 
     Button_Login = (Button)findViewById(R.id.login); 

     Button_Login.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       ConnectionDetector conn = new ConnectionDetector(getApplicationContext()); 
       if(conn.isConnectingToInternet()) 
       { 
        Toast.makeText(getApplicationContext(), "CONNECTEDs", Toast.LENGTH_LONG).show(); 
       new DownloadTextTask().execute("http://192.168.1.100/PHP_MVC/mobile/MLogin.php"); 
       } 
       else 
        Toast.makeText(getApplicationContext(), "No connection", Toast.LENGTH_LONG).show(); 

      } 
     }); 

    } 

這裏是logcat的:

05-01 06:08:07.673: D/OpenGLRenderer(1276): TextureCache::get: create texture(0xb881bb38): name, size, mSize = 13, 7488, 1106852 
05-01 06:08:10.773: D/OpenHttpPOSTConnection TIMEOUT(1276): Connect to /192.168.1.100:80 timed out 
05-01 06:08:10.773: W/dalvikvm(1276): threadid=10: thread exiting with uncaught exception (group=0xa62b0288) 
05-01 06:08:10.773: E/AndroidRuntime(1276): FATAL EXCEPTION: AsyncTask #1 
05-01 06:08:10.773: E/AndroidRuntime(1276): java.lang.RuntimeException: An error occured while executing doInBackground() 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at android.os.AsyncTask$3.done(AsyncTask.java:299) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.lang.Thread.run(Thread.java:856) 
05-01 06:08:10.773: E/AndroidRuntime(1276): Caused by: java.lang.NullPointerException 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.io.Reader.<init>(Reader.java:64) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.io.InputStreamReader.<init>(InputStreamReader.java:122) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.io.InputStreamReader.<init>(InputStreamReader.java:59) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at com.example.chap6_5.MainActivity.DownloadText(MainActivity.java:118) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at com.example.chap6_5.MainActivity.access$0(MainActivity.java:106) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at com.example.chap6_5.MainActivity$DownloadTextTask.doInBackground(MainActivity.java:140) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at com.example.chap6_5.MainActivity$DownloadTextTask.doInBackground(MainActivity.java:1) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at android.os.AsyncTask$2.call(AsyncTask.java:287) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
05-01 06:08:10.773: E/AndroidRuntime(1276):  ... 5 more 
05-01 06:08:10.893: D/OpenGLRenderer(1276): TextureCache::get: create texture(0xb87ab998): name, size, mSize = 24, 7488, 1114340 
05-01 06:08:11.329: D/OpenGLRenderer(1276): TextureCache::flush: target size: 668604 
05-01 06:08:11.329: D/OpenGLRenderer(1276): TextureCache::callback: name, removed size, mSize = 2, 5184, 1109156 
05-01 06:08:11.329: D/OpenGLRenderer(1276): TextureCache::callback: name, removed size, mSize = 4, 20736, 1088420 
05-01 06:08:11.329: D/OpenGLRenderer(1276): TextureCache::callback: name, removed size, mSize = 10, 2304, 1086116 
05-01 06:08:11.329: D/OpenGLRenderer(1276): TextureCache::callback: name, removed size, mSize = 13, 7488, 1078628 
05-01 06:08:11.329: D/OpenGLRenderer(1276): TextureCache::callback: name, removed size, mSize = 6, 7488, 1071140 
05-01 06:08:11.329: D/OpenGLRenderer(1276): TextureCache::callback: name, removed size, mSize = 1, 1048576, 22564 

非常感謝!

+0

然後發佈您的logcat。 –

+0

@SimplePlan:後期編輯,Logcat添加! – satyres

+0

設置一些'setConnectionTimeout()'到你的'HttpPost' –

回答

2

第一種方法

OpenHttpPOSTConnection功能,檢查互聯網

... 
HttpResponse httpResponse = httpclient.execute(httpPost); 
if(httpResponse.getStatusLine().getStatusCode() == 200) //which means there is connection 
    inputStream = httpResponse.getEntity().getContent(); 
else 
    return null; 

的狀態,然後檢查是否爲空走出的AsyncTask的..也許通過提供onPostExcute和空值,並且依靠null顯示敬酒來告訴用戶沒有互聯網連接。

第二種方法

,你也可以有一個ConnectionDetector類,你檢查是否有執行的AsyncTask之前互聯網連接..

public class ConnectionDetector { 

private Context _context; 

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

public boolean isConnectingToInternet(){ 
    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; 
    } 
} 

那麼您執行AysncTask前:

ConnectionDetector conn = new ConnectionDetector(getApplicationContext()); 
if(conn.isConnectiontoInternet()) 
    new DownloadTextTask().execute("http://192.168.1.100/PHP_MVC/mobile/MLogin.php"); 
else 
    //show toast. 

PS:請確保您將此權限添加到您的清單中:

<!-- Network State Permissions --> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
+0

感謝您的評論!但第一個方法不適合我,我正在嘗試第二個! – satyres

+0

我很抱歉,但仍然得到同樣的問題,應用程序崩潰,甚至與第二種方法:( – satyres

+0

isConnectiontoInternet總是返回true!即使關閉我的互聯網連接!和我的本地網絡!( – satyres

1

您收到空指針異常。檢查是否有空值,然後如果得到空值,則相應地執行邏輯。最重要的是,在執行網絡IO之前,您應該檢查是否有網絡連接,以幫助防止發生這些類型的問題。

您可以通過以下這個問題列出的解決方法做到這一點:Detect whether there is an Internet connection available on Android

+0

我嘗試了鏈接中的功能!但也沒有工作!該applcation仍然崩潰!我不明白爲什麼! – satyres

+0

因爲你得到一個空指針異常。在你的代碼的某個地方,你正在訪問的東西是null。通過每行調試並檢查對象是否爲空。如果是這樣,那是你的問題。一旦你找到它,你需要弄清楚爲什麼它是空的。解決這個問題,然後解決問題。 –

+0

感謝您的評論,但是當連接正常時!沒有零點!所以問題是與連接! – satyres

0

這將如果在的InputStream = NULL發生。如果網絡發生故障,OpenHttpPOSTConnection會嘗試從網絡中讀取,並會失敗並拋出異常。你抓住這個。這將導致函數返回null,並且inputstream將爲空。

OpenHttpPOSTConnection返回值的空檢查將解決此問題

+0

問題是我如何捕獲這個異常,以防止應用程序崩潰! – satyres

+0

你可以捕捉它在最外面的塊,而不是捕捉它。讓OpenHttpPOSTConnection拋出一個IOException – user868459