[英]Having trouble connecting to my database server: ArrayIndexOutOfBoundsException
[英]Having some trouble connecting an android app to an online database
我在學校的一個小型Android項目中遇到了一些問題。 我需要通過發送用戶名從.php通過在線數據庫請求密碼。 它應該返回一個加密的密碼。 但是我用來連接數據庫並接收密碼的方法似乎存在問題。 LogCat給了我這些:
HTTP連接java.net.UnknownHostException中的錯誤:boekenapp.atwebpages.com
轉換結果java.lang.NullPointerException時出錯
解析數據org.json.JSONException時出錯:輸入的結尾在字符0處
所以我的問題是:我做錯了什么?/我需要進行哪些更改才能使其正常工作?
編碼:
public static String phpconnect(String name, String value) {
String result = "";
InputStream is = null;
//variables to send to database
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(name,value));
//HTTP post
try{
HttpClient httpclient = new DefaultHttpClient();
URI connection = new URI("http://boekenapp.atwebpages.com/phpscript.php");
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in HTTP connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
} catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse JSON data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","userid: "+json_data.getInt("userid")+", password: "+json_data.getString("password"));
}
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return "";
}
因為您僅登錄第一個catch塊,所以第二個try塊將始終執行。
您應該考慮一個return語句或throw語句。 一種替代方法是將第二個try塊嵌入第一個try塊中,但是這樣可能會導致可讀性降低。
在您的情況下,問題在於連接本身失敗。 您確定已建立網絡嗎? 是否可以從計算機和Android ping主機(可以在CLI上使用adb shell ping <host>
)。
並且不要在第一行截斷錯誤堆棧,必須從上至下完整讀取堆棧,直到找到導致錯誤的代碼為止。
首先,瀏覽器中使用的該代碼中的URL重定向到www.alotspace.com/error-404/正如您所知。
如果不進行測試,僅查看代碼,我將從檢查響應的狀態行開始。 這就是
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// here all is OK, you can check for 404 and so on
}
我還看到您使用緩沖的讀取器處理響應,並將所有內容進一步放入StringBuilder中。 更好的選擇是使用gson 。
但是首先要關注與網絡相關的初始異常。 其他異常只是單獨的try / catch塊的結果(如@Snicolas所指出的)。 Unknownhost聽起來像沒有網絡。 重定向將僅返回與預期不同的輸出,而不是unkownhost。 要驗證您正在測試的Android設備上的瀏覽網址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.