[英]How to display table from the database using json response in Android? (I'm getting JsonArray Fail error in this code)
This is Attendance.java file 这是Attendance.java文件
package com.glbwebsim;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;`
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;
public class Attendance extends Activity
{
static InputStream iStream = null;
static JSONArray jArray = null;
static String json = "";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main7);
Button details = (Button) findViewById(R.id.mydetails);
details.setOnClickListener(new View.OnClickListener()
{
@SuppressWarnings({ "deprecation", "unused" })
public void onClick(View view)
{
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://frndz4ever.com/glbsim/attend.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
// Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
//convert response to string
StringBuilder sb = new StringBuilder();
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
// Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try
{
JSONArray jArray = new JSONArray("["+result+"]");
String re=jArray.getString(jArray.length()-1);
TableLayout tv=(TableLayout) findViewById(R.id.table);
tv.removeAllViewsInLayout();
int flag=1;
for(int i=0;i<re.length();i++)
{
TableRow tr=new TableRow(Attendance.this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
if(flag==1)
{
TextView b6=new TextView(Attendance.this);
b6.setText("Roll_no");
b6.setTextColor(Color.BLACK);
b6.setTextSize(18);
tr.addView(b6);
TextView b19=new TextView(Attendance.this);
b19.setPadding(10, 0, 0, 0);
b19.setTextSize(18);
b19.setText("Subjects");
b19.setTextColor(Color.BLACK);
tr.addView(b19);
TextView b29=new TextView(Attendance.this);
b29.setPadding(10, 0, 0, 0);
b29.setText("Present");
b29.setTextColor(Color.BLACK);
b29.setTextSize(18);
tr.addView(b29);
TextView b30=new TextView(Attendance.this);
b30.setPadding(10, 0, 0, 0);
b30.setText("Absent");
b30.setTextColor(Color.BLACK);
b30.setTextSize(18);
tr.addView(b30);
tv.addView(tr);
final View vline = new View(Attendance.this);
vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 2));
vline.setBackgroundColor(Color.BLUE);
tv.addView(vline);
}
else
{
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","Roll_no: "+json_data.getInt("Roll_no")+
", Subjects: "+json_data.getString("Subjects")+
", Present: "+json_data.getInt("Present")+
",Absent: "+json_data.getInt("Absent"));
TextView b=new TextView(Attendance.this);
String stime=String.valueOf(json_data.getInt("Roll_no"));
b.setText(stime);
b.setTextColor(Color.RED);
b.setTextSize(15);
tr.addView(b);
TextView b1=new TextView(Attendance.this);
b1.setPadding(10, 0, 0, 0);
b1.setTextSize(15);
String stime1=json_data.getString("Subjects");
b1.setText(stime1);
b1.setTextColor(Color.WHITE);
tr.addView(b1);
TextView b2=new TextView(Attendance.this);
b2.setPadding(10, 0, 0, 0);
String stime2=String.valueOf(json_data.getInt("Present"));
b2.setText(stime2);
b2.setTextColor(Color.RED);
b2.setTextSize(15);
tr.addView(b2);
TextView b3=new TextView(Attendance.this);
b3.setPadding(10, 0, 0, 0);
String stime3=String.valueOf(json_data.getInt("Absent"));
b3.setText(stime2);
b3.setTextColor(Color.RED);
b3.setTextSize(15);
tr.addView(b3);
tv.addView(tr);
final View vline1 = new View(Attendance.this);
vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
vline1.setBackgroundColor(Color.WHITE);
tv.addView(vline1);
}
}}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
return;
}
});
}}
I'm getting JsonArray fail error on click of the button. 单击该按钮,我收到JsonArray失败错误。 Please help. 请帮忙。
LogCat: logcat的:
04-20 20:54:37.458: D/StrictMode(9281): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1151) 04-20 20:54:37.458: D/StrictMode(9281): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163) 04-20 20:54:37.458: D/StrictMode(9281): at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
See the code below for reference, it might have errors, its just to get an ides how it works. 请参阅下面的代码以供参考,它可能有错误,只是为了了解其工作原理。
Any network activity should be performed in doInBackground
. 任何网络活动都应在doInBackground
执行。 Do not perform any action on UI. 不要在UI上执行任何操作。
Once the doInBackground
is complete, the data is returned to onPostExecute
. 一旦doInBackground
完成,数据将返回给onPostExecute
。 Now you can perform your UI actions here. 现在,您可以在此处执行UI操作。
public class Attendance extends Activity {
static InputStream iStream = null;
static JSONArray jArray = null;
static String json = "";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button details = (Button) findViewById(R.id.mydetails);
details.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings({ "deprecation", "unused" })
public void onClick(View view) {
new makeHTTPRequest().execute();
}
});
}
private class makeHTTPRequest extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String result = null;
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://frndz4ever.com/glbsim/attend.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("log_tag", "connection success ");
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
// Toast.makeText(getApplicationContext(), "Connection fail",
// Toast.LENGTH_SHORT).show();
}
// convert response to string
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
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());
}
return result;
}
protected void onPostExecute(String result) {
// parse json data
try {
JSONArray jArray = new JSONArray(result);
String re = jArray.getString(jArray.length() - 1);
int flag = 1;
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(0);
Log.i("log_tag",
"Index: "+ i + " Roll_no: " + json_data.getInt("Roll_no")
+ ", Subjects: "
+ json_data.getString("Subject")
+ ", Present: "
+ json_data.getInt("Present")
+ ",Absent: "
+ json_data.getInt("Absent"));
}
// Perform any required actions here
}
catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}
}
} }
I have updated the private class makeHTTPRequest
我已经更新了私有类makeHTTPRequest
dont forget to add 不要忘记添加
<uses-permission android:name="android.permission.INTERNET" />
under the uses-sdk
tag 在uses-sdk
标签下
And this is the Logcat
output: 这是Logcat
输出:
04-21 23:37:13.904: I/log_tag(14032): Index: 0 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
04-21 23:37:13.905: I/log_tag(14032): Index: 1 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
04-21 23:37:13.905: I/log_tag(14032): Index: 2 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
04-21 23:37:13.905: I/log_tag(14032): Index: 3 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
First try this, if it works, add code step by step to enhance your app. 首先尝试一下,如果可行,请逐步添加代码以增强您的应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.