2012-07-25 6 views
0

이에 도움이 필요 JSON으로 안드로이드 = (연령이에 갇혀! 내 코드가 표시되어있다. 안드로이드 오류 구문 분석 문자열은

public class AllUsersActivity extends ListActivity { 

// Progress Dialog 
private ProgressDialog pDialog; 

// Creating JSON Parser object 
JSONParser jParser = new JSONParser(); 

ArrayList<HashMap<String, String>> usersList; 

// url to get all users list 
private static String url_all_users = "http://10.0.2.2/android_connect/get_all_users.php"; 

// JSON Node names 
private static final String TAG_SUCCESS = "success"; 
private static final String TAG_USERS = "users"; 
private static final String TAG_UID = "UserID"; 
private static final String TAG_FIRSTNAME = "FirstName"; 

// users JSONArray 
JSONArray users = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.all_users); 

    // Hashmap for ListView 
    usersList = new ArrayList<HashMap<String, String>>(); 

    // Loading users in Background Thread 
    new LoadAllusers().execute(); 

    // Get listview 
    ListView lv = getListView(); 

    // on seleting single product 
    // launching Edit Product Screen 
    lv.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
      // getting values from selected ListItem 
      String uid = ((TextView) view.findViewById(R.id.uid)).getText() 
        .toString(); 

      // Starting new intent 
      Intent in = new Intent(getApplicationContext(), 
        UserDetailsActivity.class); 
      // sending uid to next activity 
      in.putExtra(TAG_UID, uid); 

      // starting new activity and expecting some response back 
      startActivityForResult(in, 100); 
     } 
    }); 

} 

// Response from Edit Product Activity 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    // if result code 100 
    if (resultCode == 100) { 
     // if result code 100 is received 
     // means user edited/deleted product 
     // reload this screen again 
     Intent intent = getIntent(); 
     finish(); 
     startActivity(intent); 
    } 

} 

/** 
* Background Async Task to Load all product by making HTTP Request 
* */ 
class LoadAllusers extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(AllUsersActivity.this); 
     pDialog.setMessage("Loading users. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    /** 
    * getting All users from url 
    * */ 
    protected String doInBackground(String... args) { 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // getting JSON string from URL 
     JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params); 

     // Check your log cat for JSON reponse 
     Log.d("All users: ", json.toString()); 

     try { 
      // Checking for SUCCESS TAG 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // users found 
       // Getting Array of users 
       users = json.getJSONArray(TAG_USERS); 

       // looping through All users 
       for (int i = 0; i < users.length(); i++) { 
        JSONObject c = users.getJSONObject(i); 

        // Storing each json item in variable 
        String id = c.getString(TAG_UID); 
        String name = c.getString(TAG_FIRSTNAME); 

        // creating new HashMap 
        HashMap<String, String> map = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        map.put(TAG_UID, id); 
        map.put(TAG_FIRSTNAME, name); 

        // adding HashList to ArrayList 
        usersList.add(map); 
       } 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after getting all users 
     pDialog.dismiss(); 
     // updating UI from Background Thread 
     runOnUiThread(new Runnable() { 
      public void run() { 
       /** 
       * Updating parsed JSON data into ListView 
       * */ 
       ListAdapter adapter = new SimpleAdapter(
         AllUsersActivity.this, usersList, 
         R.layout.list_item, new String[] { TAG_UID, 
           TAG_FIRSTNAME}, 
         new int[] { R.id.uid, R.id.name }); 
       // updating listview 
       setListAdapter(adapter); 
      } 
     }); 

    } 

} 

사람이 좀 도와 주시겠습니까

! 내가지고있어 오류가 입니다 오류 구문 분석 데이터 Org.json.JSONException : 값은 JSON 문자열

Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1} 
에게

을 Heres 된 JSONObject로 변환 할 수 없습니다 0

JSON 파서 클래스에 오류가 있습니까?

EDIT : 위의 배열을 출력하는 PHP 스크립트 코드. 누구든지 json 문자열 전에 단어 배열을 출력하는 PHP 스크립트가 무엇이 잘못되었는지 말해 줄 수 있습니까? 문제를 일으켜서 미안 해요. 나는 코딩에 익숙하지 않다. 온라인 자습서를 따라 왔지만 며칠 동안 여기에 붙어 있습니다.

<?php 
/* 
* Following code will list all the Users 
*/ 
// array for JSON response 
$response = array(); 
// include db connect class 
require_once __DIR__ . '/db_connect.php'; 
// connecting to db 
$db = new DB_CONNECT(); 
// get all Users from Users table 
$result = mysql_query("SELECT * FROM Users") or die(mysql_error()); 
// check for empty result 
if (mysql_num_rows($result) > 0) { 
// looping through all results 
// Users node 
$response["Users"] = array(); 

while ($row = mysql_fetch_array($result)) { 
    // temp user array 
    $user[] = array(); 
    $user["UserID"] = $row["UserID"]; 
    $user["FirstName"] = $row["FirstName"]; 
    $user["Email"] = $row["Email"]; 
    $user["Password"] = $row["Password"]; 

    // push single User into final response array 
    array_push($response["Users"], $user); 
} 
// success 
$response["success"] = 1; 
echo $response; 

// echoing JSON response 
echo json_encode($response); 
} 
else { 
// no Users found 
$response["success"] = 0; 
$response["message"] = "No Users found"; 

// echo no users JSON 
echo json_encode($response); 
} 
?> 
+2

JSON 객체의 전면에서 "Array"를 제거하려고하면 JSON 객체는 {for 및 object 또는 [배열의 경우]로 시작해야합니다. – Dampsquid

+0

나는 항상 키의 대소 문자도 일치 시키려고합니다. intance는 "사용자"를 "사용자"로 변경하여 구문 분석 한 JSON 문자열과 일치시킵니다. –

답변

0

오류에서 알 수 있듯이, 당신의 JSON 문자열이 유효한 JSON 개체를 나타내지 않습니다.

는 (처음에 Array없이)이 같은 시도 :

{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1} 

당신은 여기 JSONString의 유효성을 확인할 수 있습니다 http://jsonlint.com/

1

사용 GSON 라이브러리 대신, 공식 구글과 같이 작동 매력. 아니 HashMaps 등, 즉각적인 개체.

보십시오 here.