I'm new to java and PHP, could someone please help my database only shows 0's ...
java code:
public class postData extends Activity {
//Progress Dialog
private ProgressDialog pDialog;
//JSONParser jsonParser = new JSONParser();
//url to update coordinates
private static String url_update_coordinates = "http://www.myurl.com";
//JSON Node names
private static final String TAG_SUCCESS = "Success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.post_coords);
final Context ctx = this;
//Create button
Button btnUploadCoordinates = (Button) findViewById(R.id.button5);
//Button click event
btnUploadCoordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// updating coordinates on background thread
new UploadCoordinates(ctx).execute();
}
});
}
//Background Async Task to upload coordinates
class UploadCoordinates extends AsyncTask <String, String, String> {
// Before starting background thread Show Progress Dialog
private Context ctx;
public UploadCoordinates(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(postData.this);
pDialog.setMessage("Uploading Coordinates...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
//Creating Coordinates
#Override
protected String doInBackground(String... params) {
JSONArray json = new JSONArray();
MySQLite dbhelper = new MySQLite(ctx);
Cursor data = dbhelper.getlocations();
while(data.moveToNext()) {
int _id = data.getInt(0);
double latitude = data.getDouble(1);
double longitude = data.getDouble(2);
double altitude = data.getDouble(3);
double speed = data.getDouble(4);
double timestamp = data.getDouble(5);
JSONObject jo = new JSONObject();
try{
jo.put("_id", _id);
jo.put("latitude", latitude);
jo.put("longitude", longitude);
jo.put("altitude", altitude);
jo.put("speed", speed);
jo.put("timestamp", timestamp);
} catch(JSONException e) {
}
json.put(jo);
}
String json_data = json.toString();
// Adding the data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("coords", json_data));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.myurl.com");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Check log for response
Log.d("Create response", json.toString());
return null;
}
// check for success tag
try {
int success = json_data.getInt(TAG_SUCCESS);
GIVING ME PROBLEMS HERE The method getInt(String) is undefined for the type String
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), GPSLoggerService.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//After completion background task Dismiss progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once done
pDialog.dismiss();
}
}
}
php script:
<?php
ini_set('error_reporting', E_ALL); ini_set('display_errors','1');
//include dbconnect class
require_once (__DIR__ . '/db_connect.php');
//connecting to db
$db = new DB_CONNECT();
//decode array
$arr = (isset($_POST['coords']));
$decarr = json_decode($arr, true);
$count = count($decarr);
$values = array(); //hold array values so we do one single insert
$update_values = array(); //holds values for the ON DUPLICATE KEY UPDATE
for ($x=0; $x <$count; $x++)
{
$newrec = $decarr[$x];
$_id = $newrec['_id']; $_id = mysql_real_escape_string($_id);
$latitude = $newrec['latitude']; $_id = mysql_real_escape_string($latitude);
$longitude = $newrec['longitude']; $_id = mysql_real_escape_string($longitude);
$timestamp = $newrec['timestamp']; $_id = mysql_real_escape_string($timestamp);
$altitude = $newrec['altitude']; $_id = mysql_real_escape_string($altitude);
$speed = $newrec['speed']; $_id = mysql_real_escape_string($speed);
//create insert array
$values[] = "('".$_id."','".$latitude."','".$longitude."','".$timestamp."','".$altitude."','".$speed."')";
//For the duplicate updates
$update_values[]=
"latitude=VALUES(latitude), longitude=VALUES(longitude), timestamp=VALUES(timestamp), altitude=VALUES(altitude), speed=VALUES(speed)";
}
//insert records
$sql = "INSERT INTO logs(_id, latitude, longitude, timestamp, altitude, speed)
VALUES ".implode(',', $values)." ON DUPLICATE KEY UPDATE ".implode(',',$update_values);
$result = mysql_query($sql);
?>
Been trying for hours and can't figure out where the problem is, maybe this will be a silly one for many of yous out there.
thank you in advance for all your help.
Regards
V
UPDATE - Not sure if I should do this, but it will be easier as all the code is already here, my error is between blockquote... can't get my head around to see where the problem lyes ... any help appreciated.
The problem is that you use isset function and assign it's return value to $arr variable, and then using it as an array.
You should use this function to determine if a variable is set and is not NULL: it returns true or false.
In your PHP code, instead of lines 10 and 11, try this:
$decarr = isset($_POST['coords']) ? json_decode($_POST['coords'], true) : array();
Related
I have an android activity that reads some items from the web server, everything is alright except the image.
I've done the same with only one item and it worked, but I can't think of anyway to read many items and set their value to imageView.
Is there anyway that allows me to set the image value to the listAdapter after ending them by hashmap?
Any help would be greatly appreciated!
Here is the code:
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(GetAllRecipesActivity.this);
pDialog.setMessage("Loading products. 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>();
params.add(new BasicNameValuePair("category", R_category));
Log.d("R_category: ", R_category);
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_table);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SCB_ID);
String title = c.getString(TAG_TITLE);
String name = c.getString(TAG_NAME);
name= name.substring(1, name.length());
name="http://studentcookbook.comoj.com/android_connect"+name;
Log.d("NAME OF THE URL!",name);
// here i'm starting to set the image value it's all good here
downloadBitma =downloadBitmap(name);
// creating new HashMap
HashMap<String, Object> map=new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_SCB_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_NAME, downloadBitma);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),AddRecipeActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Buffer Error", "Error converting result " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Buffer Error", " Image is not passing to hashmap");
}
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
* */
// here i'm trying to set the image to imageView but it didn't work
// final ImageView imageView = (ImageView) findViewById(R.id.GetAllmg);
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
// imageView.setImageBitmap(downloadBitma); }
// });
ListAdapter adapter = new SimpleAdapter(GetAllRecipesActivity.this, productsList,
R.layout.list_recipe, new String[] { TAG_SCB_ID,TAG_TITLE},
new int[] { R.id.GetAllscbid, R.id.GetAllTitle });
// updating listview
Toast.makeText(GetAllRecipesActivity.this, "onPostExecute", Toast.LENGTH_SHORT).show();
setListAdapter(adapter);
}
});
}
// method for downloading images
private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
return bitmap;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
I recommend Universal Image Loader.
I'm writing an Android application which will occasionally need to download a json string of around 1MB and containing around 1000 elements, and parse each of these into an SQLite database, which I use to populate a ListActivity.
Even though the downloading and parsing isn't something that needs to be done on every interaction with the app (only on first run or when the user chooses to refresh the data), I'm still concerned that the parsing part is taking too long, at around two to three minutes - it seems like an eternity in phone app terms!
I am using this code... :-
public class CustomerAsyncTask extends AsyncTask<String, Integer, String> {
private Context context;
private String url_string;
private String usedMethod;
private String identifier;
List<NameValuePair> parameter;
private boolean runInBackground;
AsynTaskListener listener;
private Bitmap bm = null;
public ProgressDialog pDialog;
public String entityUtil;
int index = 0;
public static int retry = 0;
private String jsonString = "";
private String DialogString = "";
// use for AsyncTask web services-----------------
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground, String DialogString,
List<NameValuePair> parameter, AsynTaskListener callack) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.DialogString = DialogString;
}
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground,
List<NameValuePair> parameter, AsynTaskListener callack, Bitmap bm) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.bm = bm;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (runInBackground)
initProgressDialog(DialogString);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000; // mili second
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
HttpResponse response = null;
if (usedMethod.equals(GlobalConst.POST)) {
HttpPost httppost = new HttpPost(this.url_string);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
// Customer Login MObile
if (identifier.equals("Customer_Login")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_mob",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
// Customer Verify Code
} else if (identifier.equals("Customer_mob_verify")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_verify",
params[0]));
parameter.add(new BasicNameValuePair("cus_mobile",
params[1]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
} else if (identifier.equals("Dashboard")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_id",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
}
response = (HttpResponse) httpClient.execute(httppost);
} else if (usedMethod.equals(GlobalConst.GET)) {
HttpGet httpput = new HttpGet(this.url_string);
httpput.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = (HttpResponse) httpClient.execute(httpput);
}
// Buffer Reader------------------------
InputStream inputStream = null;
String result = null;
try {
HttpEntity entity1 = response.getEntity();
inputStream = entity1.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
jsonString = result;
} catch (ClientProtocolException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (IOException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (Exception e1) {
e1.printStackTrace();
return AsyncResultConst.EXCEPTION;
} finally {
httpClient.getConnectionManager().shutdown();
}
return AsyncResultConst.SUCCESS;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (runInBackground)
pDialog.dismiss();
if (result.equals(AsyncResultConst.SUCCESS)) {
listener.onRecieveResult(identifier, jsonString);
} else if (result.equals(AsyncResultConst.PARSINGERROR)) {
// showAlertMessage(context, "Error", "Parsing Error", null);
listener.onRecieveException(identifier, result);
} else {
if (retry < 0) {
retry++;
new CustomerAsyncTask(context, url_string, usedMethod,
identifier, runInBackground, DialogString, parameter,
listener).execute("");
} else {
// showAlertMessage(context, "Error", "Connection Error", null);
listener.onRecieveException(identifier, result);
}
}
super.onPostExecute(result);
}
private void initProgressDialog(String loadingText) {
pDialog = new ProgressDialog(this.context);
pDialog.setMessage(loadingText);
pDialog.setCancelable(false);
pDialog.show();
}
}
Don't use Async-task in such case, use native java thread here.
new Thread(new Runnable() {
public void run() {
// Do your work .....
}
}).start();
When need to update UI. Yes! Android won't allow you to do that. so... solution is: USE Handler for that :)
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// Do Update your UI
}
});
Use AsyncTask for:
Simple network operations which do not require downloading a lot of
data Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
You could use Google's GSON as well.
Try to use Jackson Library to manage your JSON. It is really efficient. You can find it here : http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs
I am using it for a 400KB file is less than 1 second.
If you want a tuto this one looks good http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
This is how is read JSON into my listview in my app. The result is processed to my app in an average of 3 seconds on Wi-Fi and 5 seconds on 3G:
public class CoreTeamFragment extends ListFragment {
ArrayList> membersList;
private String url_all_leaders = //URL goes here
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_TEAM = "CoreTeam";
private static final String pid = "pid";
private static final String COL_NAME = "CoreTeam_Name";
private static final String COL_DESC = "CoreTeam_Desc";
private static final String COL_PIC = "CoreTeam_Picture";
JSONArray CoreTeam = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public CoreTeamFragment() {
}
public void onStart() {
super.onStart();
membersList = new ArrayList<HashMap<String, String>>();
new LoadAllMembers().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.leader_id))
.getText().toString();
Intent intent = new Intent(view.getContext(),
CoreTeamDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_coreteam,
container, false);
return rootView;
}
class LoadAllMembers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_leaders,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
CoreTeam = json.getJSONArray(TABLE_TEAM);
// looping through All Contacts
for (int i = 0; i < CoreTeam.length(); i++) {
JSONObject ct = CoreTeam.getJSONObject(i);
// Storing each json item in variable
String id = ct.getString(pid);
String name = ct.getString(COL_NAME);
String desc = ct.getString(COL_DESC);
String pic = ct.getString(COL_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_PIC, pic);
// adding HashList to ArrayList
membersList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(),
membersList,
R.layout.coreteam_item,
new String[] { pid, COL_NAME, COL_DESC, COL_PIC },
new int[] { R.id.leader_id, R.id.leaderName,
R.id.photo });
setListAdapter(adapter);
}
});
}
}
}
Use Volley or Retrofit lib.
Those lib are increasing the speed.
Volley:
JsonObjectRequest channels = new JsonObjectRequest(Method.POST,
Constants.getaccountstatement + Constants.key, statement_object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
I have a php script that returns this json array.
{"PID":"1","PName":"Guitar","Brand":"Fender","Price":"110","Cat#":"1","Typ#":"1"}
I am making a simple app that places these results into several text views. only one product is returned each time as above.
when I run the app I get this Error: org.json.JSONException: Value
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"}
of type org.json.JSONObject cannot be converted to JSONArray.
Here is my code. Is there something wrong with the json result or the code?
public class MainActivity extends ActionBarActivity {
TextView tvname;
TextView tvbrand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvname = (TextView) findViewById(R.id.tvName);
tvbrand = (TextView) findViewById(R.id.tvBrand);
Button btnPost = (Button) findViewById(R.id.btnPost);
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new getPro().execute();
}
});
}//end of on create
private class getPro extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
getPro.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... strings) {
String url_select = "http://10.0.2.2/OnetoOne/getProduct.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("pid", "2"));
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
//JSONObject jObject = jArray.getJSONObject(0);
String anem = jArray.getJSONObject(0).getString("PName");
//String getname = jObject.getString("PName");
//String getbrand = jObject.getString("Brand");
tvname.setText(anem);
//tvbrand.setText(getbrand);
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}//end of async
}//end of class
Any help would be greatly appreciated.
That's not an array it's an object
JSONObject jObject = new JSONObject(result);
String anem = jObject.getString("PName");
tvname.setText(anem);
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"} of type org.json.JSONObject cannot be converted to JSONArray.
You are trying to convert a JSONObject into a JSONArray, this is your error.
Use :
JSONOjbect jso = new JSONObject(result);
A JSONObject Start with { and end with }.
A JSONArray Start with [ and end with ].
I have a google map inside my android application, I have some saved data in mysql db with latitude and longitude and i want to read that data from mysql db.
I have wrote code but the app is still error .
myphp is :
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('joe', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT lattitude, longitude FROM tracking";
$result = mysql_query($query, $link) or die('Errorquery: '.$query);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$data = "{joel:".json_encode($rows)."}";
echo $data;
?>
I have 3 java activities
public class lagiiiiteslagi extends ListActivity {
private static String url = "http://10.0.2.2/labiltrack/daftartracking.php";
// JSON Node names
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
// contacts JSONArray
JSONArray lattitude = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
lattitude = json.getJSONArray(TAG_lattitude);
// looping through All Contacts
for(int i = 0; i < lattitude.length(); i++) {
JSONObject c = lattitude.getJSONObject(i);
// Storing each json item in variable
String lattitude = c.getString(TAG_lattitude);
String longitude = c.getString(TAG_longitude);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_lattitude, lattitude);
map.put(TAG_longitude, longitude);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e){
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.main,
new String[] { TAG_lattitude, TAG_longitude }, new int[] {
R.id.TextViewResult, R.id.TextViewResult1 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
// getting values from selected ListItem
//String lattitude = ((TextView)) view.findViewById(R.id.TextViewResult)).getText().toString();
//String longitude = ((TextView)) view.findViewById(R.id.TextViewResult1)).getText(lattitude).toString();
String lattitude = ((TextView) view.findViewById(R.id.TextViewResult)).getText().toString();
String longitude = ((TextView) view.findViewById(R.id.TextViewResult1)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_lattitude, lattitude);
in.putExtra(TAG_longitude, longitude);
startActivity(in);
}
});
}
}
this JSONparser class :
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser(){
}
public JSONObject getJSONFromUrl(String url) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// defaultHttpClient
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 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;
}
}
this is use to display in listview :
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String lattitude = in.getStringExtra(TAG_lattitude);
String longitude = in.getStringExtra(TAG_longitude);
// Displaying all values on the screen
TextView lbllattitude = (TextView) findViewById(R.id.listlat);
TextView lbllongitude = (TextView) findViewById(R.id.listlong);
lbllattitude.setText(lattitude);
lbllongitude.setText(longitude);
}
}
I just want to display that lattitude and longitude in listview but still error, I'm new to android, I hope some one help me,
Thank in advance !
check this link for json help...
I suggest to to use log like Log.e("JSON", json); in different place to find the point where the error actually happens.
I get the "No Items found" toast on the ListActivity.
Note: When I change the PHP code to "Select * from items", the entire table shows up. But when I try to filter it with the param/cat_id value in Android/Java, I get a blank
Here is code, first: php
<?php
$sql=mysql_query("SELECT * FROM items WHERE cat_id = ' ".$_REQUEST['cat_id']." '");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
(I have confirmed that "cat_id", the value I am passing into the below activity through a bundle is what it needs to be.)
Android/Java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cat_id = getIntent().getExtras().getString("category_id");
items = new ArrayList<String>();
new task().execute();
}
class task extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/items.php";
param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("category_id", cat_id));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
//
}
and farther below
protected void onPostExecute(Void v) {
String item;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
item = json_data.getString("item");
items.add(item);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Items Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
I get the "No Items found" toast on the ListActivity.
Note: When I change the PHP code to "Select * from items", the entire table shows up. But when I try to filter it with the param/cat_id value in Android/Java, I get a blank.
On the Java code you write
param.add(new BasicNameValuePair("category_id", cat_id));
but on the PHP code you write
$_REQUEST['cat_id']
you should change it to
$_REQUEST['category_id']