Android JSON POST and then response - android

I can retrieve data through JSON in listview but I want to show data relative to the user logged in so for that I have to Post username to PHP script. I don't have any idea how to post the username to PHP script and then get respond from web server.
private class GetFixture extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d("url: ", "> " + URL_ITEMS);
String json = serviceClient.makeServiceCall(URL_ITEMS,ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture resps","> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d("matchId", matchId);
String teamA = c.getString(TAG_TEAMA);
Log.d("teamA", teamA);
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixture.put(TAG_TEAMA, teamA);
matchFixture.put(TAG_TEAMB, teamB);
matchFixtureList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
Doctor_Names.this, matchFixtureList,
R.layout.list_item, new String[] {
TAG_MATCHID, TAG_TEAMA,TAG_TEAMB
}
, new int[] {
R.id.teamA,R.id.name,
R.id.teamB
}
);
setListAdapter(adapter);
}
sir this code perfectly show me all data from this server but i want some specific data like i want to show data related to the person who is logged in so for that i have to pass the user name to PHP script so dont have idea to POST any thing to web on the basis of which i can filter data

Here is an example:
JSONObject obj = new JSONObject();
obj.put("username", "YourUser");
HttpUrlConnectionJson.sendHTTPData("http://" + serverAddress + "/api/SomeUserMethod", obj);
HttpUrlConnectionJson class
public class HttpUrlConnectionJson {
private static final String TAG = "HttpUrlConnectionJson";
public static String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d(TAG, stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e(TAG, connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e(TAG, exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
I hope this help

Related

JSON Parsing error: No value for JSON array [duplicate]

This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 4 years ago.
I have a code where i should pass an static user id for authentication and then fetch the JSON response from the URL and display it in listview. But i get an error that says "JSON Parsing error: No value in (JSON array)". Please help
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "url";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "2"));
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("SignUpRsp", String.valueOf(result));
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
}
}
public String PostData(String[] valuse) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "value"));
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse= httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try {
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
}
JSON Response:
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
},
]
}
Your JSON parsing is correct
You need to parse your JSON if your response status response code is 1
SAMPLE CODE
Try this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// check here of your status of response
// is status is 0 USER NOT FOUND
if(jsonObj.getString("status").equals("0")){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
}
});
// is status is 1 PARSE YOUR JSON
}else {
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
Your json also has an issue, can you try with this output json. Last comma(,) in an array is not required.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
JSONArray throw error because promotion_lists with a item but has needless comma.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
Your JSON parse looks fine. The issue is with the your JSON response. It is not a valid JSON Response as there is a unnecessary comma after the JSON Array "promotion_lists". Try removing the comma.
You can use this solution
public class GetContacts extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg0) {
try {
URL url = new URL(URL HERE);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
JSONObject postDataParams = new JSONObject();
postDataParams.put("user_id", user_id);
Log.i("JSON", postDataParams.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(postDataParams.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
conn.disconnect();
return sb.toString();
} else {
conn.disconnect();
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String jsonStr) {
try {
pDialog();
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Log.e(TAG, "Couldn't get json from server.");
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
One more thing you dont need to use runOnUiThread in Asynctask because
both are helper threads , which are used to Update UI,you dont have to
use runOnUIThread in it , just simple show toast without using it, it
will show it , read the documentation
https://developer.android.com/guide/components/processes-and-threads

JSONObject can't be correctly created

I want to get images from server into my Android app.
My first steps are:
I have this JSON string array from server
{"results":"[{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara1.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara2.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara3.jpg\"}]"}
I got urls in my App from server with code below and working fine.
private void getURLs() {
class GetURLs extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(GalleryTargets.this, "Loading...", "Please Wait...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(GalleryTargets.this,s,Toast.LENGTH_LONG).show();
imageJSON = s;
Log.e(LOGTAG, "Succeed Read url" + imageJSON);
extractJSON(imageJSON);
}
#Override
protected String doInBackground(String... strings) {
String uri = strings[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json);
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetURLs gu = new GetURLs();
gu.execute(newurl);
}
But, i want to extract json into a new JSON Object with this method below but throws the exception, Json object not created.
Any ideas why this exception happens?
Thank you in advance!
private void extractJSON(String jsonString){
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jArray.length(); i++) {
JSONObject oneObject = jArray.getJSONObject(i);
oneObject.getString("url");//
}
Log.e(LOGTAG, "JsonArray Succeed" );
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOGTAG, "JsonArray exception");
}
}
Instead of JSONArray jArray = jsonObject.getJSONArray("results");
Try JSONArray jArray = new JSONArray (jsonObject.getString("results"));
You're asking for a json array but it is a string.
There is an error on the json.. after "results": there must not be
quotes
This is correct
{"results":[{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara1.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara2.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara3.jpg\"}]}

Retrieving data from JSON?

I am trying to get all the species result from the first url but sadly, my for loop can only retrieve one species from my first url and I don't know what's the correct logic here. Hope you can help me. I know the problem is my for loop but I don't know how to construct it correctly. Sorry. Newbie here.
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?species_name="
+ search_species;
pDialog.setMessage("Loading data...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("tem");
for(int i = 0; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
species_id = o.getString("localname");
common = o.getString("name");
scientific = o.getString("scientificname");
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?speciesid=" + species_id;
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("locationid", c.getString("locationid"));
map.put("brgy", c.getString("brgy"));
map.put("town", c.getString("town"));
map.put("latitude", c.getString("latitude"));
map.put("longitude", c.getString("longitude"));
map.put("speciesid", local);
map.put("flowercolor", c.getString("flowercolor"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
This is my getHttpGet:
public static String getHttpGet(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
and this is the PHP file:
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$species_name = $_GET['species_name'];
$sql = "SELECT * from tbl_species WHERE CONCAT_WS(name, localname,
scientificname, familyname, flowercolor, leafshape) LIKE '%$species_name%'";
$result = $conn->query($sql);
if ($result->num_rows >0) {
$arr['aaData'] = array();
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode(array('tem' => $tem));
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
Specifically, my for loop can only get the first species, after getting that, the for loop stops to get the others. I don't know what's wrong and what I should change. I'm creating a project that can search a species by name, by color, by shape etc.
Just a guess but maybe because you use the same int in both for loops
for(int i = 0; i<array.length(); i++)
for(i = 0; i < data.length(); i++){
You have a NetworkOnMainThreadException and your app crashes when you handle the second url.
You could have told us of the crash.
You should execute all network/internet code in a thread or asynctask.
You must have 2 variables to save the values in PHP file.and use array_push for save all values in an array
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?type=first&species_name="
+ search_species;
.
.
.
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?type=tow&speciesid=" + species_id;
try {.....
and in PHP file
$type = $_GET['type'];
$response1 = array();
$response2 = array();
.
.
.
while($row[] = $result->fetch_assoc()) {
if (type ==="fist"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}elseif (type ==="tow"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}
}////end while
if (type ==="fist"){
echo $response1;
}elseif(type1 ==="tow"){
echo $response2;
}
.
.
.

Android Places API parse all JSON categories

I have the following class GetPlaces already, which will take the Google Places API URL new GetPlaces().execute("https://maps.googleapis.com/maps/api/place/search/json?types=cafe&rankby=distance&location=33.897835,-117.955759&sensor=false&key=MyKey"); that gets called in my main activity onCreate() and Parses the output.
private class GetPlaces extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : urls) {
//execute search
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
HttpGet placesGet = new HttpGet(placeSearchURL);
HttpResponse placesResponse = placesClient.execute(placesGet);
StatusLine placeSearchStatus = placesResponse.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
//we have an OK response
HttpEntity placesEntity = placesResponse.getEntity();
InputStream placesContent = placesEntity.getContent();
InputStreamReader placesInput = new InputStreamReader(placesContent);
BufferedReader placesReader = new BufferedReader(placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
protected void onPostExecute(String data) {
// TODO: check this.exception
// TODO: do something with the feed
/*
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
*/
super.onPostExecute(data);
// Dismiss the progress dialog
if(data !=null)
{
JSONObject jsonObj;
try {
jsonObj = new JSONObject(data);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String name = result.getString("name");
/*
String icon = result.getString("icon");
String address = result.getString("vicinity");
String rating = result.getString("rating");
String price = result.getString("price_level");
String webiste = result.getString("website");
//String review = result.getString("reviews");
*/
Log.d("tag", "name: " + name);
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//System.out.println(dat);
}
}
I have a few questions about this code:
I get an org.json.JSONException: No value for reviews error and I'm not sure what the best way to check for that is.
How can get Images of the place? I don't mean icon but how can I get the photos in the photos[] array?
How can I retrieve this data in my Main Activity's onCreate method or a helper function?
Try This:-
This url will help you to find/search NearByPlaces.....
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + ","
+ mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=--Your--Key--");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
Try to pass url as below.You have to put radius also in url for finding place(in your example cafe).& after getting places you can use Marker option for marking places.for that you can use your images as marker
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=2000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=Your+Key");
GetPlaces placesTask = new GetPlaces();
placesTask.execute(sb.toString());

Android sent to php (httppost) "Undefined index: txtProvinceId "Help Me please

public class DialogSelectAmphurActivity extends Activity {
private final String TAG = "internet";
private ListView listview_province;
ArrayList<HashMap<String, String>> myList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
String strUrl =("http://192.168.1.4/test_projectEnd/amphur.php");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_select_province_dialog);
new AsyncDownload().execute(strUrl);
}
public String getData(String strUrl, ArrayList<NameValuePair> params){
String jString;
HashMap<String, String> map;
String sProvince_id = getIntent().getStringExtra("provinceId");
params.add(new BasicNameValuePair("txtProvinceId",sProvince_id));
try {
jString = getJsonFromUrl(strUrl, params);
JSONArray jArray = new JSONArray(jString);
Log.d(TAG, jArray +","+ params);
for(int i =0; i< jArray.length(); i++)
{
JSONObject jObj = jArray.getJSONObject(i);
String sAmphur_id = jObj.getString("AMPHUR_ID");
String sAmphur_name = jObj.getString("AMPHUR_NAME");
map = new HashMap<String, String>();
map.put("amphur_id", sAmphur_id);
map.put("amphur_name", sAmphur_name);
myList.add(map);
Log.d(TAG, sAmphur_id + sAmphur_name);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void showProvince(){
ListView listView = (ListView) findViewById(R.id.listView_province1);
ListAdapter adapter = new SimpleAdapter(this, myList, R.layout.row_layout_select_province,
new String[]{"amphur_id","amphur_name"}, new int[]{R.id.textView_province_id,R.id.textView_province_name});
listView.setAdapter(adapter);
}
private String getJsonFromUrl(String strUrl,ArrayList<NameValuePair> params)throws IOException{
URL url = new URL(strUrl);
HttpPost httpPost = new HttpPost(strUrl);
try {
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.d(TAG, params+"check");
httpCon.setRequestMethod("GET");
httpCon.setConnectTimeout(6*1000);
int responseCode = httpCon.getResponseCode();
Log.d(TAG, "The response is" + responseCode);
if(responseCode == HttpsURLConnection.HTTP_OK){
Log.d(TAG, "size" + httpCon.getContentLength());
InputStream ins = httpCon.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(ins,"UTF-8"));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null){
response.append(line);
response.append("\n");
Log.d(TAG, line);
}
rd.close();
return response.toString();
}
} catch (Exception ex) {
Log.d(TAG,"Problem reading"+ ex.getLocalizedMessage());
}
return null;
}
private class AsyncDownload extends AsyncTask<String, Void, String>{
ProgressDialog pd;
#Override
protected void onPreExecute(){
pd = ProgressDialog.show(DialogSelectAmphurActivity.this, "Download", "Downloading....");
}
protected String doInBackground(String... Params){
String data = getData(strUrl, params);
return null;
}
protected void onPostExecute(String result){
pd.dismiss();
showProvince();
}
}
}
i sent txtprovinceId to php
"Sorry for any incorrect on my conversation, my English is not good."
<?php
$provinceid = trim($_GET["txtProvinceId"]);
require("libs/connection_to_abc.php");
mysql_query("SET character_set_results=utf8");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");
$strSQL = "SELECT amphur.* FROM province,amphur
WHERE province.PROVINCE_ID = amphur.PROVINCE_ID
AND province.PROVINCE_ID ='$provinceid' ";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($link);
echo json_encode($resultArray);
?>
php response in Logcat "Undefined index: txtProvinceId in amphur.php on line 3"
Help me please ! "Sorry for any incorrect on my conversation, my English is not good."
You never add your params to the query string. You can use URLEncodedUtils.format() to format them easily :
import org.apache.http.client.utils.URLEncodedUtils;
...
private String getJsonFromUrl(String strUrl,ArrayList<NameValuePair> params) {
String queryString = URLEncodedUtils.format(params, null);
URL url = new URL(strUrl + "?" + queryString);
...
}

Categories

Resources