I'm trying to get json data from a php script into my android application but the getJSONFromUrl(URL); doesn't work. Below is my code..
MAINACTIVITY CLASS
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;
}
}
JSON data from main.php
{"words":[["bra"],["fie"]],"success":1}
PHP code:
<?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);
?>
Error message in 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