Android考勤应用JSON解析错误

时间:2014-03-27 09:02:33

标签: java php android json

我设法解决除JSONException错误之外的所有问题。我知道我的代码效率不高,可以通过使用asynctask等进行改进,但现在解决这个错误是我的优先级列表,所以请帮我解决这个问题。

我正在分享所有必需的代码和详细信息。

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:

 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:

<?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的:

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)

2 个答案:

答案 0 :(得分:0)

问题是你的&#34; JSON&#34; -String,正如它在Logcat中所说的那样。

您的&#34; json&#34; -string包含HTML-Tags,例如 br font size =&#39; 1&#39; 等< / p>

只有Logcat中String-Result的最后一行是有效的JSON。但是你试图解析整个字符串,而不仅仅是JSON。

<强> //修改

发生此错误 - 如 D_Vaibhavツ告诉 - 因为您的Web服务器首先返回错误:

  

注意:未定义的索引:第22行的C:\ wamp \ www \ MSRIT_Student_Info_Handles \ MSRIT_retrieve_particular_attendance.php中的注释

答案 1 :(得分:0)

当您的Web服务没有返回有效的JSON时,会发生JSON解析错误。在这种情况下,您的服务器返回HTML内容和JSON。所以你在网络服务方面有问题。

查看您的PHP代码 您在MSRIT_retrieve_particular_attendance.php

的第22行有错误

注意:

中的Undefined index: comments 第22行

C:\ wamp \ www \ MSRIT_Student_Info_Handles \ MSRIT_retrieve_particular_attendance.php

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

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

您的结果未返回名为&#34;评论&#34;

的列

您可以签入该PHP代码,我建议您关闭PHP方面的警告,因为它可能不会影响您的最终结果

Here is the link会帮助你做到这一点