2014-03-27 63 views
0

我設法解決除JSONException錯誤之外的所有問題。我知道我的代碼效率不高,可以通過使用asynctask等來改進,但現在解決這個錯誤是我的優先級列表之一,所以請幫我解決這個問題。Android考勤應用JSON解析錯誤

我在分享所有必需的代碼和詳細信息。

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) 
+5

請學會閱讀的logcat ....'錯誤數據進行解析org.json.JSONException:值
'元素是'HTML'而不是'JSON'。修復你的PHP代碼,使其返回一個'JSON'字符串,而不是'HTML'中包含的'JSON'。 – Squonk

+1

嘿,我喜歡閱讀大量代碼,但是你忘了提供一個問題 – Anthony

+0

在瀏覽器中運行你的URL,首先看到響應。 –

回答

0

問題是你的 「JSON」 -STRING,因爲它在logcat中講述。

你的「JSON」 -string包含HTML標籤,就像BR字體大小=「1」

只有在你的logcat的字符串,結果的最後一行是有效的JSON。但是你試圖解析整個字符串,而不僅僅是JSON。

//編輯

此錯誤occures - 像D_Vaibhavツ說 - 因爲你的Web服務器返回錯誤第一:

公告:未定義的索引:在C註釋:\ WAMP \ www \ MSRIT_Student_Info_Handles \ MSRIT_retrieve_particular_attendance.php on line 22

0

JSON解析錯誤發生在您的Web服務時不返回有效的JSON。在這種情況下,您的服務器將返回HTML內容以及JSON。所以你在Web服務方面出了問題。

通過看你的PHP代碼 你在你的MSRIT_retrieve_particular_attendance.php

通知必須在22行錯誤:Undefined index: comments

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"]; 

你的結果沒有返回名爲「意見」

你可以在PHP代碼檢查,我建議你從你的PHP端關閉警告,也不會影響柱你的最終結果

Here is the link,這將幫助你做到這一點