我在連接到我的數據庫時遇到了一些麻煩,我可能需要一些幫助來查看它是錯誤的.java文件還是我的.php文件。結果現在是 「無法連接到數據庫」HttpClient無法連接到數據庫
PHP文件http://pastebin.com/9fMmzprd
的.java:
package com.example.stolle.httpclient;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class contact extends Activity {
TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
StrictMode.enableDefaults();
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result ="";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://stolle.se.preview.citynetwork.se/kontaktApp/read_allcontacts.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch (Exception e){
Log.e("log_tag","Error in http connection"+e.toString());
resultView.setText("Couldnt connect to database");
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line=reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag","Error converting result"+e.toString());
}
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length(); i++){
JSONObject json = jArray.getJSONObject(i);
s = s+
"id : "+json.getInt("id")+"\n"+
"name : "+json.getString("name")+"\n"+
"mail : "+json.getString("mail")+"\n"+
"company :"+json.getString("company")+"\n\n";
}
resultView.setText(s);
}
catch (Exception e){
//to do handle exception
Log.e("Log_tag", "Error Parsing Data" + e.toString());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat顯示任何錯誤?您的PHP文件工作正常,並閱讀所有數據。我檢查了它。 ;)@Filip –