2016-03-25 46 views
-1

我通過Toast得到異常錯誤,如「Error..2 JSONException:java.lang.String類型的值不能轉換爲JSONObject「。 請提出解決方案!我正在做一個列表視圖,它從我的數據庫中檢索系的名字並將它顯示在列表視圖中

IT_Faculty.java

package com.roadraz.vcademy1; 

    import android.app.ListActivity; 
    import android.os.AsyncTask; 
    import android.os.Bundle; 
    import android.support.design.widget.FloatingActionButton; 
    import android.support.design.widget.Snackbar; 
    import android.support.v7.app.AppCompatActivity; 
    import android.support.v7.widget.Toolbar; 
    import android.view.View; 
    import android.widget.AdapterView; 
    import android.widget.ArrayAdapter; 
    import android.widget.ListAdapter; 
    import android.widget.ListView; 
    import android.widget.SimpleAdapter; 
    import android.widget.Toast; 

    import org.apache.http.HttpResponse; 
    import org.apache.http.client.ClientProtocolException; 
    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 java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStream; 
    import java.io.InputStreamReader; 
    import java.util.ArrayList; 
    import java.util.HashMap; 
    import java.util.List; 
    import java.util.Map; 

    public class IT_Faculty extends AppCompatActivity { 

     private String jsonResult; 
     private String url = "<have added my server address>"; 
     private ListView listView; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_it__faculty); 
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
      setSupportActionBar(toolbar); 
      listView = (ListView) findViewById(R.id.faculty_listView); 
      accessWebService(); 
     } 

     private class JsonReadTask extends AsyncTask<String, Void, String> { 

      @Override 
      protected String doInBackground(String... params) { 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost(params[0]); 
       try { 
        HttpResponse response = httpclient.execute(httppost); 
        jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); 
       } catch (ClientProtocolException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       return null; 
      } 

      private StringBuilder inputStreamToString(InputStream is) { 
       String rLine = ""; 
       StringBuilder answer = new StringBuilder(); 
       BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
       try { 
        while ((rLine = rd.readLine()) != null) { 
         answer.append(rLine); 
        } 
       } catch (IOException e) { 
        //e.printStackTrace(); 
        Toast.makeText(IT_Faculty.this, "Error...1" + e.toString(), Toast.LENGTH_LONG).show(); 
       } 
       return answer; 
      } 

      @Override 
      protected void onPostExecute(String s) { 
       ListDrawer(); 
      } 
     }//end async task 

     public void accessWebService() { 
      JsonReadTask task = new JsonReadTask(); 
      task.execute(new String[]{url}); 
     } 

     //build hash set for list view 
     public void ListDrawer() { 
      List<Map<String, String>> facultyList = new ArrayList<Map<String, String>>(); 
      try { 
       JSONObject jsonResponse = new JSONObject(jsonResult); 
       JSONArray jsonMainNode = jsonResponse.optJSONArray("asdb"); 

       for (int i = 0; i < jsonMainNode.length(); i++) { 
        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 
        String name = jsonChildNode.optString("name"); 
        String number = jsonChildNode.optString("roll_no"); 
        String outPut = name + "-" + number; 
        facultyList.add(createFaculty("faculties",outPut)); 
       } 

      } catch (JSONException e) { 
       Toast.makeText(IT_Faculty.this, "Error...2" + e.toString(), Toast.LENGTH_LONG).show(); 
      } 
      SimpleAdapter simpleAdapter= new SimpleAdapter(IT_Faculty.this,facultyList, 
        android.R.layout.simple_list_item_1,new String[]{"faculties"},new int[]{android.R.id.text1}); 
      listView.setAdapter(simpleAdapter); 
      Toast.makeText(IT_Faculty.this, "c", Toast.LENGTH_SHORT).show(); 
     } 
     private HashMap<String,String> createFaculty(String name,String roll_no){ 
      HashMap<String,String> facultyNameNo=new HashMap<String,String>(); 
      facultyNameNo.put(name,roll_no); 
      return facultyNameNo; 
     } 
    } 

it__faculty.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" 
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:orientation="vertical" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:showIn="@layout/activity_it__faculty" tools:context="com.roadraz.vcademy1.IT_Faculty"> 

    <ListView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/faculty_listView"> 
    </ListView> 
</LinearLayout> 

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.roadraz.vcademy1" > 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".FirstPage" 
      android:label="V-Cademy" 
      android:theme="@style/AppTheme.NoActionBar" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <activity 
      android:name=".IT_Faculty" 
      android:label="@string/title_activity_it__faculty" 
      android:theme="@style/AppTheme.NoActionBar" > 
     </activity> 
    </application> 

</manifest> 

faculty_fetch.php

<?php 
$host="localhost"; 
$username="myusername"; 
$password="mypassword"; 
$db_name="asdb";  
$con=mysql_connect("$host","$username","$password"); 
mysql_select_db=("$db_name"); 
$sql="select * from asdb where class='Faculty'"; 
$result=mysql_query($sql); 
$json=array(); 

if(mysql_num_rows($result)){ 
while($row=mysql_fetch_assoc($result)){ 
$json['asdb']['sr_no']=$row['sr_no'] 
$json['asdb']['name']=$row['name'] 
$json['asdb']['email']=$row['email'] 
$json['asdb']['roll_no']=$row['roll_no'] 
$json['asdb']['class']=$row['class'] 
$json['asdb']['phone']=$row['phone'] 
$json['asdb']['password']=$row['password']; 
} 
} 
mysql_close($con); 
echo json_encode($json); 
?> 

下面是Android的監視器

03-25 01:43:08.802 28804-28804/? I/art: Not late-enabling -Xcheck:jni (already on) 
03-25 01:43:08.802 28804-28804/? I/art: Late-enabling JIT 
03-25 01:43:08.810 28804-28804/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000 
03-25 01:43:08.922 28804-28804/com.roadraz.vcademy1 W/System: ClassLoader referenced unknown path: /data/app/com.roadraz.vcademy1-1/lib/x86 
03-25 01:43:09.445 28804-28811/com.roadraz.vcademy1 W/art: Suspending all threads took: 5.088ms 
03-25 01:43:09.839 28804-28837/com.roadraz.vcademy1 D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true 
03-25 01:43:09.859 28804-28804/com.roadraz.vcademy1 D/: HostConnection::get() New Host Connection established 0xab8027b0, tid 28804 
03-25 01:43:10.115 28804-28811/com.roadraz.vcademy1 W/art: Suspending all threads took: 164.743ms 
03-25 01:43:10.269 28804-28837/com.roadraz.vcademy1 I/OpenGLRenderer: Initialized EGL, version 1.4 
03-25 01:43:10.316 28804-28837/com.roadraz.vcademy1 W/EGL_emulation: eglSurfaceAttrib not implemented 
03-25 01:43:10.316 28804-28837/com.roadraz.vcademy1 W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabfbe100, error=EGL_SUCCESS 
03-25 01:43:10.874 28804-28836/com.roadraz.vcademy1 W/MYAPP: [email protected] 
03-25 01:43:10.875 28804-28836/com.roadraz.vcademy1 W/MYAPP: [email protected] 
03-25 01:43:11.012 28804-28837/com.roadraz.vcademy1 W/EGL_emulation: eglSurfaceAttrib not implemented 
03-25 01:43:11.012 28804-28837/com.roadraz.vcademy1 W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7b4460, error=EGL_SUCCESS 
03-25 01:43:14.417 28804-28837/com.roadraz.vcademy1 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4057390 
03-25 01:43:14.491 28804-28837/com.roadraz.vcademy1 W/EGL_emulation: eglSurfaceAttrib not implemented 
03-25 01:43:14.491 28804-28837/com.roadraz.vcademy1 W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7cc3a0, error=EGL_SUCCESS 
03-25 01:43:16.438 28804-28837/com.roadraz.vcademy1 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4053dc0 
+0

進行調試; JsonObject jo = s.getJSONObject(); ' –

+0

我已經上傳了Android監視器......請看看並幫助我! –

+0

您的ListDrawer()方法中出現錯誤。在catch-Block中寫入e.printStackTrace(); 這樣你就可以在你的例外中獲得更多細節。 我可以看看你的json嗎? –

回答

0

嘗試從沒有你amdroid顯示器 看到這可能是因爲你做了某事像 `一個String行更改爲以下

//build hash set for list view 
    public void ListDrawer() { 
     List<Map<String, String>> facultyList = new ArrayList<Map<String, String>>(); 
     try { 
      JSONObject jsonResponse = new JSONObject(jsonResult); 
      JSONArray jsonMainNode = jsonResponse.optJSONArray("asdb"); 

      for (int i = 0; i < jsonMainNode.length(); i++) { 
       JSONObject jsonChildNode = new JSONObject(jsonMainNode.getString(i)); 
       String name = jsonChildNode.optString("name"); 
       String number = jsonChildNode.optString("roll_no"); 
       String outPut = name + "-" + number; 
       facultyList.add(createFaculty("faculties",outPut)); 
      } 

     } catch (JSONException e) { 
      Toast.makeText(IT_Faculty.this, "Error...2" + e.toString(), Toast.LENGTH_LONG).show(); 
     } 
     SimpleAdapter simpleAdapter= new SimpleAdapter(IT_Faculty.this,facultyList, 
       android.R.layout.simple_list_item_1,new String[]{"faculties"},new int[]{android.R.id.text1}); 
     listView.setAdapter(simpleAdapter); 
     Toast.makeText(IT_Faculty.this, "c", Toast.LENGTH_SHORT).show(); 
    } 
+0

同樣的錯誤出現.. –

相關問題