Retrieving data from JSON? - android

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;
}
.
.
.

Related

How to fetch json array inside array in android listview

I'm having json format as below , How do i fetch it into listview in android, While i'm trying to do, following error rises. I,m having multiple starting array square brackets.
org.json.JSONException: Value [{"id":"30","title":"Android Design Engineer","postedDate":"2016-11-19","jobtype":"Contract","location":"Alabama","description":"Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world","experience":"2 to 6 yrs","salary":" Upto $50"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
and the following my java code is, here i call jsosarray and split it into objects.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE,postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
My Json array
[
[
{
"id": "30",
"title": "Android Design Engineer",
"description": "Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-19",
"location": "Alabama",
"experience": "2 to 6 yrs"
}
],
[
{
"id": "24",
"title": "Android Application Developer",
"description": "Android Application Developer is the major Development Technique that is used in this damn World.",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-16",
"location": "North Carolina",
"experience": "6 to 10 yrs"
}
]
]
Check below parsing logic as per your JSON:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray jsonChildArray = jsonArray.getJSONArray(i);
if (jsonChildArray != null && jsonChildArray.length() > 0) {
JSONObject c = jsonChildArray.getJSONObject(0);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE, postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
}
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
}
} catch (Exception e) {
Log.e("erroe", e.toString());
return e.toString();
}
Yes .There is an error.Your JSON Data has An array inside array and you are trying to assign internal array as object.
First convert outer array JsonArray jsonArray1;
Iterate through this array. i=0 -> jsonArray1.length; and create another
JsonArray jsonArray2 = jsonArray1[i];
And finally iterate through jsonArray2: j=0 -> jsonArray2.length()
and create a JsonObject json = jsonArray2[j];
I hope you understood. This is psuedocode. If you want code, tell me.I can write it.

Android JSON POST and then response

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

org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject

Getting org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject..Where would be code went wrong?This is a program to get values from a live streaming ..complete code is given below..
JSON given
race: {
id: "44708",
track_id: "1",
track: "International",
starts_at: "2016-05-04 06:16:00",
finish_time: "1970-01-01 01:00:00",
heat_type_id: "123",
heat_status_id: "1",
speed_level_id: "5",
speed_level: "Nat Cadet & Junior",
win_by: "position",
race_by: "minutes",
duration: 10,
race_name: "Inkart National Heat",
race_time_in_seconds: 276.336
},
scoreboard: [
{
position: "1",
nickname: "Emily Linscott",
average_lap_time: "90.053",
fastest_lap_time: "60.490",
last_lap_time: "60.490",
rpm: "1225",
first_name: "Emily",
last_name: "Linscott",
is_first_time: "0",
total_races: "6",
racer_id: "1157509",
lap_num: "3",
kart_num: "63",
gap: ".000",
ambtime: "31728819591"
},
Code
protected JSONObject doInBackground(String... urls) {
JSONObject jsonObj = null;
Log.d("TAG","inside doInBackground..");
try {
URL url = new URL("http://daytonamk.clubspeedtiming.com/api/index.php/races/scoreboard.json?track_id=1&key=cs-dev" + kartNumber);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String result = convertInputStreamToString(inputStream);
parseResult(result);
Log.e("Message", "This is a message");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
String result = "";
{
while ((line = bufferedReader.readLine()) != null) {
builder.append( line);
}
return result;
}
}
private JSONObject parseResult(String result) {
JSONObject jsonObj = null;
if (result == null) {
Toast.makeText(Main_Activity.this, "Race not currently running", Toast.LENGTH_LONG).show();
} else {
try {
int number = 0;
jsonObj = new JSONObject("result");
JSONObject race = jsonObj.getJSONObject("race");
int durationInMins = race.getInt("duration");
String win_by = race.getString("win_by");
JSONArray scoreboard = jsonObj.getJSONArray("scoreboard");
Log.d("TAG", "Json value :" + scoreboard);
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
number = data.getInt("kart_num");
while (kartNumber == number) {
int gridPosition = data.getInt("position");
int gap = data.getInt("gap");
int lastLapTime = data.getInt("last_lap_time");
int bestLapTime = data.getInt("fastest_lap_time");
int raceInTime = race.getInt("race_time_in_seconds");
duration = durationInMins * 60 - raceInTime;
if (!(gridPosition == 1)) {
JSONObject dataPreviousGap = scoreboard.getJSONObject(i - 1);
int gapPrev = dataPreviousGap.getInt("gap");
gapUp = gap - gapPrev;
}
if (!(i == scoreboard.length() - 1)) {
JSONObject dataNext = scoreboard.getJSONObject(i + 1);
int gapNext = dataNext.getInt("gap");
gapDown = gapNext - gap;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObj) {
Intent myIntent = new Intent(Main_Activity.this, Display_Activity.class);
try {
JSONObject jsonObje = new JSONObject("result");
JSONArray scoreboard = jsonObje.getJSONArray("scoreboard");
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
myIntent.putExtra("GridPosition", data.getInt("position"));
myIntent.putExtra("LastLapTime", data.getInt("last_lap_time"));
myIntent.putExtra("MinutesToGo", duration);
myIntent.putExtra("BestLapTime",data.getInt("fastest_lap_time"));
myIntent.putExtra("GapUp", gapUp);
myIntent.putExtra("GapDown", gapDown);
}
Just as your logcat reads org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject
Log the response you are getting without parsing the data first. Then you may find out what data types you are dealing with eg: Strings, Integers, Floats,etc.
Post the response here for more help.
EDIT:
This line here jsonObj = new JSONObject("result");
Do this instead jsonObj = new JSONObject(result);
EDIT:
jsonObj = new JSONObject(result);
JSONObject obj = jsonObj.getJSONObject("race");
String id = obj.getString("id");
//do the same for all objects inside race

Sending ArrayList from Android to PHP script using JSON

What is the Scenario
I want to send multiple ArrayList (usally 5) from android to the server and want to insert it into mysql database.
What I Have Done Successfully
I have Successfully send single value and Multiple Values from Android to PHP script using JSON
i have Received single and Multiple Records from mysql database to android using JSON
Here is the Code for inserting and getting value from server
class TeacherLogin1 extends AsyncTask<Void, Void, Void> {
String name,pass;
Context contextt;
int idofteach = 0;
int codee = 0;
TeacherLogin1(String pass1,String name1,Context context)
{
name = name1;
pass = pass1;
contextt = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
codee = Authenticate(name,pass);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(codee!=0)
{
Intent teachers = new Intent(context,TeachersView.class);
teachers.putExtra("TID", codee);
teachers.putExtra("TNAME", TeachName);
teachers.putExtra("sub1", subj1);
teachers.putExtra("sub2", subj2);
teachers.putExtra("sub3", subj3);
teachers.putExtra("sub4", subj4);
startActivity(teachers);
}
else
Toast.makeText(context, "Wrong Details", Toast.LENGTH_SHORT).show();
codee = 0;
}
}
public int Authenticate(String name,String Pass)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pass",Pass));
try
{
HttpClient httpclient = new DefaultHttpClient();
ScriptsFilePath a = new ScriptsFilePath();
HttpPost httppost = new HttpPost(a.TeacherAuthen);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try {
JSONObject jsonResponse = new JSONObject(result);
if(jsonResponse != null)
{
JSONArray jsonMainNode = jsonResponse.optJSONArray("GetTeacher");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
code = jsonChildNode.optInt("ID");
TeachName= jsonChildNode.optString("Name");
subj1= jsonChildNode.optString("subject1");
subj2= jsonChildNode.optString("subject2");
subj3= jsonChildNode.optString("subject3");
subj4= jsonChildNode.optString("subject4");
}
}
} catch (JSONException e) {
// Toast.makeText(getApplicationContext(), "Error" + e.toString(),
// Toast.LENGTH_SHORT).show();
}
return code;
}
and the TeacherAuthen.php script
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host="localhost";
$uname="root";
$pwd='';
$db="examsystem";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
if(isset($_REQUEST)){
$name=$_REQUEST['name'];
$pass=$_REQUEST['pass'];}
$flag['code']=0;
$name1['code1'] = "sdf";
$sql = "SELECT * FROM teachers WHERE Username ='$name' and Pass='$pass'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['GetTeacher'][]=$row;
}
}
echo json_encode($json);
mysql_close($con);
?>
where i am stuck
I dont no how to send ArrayList from android to PHP Script.
For Example I want to send these arraylists to php script =
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
and then in the PHP script i want to insert like this
"INSERT INTO `Question` (`ID` ,`Question` ,`A1` ,`A2` ,`A3` , `A4` ) VALUES (NULL, '$Question', '$A1', '$A2', '$A3' ,'$A4'); "
if i am able to send even a single arrayList then i think i can make a way to do the above
and Thanks for you Time
This is your Array: you can create more as required in your example.
ArrayList<String> contact = new ArrayList<String>();
Then, create a JSONcontacts variable of type JSONObject to store this array in this object
JSONObject JSONcontacts = new JSONObject();
Now, loop through all elements in that contact array and store it in the JSONcontacts
//Loop through array of contacts and put them to a JSONcontact object
for (int i = 0; i < contact.size(); i++) {
try {
JSONcontacts.put("Count:" + String.valueOf(i + 1), contact.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Lets say you created many Arrays, which you probably have done, now you hvave to put them all into 1 JSON. So create a EverythingJSON variable of type JSONObject()
JSONObject EverythingJSON = new JSONObject();
and now put all your contact array and other arrays into it, right you loop through them as described above:
EverythingJSON.put("contact", JSONcontacts);
EverythingJSON.put("something", JSONsoemthing);
EverythingJSON.put("else", JSONelse);
now this is your AsynchTask to send them to your PHP server:
new AsyncTask() {
//String responseBody = "";
#SuppressWarnings("unused")
protected void onPostExecute(String msg) {
//Not Needed
}
protected Object doInBackground(Object... params) {
//Create Array of Post Variabels
ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
//Add a 1st Post Value called JSON with String value of JSON inside
//This is first and last post value sent because server side will decode the JSON and get other vars from it.
postVars.add(new BasicNameValuePair("JSON", EverythingJSON.toString());
//Declare and Initialize Http Clients and Http Posts
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.OnlineAPI);
//Format it to be sent
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/* Send request and Get the Response Back */
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
}.execute(null, null, null);
Now on the PHP server side, you can loop through this JSON as such:
FIrst of all, get that JSON from POST and store it in a var:
//Receive JSON
$JSON_Received = $_POST["JSON"];
Now decode it from JSON:
//Decode Json
$obj = json_decode($JSON_Received, true);
And this is the loop to go through the array of contacts and get he Key and Value from it:
foreach ($obj['contact'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
}
you can repeat this loop for other Arrays you have sent :) Good Luck!
You cant send Arraylist to server,its an object. The best way to solve your problem is
user JSON , you need to do something like that -
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
JsonArray jArr1= new JsonArray();
for(String data:A1)
{
jArr1.add(data);
}
JsonArray jArr2= new JsonArray();
for(String data:A2)
{
jArr2.add(data);
}
//convert each array list to jsonarray
JsonArray jArraySet = new JsonArray();
jArraySet.add(jArr1);
jArraySet.add(jArr2);
//add each json array to jArraySet
// then send the data via
HttpClient httpclient = new DefaultHttpClient();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("all_arraylist",jArraySet.toString()));
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
note: dont forget to do it in asynctask
in php section ,do the following
<?php
$all_arraylist = $_POST['all_arraylist'];
$all_arraylist= json_decode($all_arraylist,TRUE); //this will give you an decoded array
print_r($all_arraylist); // display the array
// after seeing the array , i hope you will understand how to process it.
?>
Very simple. you should parse your JSON in php and get array of objects that you have sent. Here is solution
$JSON_Received = $_POST["json"];
$obj = json_decode($JSON_Received, true);
$array_1st_name = $obj[0];
$array_2nd_name = $obj[1];
and so on you will get all array of object.

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());

Categories

Resources