我正在尝试通过AsyncTask连接到我服务器上的外部数据库,但Eclipse在日志中显示错误 -
以下是我正在使用的代码 -
MainActivity.java:
package com.deltware.newco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView res;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.res = (TextView) this.findViewById(R.id.textView1);
this.btn1 = (Button) this.findViewById(R.id.button1);
this.btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new getAllUsersTask().execute(new Connector());
}
});
}
public void setTextToView(JSONArray json){
String s= "";
for(int i = 0; i<json.length(); i++){
JSONObject jo = null;
try{
jo = json.getJSONObject(i);
s += "Name: " + jo.getString("name") +
"Email: " + jo.getString("email");
}catch(JSONException e){
e.printStackTrace();
}
}
this.res.setText(s);
}
private class getAllUsersTask extends AsyncTask<Connector, Long,JSONArray>{
@Override
protected JSONArray doInBackground(Connector... param) {
return param[0].getAllUsers();
}
@Override
protected void onPostExecute(JSONArray result) {
setTextToView(result);
}
}
}
Connector.java:
package com.deltware.newco;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.DefaultedHttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class Connector {
public JSONArray getAllUsers(){
String url = "url to the location of my php file";
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
httpEntity = httpResponse.getEntity();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
JSONArray json = null;
if(httpEntity == null){
try{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response:",entityResponse);
json = new JSONArray(entityResponse);
}catch(JSONException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
return json;
}
}
PHP文件:
$query = mysqli_query($db, "SELECT name, email, gender FROM users");
while($row = mysqli_fetch_assoc($query)){
$ouput[] = $row;
}
echo json_encode($ouput);
我正在使用Eclipse和Android 4.4 KitKat。