Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Android中使用json响应显示数据库中的表?(我在这段代码中遇到JsonArray失败错误)_Java_Android_Mysql_Json - Fatal编程技术网

Java 如何在Android中使用json响应显示数据库中的表?(我在这段代码中遇到JsonArray失败错误)

Java 如何在Android中使用json响应显示数据库中的表?(我在这段代码中遇到JsonArray失败错误),java,android,mysql,json,Java,Android,Mysql,Json,这是Attention.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;

这是Attention.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;


           }
              });
           }}

请参阅下面的代码以供参考,它可能有错误,这只是为了了解它是如何工作的

任何网络活动都应在
doInBackground
中执行。 不要在UI上执行任何操作

doInBackground
完成后,数据将返回到
onPostExecute
。 现在,您可以在此处执行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();
        }

    }

}

首先尝试一下这个,如果可行的话,一步一步地添加代码来增强你的应用程序

还可以在这里共享您试图解析的json字符串:04-20 20:54:37.458:D/StrictMode(9281):在android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1151)04-20:54:37.458:D/StrictMode(9281):在libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)04-20:54:37.458:D/StrictMode(9281):在libcore.io.IoBridge.recvfrom(IoBridge.java:506)上,我正在解析的代码中已经有json字符串。您应该使用AsyncTask来执行任何网络活动。@MTahir如何使用AsyncTask?在参数中添加什么-受保护的字符串doInBackground(字符串…参数)?无,使用上述方法尝试呼叫您的服务器,并检查是否收到任何响应My app force closed:(04-20 23:37:46.328:I/ActivityManager(601):从pid 5096 04-20 23:37:46.419:I/ActivityManager(601)启动u0{cmp=com.whatsapp/.ContactInfo(有额外功能)}从pid 5096 04-20 23:37:46.419:I/ActivityManager(601):显示com.whatsapp/.ContactInfo:+78ms 04-20 23:37:51.074:I/ActivityManager(601):从pid 5096 04-20 23:37:51.204:I/ActivityManager(601)启动u0{cmp=com.whatsapp/.ContactInfo}:显示com.whatsapp/.ContactInfo:+108ms 04-20 23:37:52.625:V/DeadZone(687):消耗错误点击:(116.0,23.0)你知道如何使用logcat吗?搜索一些教程/示例。也可以搜索
AsyncTask
教程和示例。在使用它们之前,你需要知道它们是如何工作的。
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();
        }

    }

}
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