Null display when parsing json from php to android - java

here is my php code
$titikPetaInti = array();
while($row = mysql_fetch_assoc($hasil2))
{
$titikPetaInti[] = $row['koordinat'];
}
$data = "{titikPeta:".json_encode($titikPetaInti)."}";
echo $data;
?>
then here is my android code
xResultTitikPeta is result request to php
jObject = new JSONObject(xResultTitikPeta);
JSONArray myArray1 = (JSONArray) jObject.getJSONArray("titikPeta");
String[]titikPeta = new String[myArray1.length()];
for(int a = 0; a < myArray1.length(); a++)
{
titikPeta[a] = myArray1.getJSONObject(a).toString();
}
teks1 = (TextView) findViewById(R.id.textView1);
teks1.setText(Arrays.toString(titikPeta));
it displaying null at emulator like no value
--EDIT--
i think there something mistake in parsing code, cus when i display the xResultTitikPeta in android, it give me string result
here is result of xResultTitikPeta
{titikPeta:["-8.705378,115.225189","-8.56056700000000,115.42395100000","-8.57659700000000,115.40065300000","-8.55596300000000,115.41085700000","-8.51855200000000,115.491908000000","-8.54743200000000,115.41036800000","-8.56551100000000,115.45173900000","-8.44321000000000,115.616019000000"]}

this is malformed JSON! no double quotes on key.
$data = "{titikPeta:".json_encode($titikPetaInti)."}";
instead do:
$data = '{"titikPeta":'.json_encode($titikPetaInti).'}';
EDITED:
Ok, remove that hand made approach:
$data = json_encode(array("titikPeta"=>$titikPetaInti));

OK, I've found your bug! As well as fixing the $data = json_encode(array("titikPeta" => $titikPetaInti)); issue, the problem is here:
titikPeta[a] = myArray1.getJSONObject(a).toString();
The elements of myArray1 are actually of type string and cause an exception to be thrown, so you need instead:
titikPeta[a] = myArray1.getString(a);
This produces the output of:
[-8.705378,115.225189, -8.56056700000000,115.42395100000, -8.57659700000000,115.40065300000, -8.55596300000000,115.41085700000, -8.51855200000000,115.491908000000, -8.54743200000000,115.41036800000, -8.56551100000000,115.45173900000, -8.44321000000000,115.616019000000]
As each element in your array is of the form "-8.705378,115.225189", the JSON parser assumes they are strings. If you change the elements to "-8.705378","115.225189" you can also use:
titikPeta[a] = Double.toString(myArray1.getDouble(a));
However, the first version will work too.
Note: my personal preference is that I would declare each array element as:
{"x":-8.705378,"y":115.225189}

try
$data = "{\"titikPeta\":".json_encode($titikPetaInti)."}";

Related

Read a specific value from JSON in Java

I am making an app in android studio using an API that returns the following:
[{"domains": ["upes.ac.in"], "country": "India", "state-province": "Dehradun", "web_pages": ["https://www.upes.ac.in/"], "name": "University of Petroleum and Energy Studies", "alpha_two_code": "IN"}]
I run it as follows:
public void onResponse(String response) {
listaUniversidades = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
String nombreUni, pais, url;
for (int i = 0; i < jsonArray.length(); i++) {
nombreUni = jsonArray.getJSONObject(i).getString("name");
pais = jsonArray.getJSONObject(i).getString("country");
url = jsonArray.getJSONObject(i).getString("web_pages"));
texto.setText(url);
listaUniversidades.add(new Universidad(nombreUni, pais, url));
}}
The thing is that the web_pages returns the following: ["http://.www.upes.ac.in/"]
How could I make it return the correct url? Since that way I can not access the university website.
Thank you!
I will assume that you aways want to get the first "web_page" inside the "web_pages" array.
You can try to convert the "web_pages" attribute to an array before trying to get the first element, like this:
url = jsonArray
.getJSONObject(i)
.getJSONArray("web_pages"))
.getJSONObject(0)
.toString();
Have you verified that the API returns the expected value for web_pages? You can set a breakpoint on the line
String nombreUni, pais, url;
And then inspect the variable jsonArray. I think the incorrect value that you got is most likely because the API returns that value.
The problem is that "web_pages": ["https://www.upes.ac.in/"] is a JSON Array, so you need to convert it to the array and then access the appropriate item in it(presumably first one?)
It can be done the way Aleph proposed above.

Replace XML path with a string in groovy file

I'm trying to replace a xml rootnode with a string, but it doesn't allow me.
I was trying to give it as
String str = "SOAP-ENV:Body'.'ns1:creditCardResponse";
I should not repeat SOAP-ENV:Body'.'ns1:creditCardResponse in all these lines.
def rootnode = new XmlParser().parseText(responseXml);
status = rootnode.'SOAP-ENV:Body'.'ns1:creditCardResponse'.return.Status.text();
errorCode = rootnode.'SOAP-ENV:Body'.'ns1:creditCardResponse'.return.Errorcode.text();
errorInfo = rootnode.'SOAP-ENV:Body'.'ns1:creditCardResponse'.return.Errorinfo.text();
referenceCode = rootnode.'SOAP-ENV:Body'.'ns1:creditCardResponse'.return.ReferenceCode.text();
requestIp = rootnode.'SOAP-ENV:Body'.'ns1:creditCardResponse'.return.RequestIP.text()
Any ideas would be greatly appreciated.
Thanks.
Remember that these "paths" are just a series of normal groovy property accesses, so you can store any intermediate point in the path as a variable and continue navigating from there:
deg rtn = rootnode.'SOAP-ENV:Body'.'ns1:creditCardResponse'.return
status = rtn.Status.text()
errorCode = rtn.Errorcode.text()
// etc.

send String[] b httprequest and get in php b $_GET

I want to send a String[] by an HTTP request and get the values in PHP with the $_GET method.
The total number of values in the String[] is variable.
I have tried so far:
List<NameValuePair> params = new ArrayList<NameValuePair>();
String[] dropdowns = {"1st item","2nd item","3rd item","4th item"};
for (int i = 0; i < dropdowns.length; i++) {
params.add(new BasicNameValuePair("pid", dropdowns[i]));
}
In PHP I want to get all values and query based on them.
$pid = $_GET['pid'];
And use them like:
$result = mysql_query("SELECT *FROM Apps WHERE pid[0] = $pid" AND pid[1] = $pid"
AND ...);
But I know this way is wrong.
How can I do that?
This
$result = mysql_query("SELECT *FROM Apps WHERE pid[0] = $pid" AND pid[1] = $pid" AND ...);
Is very wrong and unsafe. (Columns wrong syntax, SQL injection, wrong quotation, wrong SQL syntax,...)
Must be something like
$result = mysql_query("
SELECT * FROM Apps WHERE pid
IN(" . implode(',', mysql_real_escape_string($pid)) . ")
");
You can create a serialized reprezentation of the values you want to send in the url. It has limitations such as the max length of the url.
'http://domain.com/data_handler.php?data=' . urlencode(serialize($array1));
Getting back your array:
$array1 = unserialize($_GET['data']);
Its even better to create a post request and use this syntax:
pid[]=1
pid[]=2
http://www.php.net/manual/en/faq.html.php
You cannot send an array through HTTP request UNLESS you have an array of inputs such as:
<input type='text' name='manyOfThese[]' />
To send an array you have two options. One is to use serialize() and unserialize() to turn your array into a string. And the other is to use session variables:
$_SESSION['pid'] = $pid;
Then on the next script
$pid = $_SESSION['pid'];
unset($_SESSION['pid']);
foreach($pid as $element){
echo $element //or do whatever you need to do to that variable
}
Also at the beginning of your scripts you will want to include:
session_start();
And then when your php application is exited (upon logoff for example):
session_destroy();
There are two parts to this and both involve loops. First, when you are sending the data, put the brackets in the name to send it as an array:
for (int i = 0; i < dropdowns.length; i++) {
params.add(new BasicNameValuePair("pid[]", dropdowns[i]));
}
Second, on the php end this array is stored in $_GET['pid'] or $_POST['pid'] depending on how you sent it, so you would loop through the array and add the items to your sql query. Just make a separate variable to store the sql statement so you can add to it:
$x = 0;
foreach($_GET['pid'] as $value) {
$yourSQLString .= " AND pid[". $x ."] = '" . $value . "'";
$x++;
}
And obviously you should do something else with the actual value to avoid sql injections.

How to get multiple rows of JSON data and put it into some sort of Array?

I tried to retrieve multiple rows of JSON data and display it but im not able to retrieve all the rows,im only getting the top(first) row of the database table.And im confused about how can i put the retrieved JSON data into some sort of array and access the individual rows?
I have provided the code relevant to the problem.
Yes i have done enough research before posting this question.I actually found one question which was some what similar to mine but nobody has answered it so i'm making this post.
Thank You
Below is the code from my Freebies.java class where i'm trying to retrieve JSONdata by calling getAllFreebies function from UserFunctions.java class
UserFunctions uf = new UserFunctions();
JSONObject json = uf.getAllFreebies();
System.out.println(json);
Below is the code of the function getAllFreebies() in the class UserFunctions.java
public JSONObject getAllFreebies(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getAllFreebies_tag));
JSONObject json = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
return json;
}
Below is the code from index.php where im calling getFreebies() function from DB_Function.php file
else if($tag = 'getAllFreebies'){
$getAllFreebies = $db->getFreebies($username,$catagory,$subcatagory,$title,$condition,$description,$address,$city,$state,$country,$zipcode,$posted_on);
if($getAllFreebies)
{
$response["success"] = 1;
$response["getAllFreebies"]["username"] = $getAllFreebies["username"];
$response["getAllFreebies"]["catagory"] = $getAllFreebies["catagory"];
$response["getAllFreebies"]["subcatagory"] = $getAllFreebies["subcatagory"];
$response["getAllFreebies"]["title"] = $getAllFreebies["title"];
$response["getAllFreebies"]["item_condition"] = $getAllFreebies["item_condition"];
$response["getAllFreebies"]["description"] = $getAllFreebies["description"];
$response["getAllFreebies"]["address"] = $getAllFreebies["address"];
$response["getAllFreebies"]["city"] = $getAllFreebies["city"];
$response["getAllFreebies"]["state"] = $getAllFreebies["state"];
$response["getAllFreebies"]["country"] = $getAllFreebies["country"];
$response["getAllFreebies"]["zipcode"] = $getAllFreebies["zipcode"];
$response["getAllFreebies"]["posted_on"] = $getAllFreebies["posted_on"];
echo json_encode($response);
}else {
$response["error"] =1;
$response["error_msg"] = "Error in getAllFreebies";
echo json_encode($response);
}
}// end of getAllFreebies tag
Below is the code of my getFreebies() function of DB_function.php which is responsible for performing queries on MySQL database.
public function getFreebies(){
$result = mysql_query("SELECT * FROM freebie") or die(mysql_error());
return mysql_fetch_array($result);
}
Below is the logcat:
05-30 00:13:23.960: E/JSON(318): {"tag":"getAllFreebies","success":1,"error":0,"getAllFreebies":{"username":"viking","catagory":"Art","subcatagory":"Potrait","title":"Potrait","item_condition":"Good","description":"potarit","address":"Blah St","city":"lalaland","state":"NA","country":"NA","zipcode":"blah","posted_on":"2012-05-27"}}
mysql_fetch_array() only returns a single row of the query result set as an array. It does not fetch ALL of the rows. Since you're returning the results of the fetch from your getFreebies method, instead of the result handle itself, it is impossible for the calling code to get any other results from the query, other than the one row you've fetched.
As such, you should have:
public function getFreebies() {
$result = ...
return($result);
}
and
$getAllFreebies = $db->getFreebies(...);
$data = array();
while($row = mysql_fetch_assoc($getAllFreebies)) {
$data[] = array(
.... your variable assignments here ...
);
}
echo json_encod($data);

Extracting top-level domain names from list of website addresses

I have a list of web addresses such as listed below in my DB.
I need to get the domain name from each address in the list.
http://en.wordpress.com/tag/1000-things-we-hate/
http://en.wordpress.com/tag/1019/
http://en.wordpress.com/tag/1030-am/
http://www.yahoo.com/index.html
http://www.msn.com/index.html
Here's a way to do it in Java:
String input = "http://en.wordpress.com/tag/1000-things-we-hate/";
// Assuming that all urls start with "http://"
int finish = input.indexOf("/", 7);
if(finish == -1)
{
finish = input.length();
}
System.out.println(input.substring(7, finish));
Prints en.wordpress.com (I assume that is what you want?)
<?php
$url = "http://en.wordpress.com/tag/1000-things-we-hate/";
$bits = explode("/",$url);
$nextBits = explode(".",$bits[1]);
$count = count($nextBits);
$domain = $nextBits[$count-1].".".$nextBits[$count];
echo $domain;
?>
<?php
echo parse_url($url, PHP_URL_HOST);
That would return "en.wordpress.com". If you don't want subdomains (i.e. only "wordpress.com), then things are getting complicated. You would need something like http://www.dkim-reputation.org/regdom-libs/
Use the parse_url in PHP.

Categories