【发布时间】:2023-04-07 12:30:01
【问题描述】:
我从数据库中读取数据(仅最后一行,我在我的 php 文件中执行)我想要做的是分别使用每个字段的数据但问题是 JSONArray 为空我尝试了很多在不同的帖子中寻找它的方法,但它总是空的。
这是我的代码
public class MainActivity extends Activity {
/** Called when the activity is first created. */
JSONArray jArray = null;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String ct_id;
String ct_name;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://xxx.php");
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);
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());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("fecha");
ct_name=json_data.getString("dia");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "JSON is empty" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
它总是捕获 JSONException e1。
提前谢谢大家
【问题讨论】:
-
你确定 PHP 正确地格式化了回复吗?
-
我在这个问题中没有看到任何对 PHP 的引用。
-
发布传输的 json 字符串,以便查看 json 是否正常。此外,如果您添加一些标题,这也可能会有所帮助。
-
@Matt:在标签里。
-
@hakra 我知道。 在问题中哪里提到过 PHP?