我正在尝试从我创建了php文件的数据库中获取数据。它返回名称作为对呼叫的回复。网站Ensignweb
程序代码是这样的。
php文件就像这样
<?php
$connect = mysql_connect("localhost","databasename","password");
mysql_select_db("ews_app");
$query = mysql_query("select name from comment");
if(!empty($query)){
if(mysql_num_rows($query)>0){
WHILE($row=mysql_fetch_array($query)):
$comment = array();
$comment["name"] = $row['name'];
echo "$comment<br>";
echo json_encode($comment);
echo "<br>";
endwhile;
}
}
?>
java代码如下:
import java.io.IOException;
import java.io.Reader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://www.ensignweb.com/sandbox/app/comment11.php";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.data);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException,IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();//return 200 if execution is success
if(status==200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG);
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class Read extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
但它没有显示json回复。过去几天我被困在里面了。 请帮助我。我真的需要它。