mySQL to PHP to JSON: String Cannot be Converted to JSONObject - java

I am trying to get data from a mySQL database using PHP. This is my fist real attempt of getting data remotely & using JSON. The php file is functioning correctly because it outputs in a browser as a JSON string and i valadated it using JSONLint. So, I am not sure what I have wrong here. Any help would be greatly appreciated
This is what LogCat is throwing:
Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
threadid=9: thread exiting with uncaught exception (group=0x401dce20)
FATAL EXCEPTION: Thread-10
java.lang.NullPointerException
at com.andaero.test.JSON.JSONMain$1.run(JSONMain.java:39)
at java.lang.Thread.run(Thread.java:1020)
UPDATE: I removed the echo method from the php file as Mark requested. I think it has to do with "JSONArray a = json.getJSONArray("regulatory"). I also tried everyone else's approach with no prevail.
Here are the classes:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "regulatory";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The List Activity:
public class JSONMain extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
new Thread(new Runnable() {
public void run() {
JSONObject json = JSONfunctions
.getJSONfromURL("http://192.168.1.34/andaero/regulatory_list_ASC.php");
try {
JSONArray a = json.getJSONArray("regulatory");
for (int i = 0; i < a.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = a.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("label", e.getString("label"));
map.put("title", e.getString("title"));
map.put("caption", e.getString("description"));
map.put("dummy", e.getString("gotoURL"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}).start();
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.list_item, new String[] { "label", "title", "caption",
"dummy" }, new int[] { R.id.label, R.id.listTitle,
R.id.caption, R.id.dummy });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Toast.makeText(JSONMain.this,
"ID '" + o.get("id") + "' was clicked.",
Toast.LENGTH_SHORT).show();
}
});
}
}
The PHP:
<?php
//MySQL Database Connect
include 'andaerologin.php';
mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");
$output = array();
while($row = mysql_fetch_assoc($sql)) {
$output['regulatory'][] = $row;
}
exit (json_encode($output));
mysql_close();
?>

Try changing your PHP to this:
$output = new stdClass();
$output->regulatory = array();
while($row = mysql_fetch_assoc($sql)) {
$output->regulatory[] = $row;
}
header('Content-type: application/json');
echo (json_encode($output));

Try changing your PHP script to this:
<?php
// Hide errors to prevent data corruption
ini_set('display_errors', 0);
// For debugging, uncomment these lines to show errors
//ini_set('display_errors', 0);
//error_reporting(E_ALL);
//MySQL Database Connect
require 'andaerologin.php';
if (!mysql_select_db("andaero")) {
// Use trigger_error() so you can find out in the server logs if something
// goes wrong
trigger_error('Unable to select MySQL database');
header('HTTP/1.1 500 Internal Server Error');
exit;
}
$query = "SELECT *
FROM regulatory_list";
if (!$result = mysql_query($query)) {
trigger_error('MySQL error: '.mysql_error());
header('HTTP/1.1 500 Internal Server Error');
exit;
}
if (!mysql_num_rows($query)) {
trigger_error('MySQL returned no results');
header('HTTP/1.1 500 Internal Server Error');
exit;
}
// Build an array of the results
$output = array();
while ($row = mysql_fetch_assoc($result)) {
$output[] = $row;
}
// Send the results back as JSON
exit(json_encode($output));
// Closing the database connection happens implicitly at the end of the
// script. Also, you don't need to have a closing PHP tag at the end of the
// file and omitting it is a good habit to get into as it can avoid problems

In your PHP code, change
json_encode($output)
to
json_encode($output, JSON_FORCE_OBJECT)
The JSON_FORCE_OBJECT option requires PHP version >= 5.3.0
Your problem seems to be at jArray = new JSONObject(result);
I don't know what the JSONObject constructor expects, but I know you are sending a JSON array to it, not an object.

Do you really need all those fields in the table?
I once did the same, SELECT * FROM table, and json_encode() all the results. jQuery seemed to have a problem reading the data even though the JSON result looks perfectly fine.
So I tried to limit the data and send only the required fields to the browser by SELECT field1, field2 FROM table, instead of all the fields.
Then everything worked fine. I could only suspect that there's a limit to the amount of JSON data jQuery can parse.
I know you aren't using jQuery but I'm just leaving my experience here just in case.

Related

Get Json data from the Url below(Url returns json data)

This is the URL which returns me the json object Link.
Now I need to get the json data to my code. When I try to access the link I get the html script. How do I get the json data from the above URL to my code. Here is my code.
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new
`ProgressDialog(MainActivity.this);`
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select1 = "http://andpermission.byethost5.com/PermissionList.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select1);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
//Toast.makeText(MainActivity.this, "Please Try Again", Toast.LENGTH_LONG).show();
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String db_detail="";
if(et.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
}
//text_1.append(id+"\t\t"+name+"\t\t"+password+"\t\t"+"\n");
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Using string builder I append the content and I find only the java script and I don't find the json data. How to I get the json data from the above URL.
In string "Result" in my code I get the below output.
<html>
<body>
<script type="text/javascript" src="/aes.js"></script>
<script>
function toNumbers(d) {
var e = [];
d.replace(/(..)/g, function(d) {
e.push(parseInt(d, 16))
});
return e
}
function toHex() {
for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
return e.toLowerCase()
}
var a = toNumbers("f655ba9d09a112d4968c63579db590b4"),
b = toNumbers("98344c2eee86c3994890592585b49f80"),
c = toNumbers("b8eeb5e790c4a5395d01cde6b8230fdd");
document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
location.href = "http://andpermission.byethost5.com/PermissionList.php?ckattempt=1";
</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
How do I get only the json data from the URL instead the java script.
Try the full URL: http://andpermission.byethost5.com/PermissionList.php?ckattempt=1.
And also make sure you are using GET instead of POST, because that's what the URL refers to.
Here a good example: http://www.learn2crack.com/2013/10/android-json-parsing-url-example.html
On the other hand, there are some libraries like Aquery, Okhttp and Volley, that do this job very good.

Android - Display data from MySQL

I'm very new to Android and I'm currently making an application wherein the user can enter and ID number once (that serves as a login) and he can use access the rest of the features of the app.
I'm currently stuck in the displaying of a data from the MySQL server. Using the ID that the user entered (which is unique and only the user's identificaton), I can display the information with of the user (through TextView or something).
This is my code so far:
public class MainActivity3Activity extends Activity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
TextView tv;
TextView tv2;
String get;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
tv = (TextView)findViewById(R.id.tv);
tv2 = (TextView)findViewById(R.id.tv2);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://usamobileapp.pe.hu/webservice/student_info.php");
SharedPreferences preferences = getSharedPreferences("rfid", Context.MODE_PRIVATE);
if(preferences.contains("rfid")){
get = preferences.getString("rfid", null);
}
}
So my question what do I do from here? I'm quite familiar about httpost but I'm wondering how do I display the user information using the previously entered ID during the login? I heard things like JSON parsing but I'm not quite sure on how to use it.
How do I get to display the information of the user matching the ID he entered? How to diplay using a TextView?
Thanks for the help.
PS. Please disregard the webview there. I only used it as a sample if my app really us connected to my php.
1) make a restful API on your server
2) receive API elements on your client (android), i suggest retrofit, its too easy
3) display your data! otto will help :)
want more? more ,
it might seem hard, but if you study for a few days you'll learn it.
To implement a login / registration system using MySql you need a server-side API, for example in PHP to manipulate the database.
You need something like that on the server side:
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
And the function that queries the database:
public function getUserByEmailAndPassword($username, $password) {
$query = $this->dbh->prepare("SELECT * FROM users2 WHERE username = :username");
$query->bindParam(':username', $username);
$result = $query->execute();
// check for results
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_ASSOC);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
The android 'calls' the php scripts:
private static String login_tag = "login";
public void loginUser(String username, String password) throws ExecutionException, InterruptedException {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
jsonParser = new DbHandler(activity, this, params).execute();
}
And here is the DbHandler:
public DbHandler1(Activity activity, MyCallback dbIntf, List<NameValuePair> params) {
this.activity = activity;
intf = dbIntf;
this.params = params;
}
public JSONObject makeHttpRequest() {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(MainActivity.baseUrl);
//If database contains greek characters instantiate with UTF-8 Encoding
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (HttpHostConnectException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, R.string.connection_error, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
try {
//If database contains greek characters instantiate with UTF-8 Encoding
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 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 JSON String
return jObj;
}
#Override
protected JSONObject doInBackground(Void... params) {
jObj = makeHttpRequest();
return jObj;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
try {
intf.onRemoteCallComplete(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
So the php scripts 'catches' the tag and if the user exists it returns a JSON response to the device. For example:
{
"tag": "login",
"success": 1,
"error": 0,
}
The data transfered from the MySql server must be JSON encoded.
On the android device you must read the JSON Response and act accordingly.
Take a look here for more details.
login / registration system
json parsing
you need perform network operations on a separate thread from the UI.
reade aboute rest Google I/O 2010 - Developing Android REST client application
documentation
in the client, for rest api i like use retrofit + gsongroundy
or php, very easy create rest api using slim framework ─ How to create REST API for Android app using PHP, Slim and MySQL

how to connect android to mysql?

Please help me , I am trying to connect my android app to mysql database in localhost through connection in php and json array, but i cant figure out what is the problem , i cant view the data from database.
Here is my files.
Connection.php
<?php
$db_con = mysqli_connect('localhost', 'root', '', 'android') or die ("connection error");;
$query = "SELECT * FROM product";
$results = mysqli_query($db_con, $query) or die ("query error");;
while($row = mysqli_fetch_assoc($results)){
$output[]=$row;
}
echo json_encode($output);
?>
and this the android java "MainActivity.java" :
public class MainActivity extends ActionBarActivity {
TextView viewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewItem = (TextView) findViewById(R.id.itemView);
// Button btnViewItems = (Button) findViewById(R.id.btnViewItems);
getData();
}
public void getData() {
String results = "";
InputStream isr = null;
// Http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2:8080/android/Connection.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
Log.e("log-tag", "Error in http connection" + e.toString());
viewItem.setText("Cannot connect to database");
}
// Converting response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
results = sb.toString();
} catch (Exception e) {
Log.e("log-tag", "Error Converting string" + e.toString());
viewItem.setText("Cannot convert string");
}
// prase jason data
try {
String s = "";
JSONArray jArray = new JSONArray(results);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jOb = jArray.getJSONObject(i);
s = s + jOb.getString("id") + " || " + jOb.getString("name")
+ " || " + jOb.getString("cost") + "\n\n";
}
viewItem.setText(s);
} catch (Exception e) {
Log.e("log-tag", "prasing json data" + e.toString());
viewItem.setText("cannot prase json data");
}
}
}
and the out keep saying : "cannot prase json data".
here is the log error :
E/log-tag(1904): Error in http connectionandroid.os.NetworkOnMainThreadException
E/log-tag(1904): Error Converting stringjava.lang.NullPointerException: lock == null
E/log-tag(1904): prasing json dataorg.json.JSONException: End of input at character 0 of
thanks
You need to run HTTP requests on different thread instead on main thread. Android API does not allow running HTTP requests on main thread. Try using Runnable() to run http request asynchronously on separate thread.

JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject

Guys can you help me a little bit, Im getting this error:
"JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject"
When I'm parsing the data here is my code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
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 JSON String
return jObj;
}
}
Here is the code where I'm instantiating the Parser:
private void fillSpinnerCabTypes() {
List<String> cabTypesSpinner = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
JSONObject cabTypesObject = jsonParser.getJSONFromUrl(urlTypeCabs);
try{
TypesArray = cabTypesObject.getJSONArray(TAG_TYPES);
for(int i = 0; i < TypesArray.length(); i++){
JSONObject c = TypesArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
cabTypesSpinner.add(name);
}
}catch(Exception e ){
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cabTypesSpinner);
final Spinner spnCabTypes = (Spinner)findViewById(R.id.spnTypeOfCab);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spnCabTypes.setAdapter(adapter);
}
I'm really stuck with this. I'm populating the spinner from a database in a backend on Django in the server.
This is my JSON data
{"Types": [{"name": "Normal"}, {"name": "Discapacitados"}, {"name": "Buseta"}]}
This issue comes from the server.
The URL you're requesting, send you back data but not in the JSON format.
The Exception you get is telling you that the String the server send you back starts with:
<!DOCTYPE
This can be:
A simple webpage (instead of raw JSON). It correspond to the first XML tag of a web page (source)
An error page generated by the server, and printed in HTML
To debug this further, simply print the content of your json variable in the logcat:
Log.d("Debug", json.toString());
jObj = new JSONObject(json);
This problem came in my code also.and solution was different.It occured due to spelling mistake of webservice.
Solution 1:
for example real the url is
http://example.com/directory/file.php
and i had used
http://example.com/directory/file1.php
Solution 2:
use loopj library .it exactly gives you the explained error.
AsyncHttpClient client = new AsyncHttpClient();
client.post(str , localRequestParams, new AsyncHttpResponseHandler() {
#Override
public void onFinish() {
super.onFinish();
Log.i("onFinish","onFinish");
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i("onSuccess","onSuccess");
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i("onFailure","onFailure");
}
});

App doesn't retrieve JSON data from PHP webservice. Webservice works fine

My app doesn't seem to pull the JSON data from PHP webservice properly.
Visiting the webservice's function to get all data records from database produces JSON properly, but my app can't grab that data and seems to end up with NullPointerException.
LogCat issues me this:
Update:
Noticed this error in yellow that happens before the below errors:
W/System.err(835): org.apache.http.conn.HttpHostConnectException:
Connection to http:// localhost refused
If I can't connect to the webservice on my localhost then I'm not getting the JSON to my app. But why would it refuse connection to localhost?
W/System.err(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:113)
W/System.err(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1)
E/AndroidRuntime(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:116)
E/AndroidRuntime(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1)
E/WindowManager(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.onPreExecute(MainActivity.java:103)
Line 113: JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
Line 116: Log.d("All Cars: ", json.toString());
MainActivity
package com.example.myfirstproject;
//imports
public class MainActivity extends ListActivity implements OnItemClickListener {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> carsList;
// url to get all products list
private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CARS = "cars";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray cars = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
carsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllcars().execute();
// Get listview
ListView lv = getListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllcars extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading cars. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products 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_cars, "GET", params);
// Check your log cat for JSON reponse
Log.d("All cars: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
cars = json.getJSONArray(TAG_CARS);
// looping through All Products
for (int i = 0; i < cars.length(); i++) {
JSONObject c = cars.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
carsList.add(map);
}
} else {
// no products found
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("No cars found");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
} 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 products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, carsList,
android.R.id.list, new String[] {TAG_NAME},
new int[] { R.id.title });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
EDIT
JSONParser:
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 method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "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 == "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();
} 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", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I think your problem may be that you never put anything in params. It's just an empty List.
Well if you are getting a null pointer exception on this line
JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
then 1 or more of them things must be null. The jParser is instantiated, the url string is also, the params is as a list however there is nothing in the list. Have a look inside the jParser and see what is happening with that list of params. Do you need them? Does it need them?
EDIT
So the jParser is converting your list(which is empty) to a string with string builder. Which is returning an empty sting.
so your url when it is sent to your server looks like this
http://localhost/webservice/get_all_cars.php?
So the normal url but with a question mark on it. Is that correct?
It would make sense to log the statuscode and status reason from your httpresponse so you can see what the server is responsing you would do that like so...
Log.d("Class Name", "Status code: " + httpResponse.getStatusLine().getStatusCode() + " Status Phrase: " + httpResponse.getStatusLine().getReasonPhrase());
EDIT
The url is set to "localhost" so I presume it is looking within the device rather than at your server. Put in the ip of your server instead
Problem was here:
private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";
Can't use localhost because the emulated phone itself is localhost/127.0.0.1
You need to change localhost to 10.0.2.2:
private static String url_all_cars = "http://10.0.2.2/webservice/get_all_cars.php";

Categories