Android JSON 解析无效
Android JSON parsing doesn't work
我正在尝试使用 JSON 从 php 脚本获取 Json 数据到我的 android 应用程序,并将这些值放在文本视图中。但是当我运行应用程序时,我得到一个空的文本视图。怎么了?
注意:我在清单中添加了互联网权限,并且 httppost 和 httpresponse 工作正常。当我更改 POST 以从我的网络浏览器获取并运行 PHP 脚本时,数据显示正常,问题出在 JSON.
PHP:
<?php
header('Content-type: application/json');
$hostname_localhost ="localhost";
$database_localhost ="myapp_db";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$roomname = $_POST['roomname'];
$query_search = "select id,c_username,c_message from chats where c_roomname = '".$roomname."' ORDER BY `id`";
$query_exec = mysql_query($query_search) or die(mysql_error());
$final_data = array(); $i=0;
while($query_row = mysql_fetch_assoc($query_exec))
{
$username = $query_row['c_username'];
$message = $query_row ['c_message'];
$id = $query_row ['id'];
$data = array('id'=>$id , 'name'=> 'username : '. $username ,'message'=>'message : '. $message);
$final_data[$i]=$data;
$i++;
print(json_encode($data));
}
//print(json_encode($final_data));
?>
安卓:
public class ChatActivity extends Activity {
public final static String CHATTER_NAME = "com.gowemto.gowemto.USERNAME";
public final static String CHATTER_COLOR = "com.gowemto.gowemto.CCOLOR";
public final static String CHATROOM_NAME = "com.gowemto.gowemto.CRNAME";
String username;
String ccolor;
String ncolor;
String crname;
String usrname;
String usrcolor;
String usrmessage;
String usrdate;
TextView teview;
HttpPost httppost;
StringBuffer buffer;
String response3;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
HttpPost httppost2;
StringBuffer buffer2;
HttpResponse response4;
HttpClient httpclient2;
List<NameValuePair> nameValuePairs2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
username = intent.getStringExtra(CHATTER_NAME);
ccolor = intent.getStringExtra(CHATTER_COLOR);
crname = intent.getStringExtra(CHATROOM_NAME);
String mycolor = ccolor.trim();
teview = (TextView) findViewById(R.id.myviewer);
new Thread(new Runnable() {
public void run() {
getchats();
}
}).start();
setTitle(crname);
}
public void getchats(){
try{
httpclient2=new DefaultHttpClient();
httppost2= new HttpPost("http://10.0.2.2/myappsite/chatdata"); // make sure the url is correct.
//add your data
nameValuePairs2 = new ArrayList<NameValuePair>(1);
nameValuePairs2.add(new BasicNameValuePair("roomname",crname));
httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
//Execute HTTP Post Request
// edited by James from coderzheaven.. from here....
response4 = httpclient2.execute(httppost2);
ResponseHandler<String> responseHandler2 = new BasicResponseHandler();
final String response5 = httpclient2.execute(httppost2, responseHandler2);
String jsonResult = inputStreamToString(response4.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
JSONObject object = mArray.getJSONObject(i);
usrname = object.getString("username");
usrmessage = object.getString("message");
}
runOnUiThread(new Runnable() {
public void run() {
teview.setText(usrname + "\n" + usrmessage);
}
});
}catch(Exception e){
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
在 php 脚本中,更改
$data = array('id'=>$id , 'name'=> 'username : '. $username ,'message'=>'message : '. $message);
至
$data = array('id'=>$id , 'username'=> 'username : '. $username ,'message'=>'message : '. $message);
我正在尝试使用 JSON 从 php 脚本获取 Json 数据到我的 android 应用程序,并将这些值放在文本视图中。但是当我运行应用程序时,我得到一个空的文本视图。怎么了?
注意:我在清单中添加了互联网权限,并且 httppost 和 httpresponse 工作正常。当我更改 POST 以从我的网络浏览器获取并运行 PHP 脚本时,数据显示正常,问题出在 JSON.
PHP:
<?php
header('Content-type: application/json');
$hostname_localhost ="localhost";
$database_localhost ="myapp_db";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$roomname = $_POST['roomname'];
$query_search = "select id,c_username,c_message from chats where c_roomname = '".$roomname."' ORDER BY `id`";
$query_exec = mysql_query($query_search) or die(mysql_error());
$final_data = array(); $i=0;
while($query_row = mysql_fetch_assoc($query_exec))
{
$username = $query_row['c_username'];
$message = $query_row ['c_message'];
$id = $query_row ['id'];
$data = array('id'=>$id , 'name'=> 'username : '. $username ,'message'=>'message : '. $message);
$final_data[$i]=$data;
$i++;
print(json_encode($data));
}
//print(json_encode($final_data));
?>
安卓:
public class ChatActivity extends Activity {
public final static String CHATTER_NAME = "com.gowemto.gowemto.USERNAME";
public final static String CHATTER_COLOR = "com.gowemto.gowemto.CCOLOR";
public final static String CHATROOM_NAME = "com.gowemto.gowemto.CRNAME";
String username;
String ccolor;
String ncolor;
String crname;
String usrname;
String usrcolor;
String usrmessage;
String usrdate;
TextView teview;
HttpPost httppost;
StringBuffer buffer;
String response3;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
HttpPost httppost2;
StringBuffer buffer2;
HttpResponse response4;
HttpClient httpclient2;
List<NameValuePair> nameValuePairs2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
username = intent.getStringExtra(CHATTER_NAME);
ccolor = intent.getStringExtra(CHATTER_COLOR);
crname = intent.getStringExtra(CHATROOM_NAME);
String mycolor = ccolor.trim();
teview = (TextView) findViewById(R.id.myviewer);
new Thread(new Runnable() {
public void run() {
getchats();
}
}).start();
setTitle(crname);
}
public void getchats(){
try{
httpclient2=new DefaultHttpClient();
httppost2= new HttpPost("http://10.0.2.2/myappsite/chatdata"); // make sure the url is correct.
//add your data
nameValuePairs2 = new ArrayList<NameValuePair>(1);
nameValuePairs2.add(new BasicNameValuePair("roomname",crname));
httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
//Execute HTTP Post Request
// edited by James from coderzheaven.. from here....
response4 = httpclient2.execute(httppost2);
ResponseHandler<String> responseHandler2 = new BasicResponseHandler();
final String response5 = httpclient2.execute(httppost2, responseHandler2);
String jsonResult = inputStreamToString(response4.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
JSONObject object = mArray.getJSONObject(i);
usrname = object.getString("username");
usrmessage = object.getString("message");
}
runOnUiThread(new Runnable() {
public void run() {
teview.setText(usrname + "\n" + usrmessage);
}
});
}catch(Exception e){
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
在 php 脚本中,更改
$data = array('id'=>$id , 'name'=> 'username : '. $username ,'message'=>'message : '. $message);
至
$data = array('id'=>$id , 'username'=> 'username : '. $username ,'message'=>'message : '. $message);