简体   繁体   English

Android出勤应用程序JSON解析错误

[英]Android attendance app JSON parsing error

I managed to solve all problems except the JSONException error. 我设法解决了除JSONException错误以外的所有问题。 I know that my code is not efficient and it can be improved by using asynctask etc but for now solving this error is on top of my priority list so please help me out with this. 我知道我的代码效率不高,可以通过使用asynctask等进行改进,但是现在解决此错误是我的优先列表,因此请帮助我。

I am sharing all required codes and details. 我正在共享所有必需的代码和详细信息。

MSRITShowAttendance.java: MSRITShowAttendance.java:

package com.vasan.msritstudentservice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MSRITShowAttendance extends Activity
{
JSONParser JP = new JSONParser();

ProgressDialog PDial = null;

String Pswd, stpwd;

Button Attendance;
EditText AIDEdit, SPEdit;
TextView StIDView, SuIDView, TCView, CAView, PView, CView;

private static String url_att_view = "http://10.0.2.2/MSRIT_Student_Info_Handles/MSRIT_retrieve_particular_attendance.php";

private static final String TAG_ATTENDANCE_SUCCESS = "success";
    private static final String TAG_ATTENDANCE_ARRAY = "attendance";
    private static final String TAG_ATTENDANCE_STUDID = "studid";
    private static final String TAG_ATTENDANCE_SUBID = "subid";
    private static final String TAG_ATTENDANCE_TOTALCLASSES = "totalclasses";
    private static final String TAG_ATTENDANCE_ATTENDEDCLASSES = "attendedclasses";
    private static final String TAG_ATTENDANCE_PERCENTAGE = "percentage";
    private static final String TAG_ATTENDANCE_COMMENTS = "comments";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.msrit_student_details);
    Attendance = (Button) findViewById(R.id.ViewAttendance); 
    AIDEdit = (EditText) findViewById(R.id.AttIDEdit);
    SPEdit = (EditText) findViewById(R.id.PasswordEdit);
    StIDView = (TextView) findViewById(R.id.StudentIDView);
    SuIDView = (TextView) findViewById(R.id.SubjectIDView);
    TCView = (TextView) findViewById(R.id.TotalClassesView);
    CAView = (TextView) findViewById(R.id.ClassesAttendedView);
    PView = (TextView) findViewById(R.id.PercentageView);
    CView = (TextView) findViewById(R.id.CommentView);

Attendance.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            PDial = ProgressDialog.show(MSRITShowAttendance.this, "", "Validating user.Please wait...", true);
            new Thread(new Runnable() 
            {
                public void run()
                {
                    showDetails();
                }
            }).start();

        }
    });
}       

void showDetails()
{
    try
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("attid",AIDEdit.getText().toString().trim())); 
        params.add(new BasicNameValuePair("studpwd",SPEdit.getText().toString().trim()));
        JSONObject json = JP.makeHttpRequest(url_att_view, "GET", params);
        int success = json.getInt(TAG_ATTENDANCE_SUCCESS);  
        new Thread(new Runnable(){
            public void run()
            {
                PDial.dismiss();
            }
        }).start();
        if (success == 1)
        {
            runOnUiThread(new Runnable()
            {
                public void run()
                {
                    Toast.makeText(getApplicationContext(),"Login Credentials Verified!!", Toast.LENGTH_SHORT).show();
                }
            });
            JSONArray attendance = json.getJSONArray(TAG_ATTENDANCE_ARRAY);

                JSONObject c = attendance.getJSONObject(0);

                String TC = ""+(c.getInt(TAG_ATTENDANCE_TOTALCLASSES));
                String AC = ""+(c.getInt(TAG_ATTENDANCE_ATTENDEDCLASSES));
                String PCNTG = ""+(c.getInt(TAG_ATTENDANCE_PERCENTAGE));
                String CMTS = ""+(c.getInt(TAG_ATTENDANCE_COMMENTS));
                StIDView.setText(("Student ID: "+c.getString(TAG_ATTENDANCE_STUDID))); 
                SuIDView.setText(("Subject ID: "+c.getString(TAG_ATTENDANCE_SUBID)));
                TCView.setText(("Total Classes: "+TC.trim())); 
                CAView.setText(("Classes Attended: "+AC.trim())); 
                PView.setText(("Percentage: "+PCNTG.trim())); 
                CView.setText(("Comments: "+CMTS.trim())); 

        }
        else
        {
            showAlert();                
        }   
    }
    catch(JSONException E)
    {
        PDial.dismiss();
        E.printStackTrace();
    }       
}
void showAlert()
{
    MSRITShowAttendance.this.runOnUiThread(new Runnable()
    {
        public void run()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(MSRITShowAttendance.this);
            builder.setTitle("Database Error:Record not found.");
            builder.setMessage("To User:Please check if you have registered.")  
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener()
                   {
                       public void onClick(DialogInterface dialog, int id)
                       {

                       }
                   });                     
            AlertDialog alert = builder.create();
            alert.show();               
        }
    });
  }
}

JSONParser.java: JSONParser.java:

 package com.vasan.msritstudentservice;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.util.Log;

    public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("The Resultant String is",json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser results",json);
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

      }
   }

MSRIT_Retrieve_Particular_Attendance.php: MSRIT_Retrieve_Particular_Attendance.php:

<?php
$response = array();
include 'MSRIT_db_connect.php';
$db = new DB_CONNECT();
if (isset($_GET["attid"]) && $_GET["studpwd"])
{
    $attid = $_GET['attid'];
$studpwd = $_GET['studpwd'];
    $result = mysql_query("SELECT * FROM attendance, studentdetails WHERE attid =   '$attid' AND studpwd = '$studpwd' AND attendance.studid = studentdetails.studid");
    if (!empty($result))
{
        if (mysql_num_rows($result) > 0)
    {
            $result = mysql_fetch_array($result);
            $attendance = array();
            $attendance["attid"] = $result["attid"];
            $attendance["studid"] = $result["studid"];
            $attendance["subid"] = $result["subid"];
            $attendance["totalclasses"] = $result["totalclasses"];
            $attendance["attendedclasses"] = $result["attendedclasses"];
            $attendance["percentage"] = $result["percentage"];
    $attendance["comments"] = $result["comments"];
            $response["success"] = 1;
            $response["attendance"] = array();
            array_push($response["attendance"], $attendance);
            echo json_encode($response);
        }
    else
    {
            $response["success"] = 0;
            $response["message"] = "No attendance found";
            echo json_encode($response);
        }
    }
else
{
        $response["success"] = 0;
        $response["message"] = "No attendance found";
        echo json_encode($response);
    }
}
else
{
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    echo json_encode($response);
}
?>

LogCat: LogCat:

03-27 08:18:36.672: E/The Resultant String is(776): <br />
03-27 08:18:36.672: E/The Resultant String is(776): <font size='1'><table    class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
03-27 08:18:36.672: E/The Resultant String is(776): <tr><th align='left'    bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: comments in   C:\wamp\www\MSRIT_Student_Info_Handles\MSRIT_retrieve_particular_attendance.php on line <i>22</i></th></tr>
03-27 08:18:36.672: E/The Resultant String is(776): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
03-27 08:18:36.672: E/The Resultant String is(776): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
03-27 08:18:36.672: E/The Resultant String is(776): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0005</td><td bgcolor='#eeeeec' align='right'>686336</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\MSRIT_Student_Info_Handles\MSRIT_retrieve_particular_attendance.php' bgcolor='#eeeeec'>..\MSRIT_retrieve_particular_attendance.php<b>:</b>0</td></tr>
03-27 08:18:36.672: E/The Resultant String is(776): </table></font>
03-27 08:18:36.672: E/The Resultant String is(776): {"success":1,"attendance":[{"attid":"2","studid":"1MS10IS049","subid":"1","totalclasses":"44","attendedclasses":"0","percentage":"0.00","comments":null}]}
03-27 08:18:36.732: E/JSON Parser results(776): <br />
03-27 08:18:36.732: E/JSON Parser results(776): <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
03-27 08:18:36.732: E/JSON Parser results(776): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: comments in C:\wamp\www\MSRIT_Student_Info_Handles\MSRIT_retrieve_particular_attendance.php on line <i>22</i></th></tr>
03-27 08:18:36.732: E/JSON Parser results(776): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
03-27 08:18:36.732: E/JSON Parser results(776): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
03-27 08:18:36.732: E/JSON Parser results(776): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0005</td><td bgcolor='#eeeeec' align='right'>686336</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\MSRIT_Student_Info_Handles\MSRIT_retrieve_particular_attendance.php' bgcolor='#eeeeec'>..\MSRIT_retrieve_particular_attendance.php<b>:</b>0</td></tr>
03-27 08:18:36.732: E/JSON Parser results(776): </table></font>
03-27 08:18:36.732: E/JSON Parser results(776): {"success":1,"attendance":[{"attid":"2","studid":"1MS10IS049","subid":"1","totalclasses":"44","attendedclasses":"0","percentage":"0.00","comments":null}]}
03-27 08:18:36.732: E/JSON Parser(776): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-27 08:18:36.742: W/System.err(776): org.json.JSONException: No value for attendance
03-27 08:18:36.752: W/System.err(776):  at org.json.JSONObject.get(JSONObject.java:354)
03-27 08:18:36.752: W/System.err(776):  at org.json.JSONObject.getJSONArray(JSONObject.java:544)
03-27 08:18:36.762: W/System.err(776):  at com.vasan.msritstudentservice.MSRITShowAttendance.showDetails(MSRITShowAttendance.java:104)
03-27 08:18:36.852: W/System.err(776):  at com.vasan.msritstudentservice.MSRITShowAttendance$1$1.run(MSRITShowAttendance.java:72)
03-27 08:18:36.852: W/System.err(776):  at java.lang.Thread.run(Thread.java:856)

The Problem is your "JSON"-String, as it tells in the Logcat. 问题是您的“ JSON”字符串,如Logcat中所述。

Your "json"-string contains HTML-Tags, like br or font size ='1' etc. 您的“ json”字符串包含HTML标记,例如brfont size ='1'等。

Only the last Line of the String-Result in your Logcat is valid JSON. Logcat中只有String-Result的最后一行是有效的JSON。 But you try to parse the whole string, and not only the JSON. 但是您尝试解析整个字符串,而不仅是JSON。

//EDIT //编辑

This Error occures - Like D_Vaibhav ツ told - because your Webserver returns an Error first: 发生此错误-类似于D_Vaibhav告诉-因为您的Web服务器首先返回一个错误:

Notice: Undefined index: comments in C:\\wamp\\www\\MSRIT_Student_Info_Handles\\MSRIT_retrieve_particular_attendance.php on line 22 注意:未定义的索引:第22行的C:\\ wamp \\ www \\ MSRIT_Student_Info_Handles \\ MSRIT_retrieve_particular_attendance.php中的注释

JSON Parsing error occurs when your web service don't return valid JSON. 当您的Web服务未返回有效JSON时,就会发生JSON解析错误。 In this case your server returning HTML contents along with JSON. 在这种情况下,您的服务器返回HTML内容以及JSON。 So you have something wrong at web service side. 因此,您在Web服务方面出了点问题。

by looking at your PHP code You have error at Line 22 in your MSRIT_retrieve_particular_attendance.php 通过查看您的PHP代码,您在MSRIT_retrieve_particular_attendance.php第22行出现错误

Notice: Undefined index: comments in 注意: Undefined index: comments

C:\\wamp\\www\\MSRIT_Student_Info_Handles\\MSRIT_retrieve_particular_attendance.php on line 22 C:\\ wamp \\ www \\ MSRIT_Student_Info_Handles \\ MSRIT_retrieve_particular_attendance.php在第22行

//this is Line 22. you are not getting anything named result["comments"]; from your database query Result I think

$attendance["comments"] = $result["comments"];

your result not returning column named "comments" 您的结果不返回名为“ comments”的列

you can check in that PHP code, I suggest you turn off the warnings from your PHP side, as it may not affect your final result 您可以检入该PHP代码,建议您从PHP端关闭警告,因为这可能不会影响最终结果

Here is the link that will help you to do that 这是可以帮助您做到这一点的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM