无法在android中获取json数组

时间:2014-03-23 09:18:06

标签: android json arrays

我正在尝试将php脚本中的json数据导入我的Android应用程序,但getJSONFromUrl(URL);不起作用。以下是我的代码..

主要活动类

public class MainActivity extends Activity {
private static final String URL = "http://10.0.2.2:1234/main.php/";
private JSONArray words = null;
private ArrayList<String> wordsList;
private static final String TAG_WORDS = "words";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    wordsList = new ArrayList<String>();
    updateJSONdata();
    Toast.makeText(getApplicationContext(), wordsList.toString(),
            Toast.LENGTH_LONG).show();
}

public void updateJSONdata() {      
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.getJSONFromUrl(URL);// this is where the error is
    try {
        words = json.getJSONArray(TAG_WORDS);
        for (int i = 0; i < words.length(); i++) {
            JSONObject c = words.getJSONObject(i);
            String title = c.toString();
            wordsList.add(title);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

JSONParser Class

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = ""; 
public JSONParser() {
}    

public JSONObject getJSONFromUrl(final String url) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        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();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }       
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }       
    return jObj;
}   
}

来自main.php的JSON数据

{"words":[["bra"],["fie"]],"success":1}  

PHP代码:

<?php
$username = "root"; 
$password = ""; 
$host = "localhost"; 
$dbname = "dictionary_db"; 
$con=mysql_connect($host, $username, $password);
if(!$con) die('could not connect'. mysql_error());
mysql_select_db($dbname,$con);
$query = "SELECT word from local_words" ;
$result=mysql_query($query) or die(mysql_error());
$count = 0;
$wordsArr = array();
$response["words"] = array();
while ($row = mysql_fetch_row($result)){
    array_push($wordsArr,$row);
    $count++;
}
$response["success"] = 1;   
$response["words"] = $wordsArr;
echo json_encode($response);
?>

LogCat中的错误消息:

Buffer Error : Error converting result.lang.NullPointerException: lock == null
JSON Parser : Error parsing data org.json.JSONException: End of input at character 0 of

1 个答案:

答案 0 :(得分:1)

{"success":1,"words":[word1,word2]}不是有效的JSON。有效的JSON应该如下所示

{"success":1,"words":["word1","word2"]}

如果正确发送JSON,请检查服务器响应。如果您添加更多信息以及服务器返回JSON的确切程度,将会有所帮助。

<强>更新

您有两个错误 -

  1. Buffer Error - lock == null。原因 - 您将null值传递给InputStreamReader,即 httpEntity.getContent(); 为空。

  2. JSON Error - 解析器试图解析一个空字符串,即字符0

  3. 不支持HTTP POST方法或服务器存在其他错误。您需要检查httpResponse的状态并记录它。这将解决问题

    另一次更新

    您收到Socket异常 - 权限被拒绝,此处的问题是您尚未向应用添加Internet权限。转到您的清单,然后添加以下权限

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

    尝试一下,让我知道它是否有帮助。