I am trying to fetch some data from server using json in my flutter app. This is the function I am using.
List<String> userFriendList = ["No Friends"];
Future<http.Response> _fetchSampleData() {
return http.get('//link/to/server/fetcher/test_fetcher.php');
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
userLvl = data["lvl"].toString();
userName = data["name"];
userFriendList = List();
userFriendList = data["friendlist"];
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print('Failed to load data from server');
}
}
I get the usrLvl and userName right. But for userFriendList, I get the following error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
Code on the server end (test_fetcher.php) :
<?php
$myObj->name = "JohnDoe";
$myObj->lvl = 24;
$friends = array("KumarVishant", "DadaMuni", "BabuBhatt", "BesuraGayak", "BabluKaneria", "MorrisAbhishek", "GoodLuckBaba", "ViratKohli", "LeanderPaes");
$myObj->friendlist = $friends;
header('Content-Type: application/json');
$myJSON = json_encode($myObj);
echo $myJSON;
?>
This is a cast error: List<dynamic> != List<String>
You can convert / cast your list in several ways.
I advise you to use this library to simplify your json / Dart object conversion
: https://pub.dev/packages/json_serializable
json_serializable will generate the conversion methods (fromJson and toJson) and take care of everything.
It's easier and safer than doing it manually.
Just what the error says. The userFriendList is of type List you have it as List.
List<String> userFriendList = ["No Friends"];
Should be
List<dynamic> userFriendList = [];
Or a different list entirely if this doesn't work for you.
The error explains it. The fetched data from the server api is decoded to type List<dynamic> and you declared userFriendList to be of type List<String>. What you need to do is change the type of userFriendList from
List<String> userFriendList = ["No Friends"];
to:
List<dynamic> userFriendList = [];
I am new to android and got entangle in problem. what i want is to pass an array object or say an arraylist to a php page so that the same can be inserted into the mysql database.To be more precise i would like to develop an app to sync my contacts with phone numbers to my own server.
thanks in advance.
Try like this.
Map<String,Object> productimages = new HashMap<String, Object>();
List<String> datas = new ArrayList<String>();
datas.add("image");
datas.add("small_image");
datas.add("thumbnail");
productimages.put("types",datas);
If your using nemevalue pair use like this.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("colors[]","red"));
nameValuePairs.add(new BasicNameValuePair("colors[]","white"));
nameValuePairs.add(new BasicNameValuePair("colors[]","black"));
nameValuePairs.add(new BasicNameValuePair("colors[]","green"));
You should be using an API for ex.Rest API. This API will grant the information from your app by an POST action (from you're android app). (transfer data-objects like an array with JSON) Php can decode the JSON and you analyze you're array in php. You can now send specific data into your tables using MYSQL, PDO,..
If the data you transfer needs to be protected, you should use SSL encryption on you're api acces url
Try this
ArrayList <NameValuePair> postparametersSend = new ArrayList <NameValuePair> ();
//This is your file php
String URL = "www.yourserver.com/file.php";
postparameters2send.add (new BasicNameValuePair ("param1", nameParam1));
postparameters2send.add (new BasicNameValuePair ("param2", nameParam2));
postparameters2send.add (new BasicNameValuePair ("param3", nameParam3));
// perform a request and response obtenes JSON array
JSONArray jdata = con.getserverdata (postparametersSend, URL);
//since we are working locally on return will almost immediately
//To give a little realism we say that the process is stopped for a few seconds to
//Observe progressdialog
// We can remove if we
// if what we got is not null
if (jdata! = null && jdata.length ()> 0) {
JSONObject json_data; // create a JSON object
try {
jdata.getJSONObject json_data = (0); // read the first segment in our case the only
System.out.println (json_data);
logstatus = json_data.getInt ("logstatus"); // access the value
Log.e ("LoginStatus", "logstatus =" + logstatus) // show by log we obtained
} Catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
// validate the value obtained
if (logstatus == 0) {// [{"logstatus": "0"}]
Log.e ("logStatus", "invalid");
return false;
}
else {// [{"logstatus": "1"}]
Log.e ("logStatus", "valid");
return true;
}
//} else {invalid json obtained WEB verify part.
Log.e ("JSON", "ERROR");
return false;
}
To make the variables you should put this in the php file
<? php
$nameParam1 = $_POST ["nameParam1"];
$nameParam2 = $_POST ["nameParam2"];
$nameParam3 = $_POST ["nameParam3"];
<- Put your code here ->
?>
I would like to parse a string such as p1=6&p2=7&p3=8 into a NameValueCollection.
What is the most elegant way of doing this when you don't have access to the Page.Request object?
There's a built-in .NET utility for this: HttpUtility.ParseQueryString
// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
You may need to replace querystring with new Uri(fullUrl).Query.
HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
queryParameters.Add(key, val);
}
}
A lot of the answers are providing custom examples because of the accepted answer's dependency on System.Web. From the Microsoft.AspNet.WebApi.Client NuGet package there is a UriExtensions.ParseQueryString, method that can also be used:
var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();
So if you want to avoid the System.Web dependency and don't want to roll your own, this is a good option.
I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the "Client-only Framework Subset".
I liked rp's answer. I added some additional logic.
public static NameValueCollection ParseQueryString(string s)
{
NameValueCollection nvc = new NameValueCollection();
// remove anything other than query string from url
if(s.Contains("?"))
{
s = s.Substring(s.IndexOf('?') + 1);
}
foreach (string vp in Regex.Split(s, "&"))
{
string[] singlePair = Regex.Split(vp, "=");
if (singlePair.Length == 2)
{
nvc.Add(singlePair[0], singlePair[1]);
}
else
{
// only one key with no value specified in query string
nvc.Add(singlePair[0], string.Empty);
}
}
return nvc;
}
To do this without System.Web, without writing it yourself, and without additional NuGet packages:
Add a reference to System.Net.Http.Formatting
Add using System.Net.Http;
Use this code:
new Uri(uri).ParseQueryString()
https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx
I needed a function that is a little more versatile than what was provided already when working with OLSC queries.
Values may contain multiple equal signs
Decode encoded characters in both name and value
Capable of running on Client Framework
Capable of running on Mobile Framework.
Here is my solution:
Public Shared Function ParseQueryString(ByVal uri As Uri) As System.Collections.Specialized.NameValueCollection
Dim result = New System.Collections.Specialized.NameValueCollection(4)
Dim query = uri.Query
If Not String.IsNullOrEmpty(query) Then
Dim pairs = query.Substring(1).Split("&"c)
For Each pair In pairs
Dim parts = pair.Split({"="c}, 2)
Dim name = System.Uri.UnescapeDataString(parts(0))
Dim value = If(parts.Length = 1, String.Empty,
System.Uri.UnescapeDataString(parts(1)))
result.Add(name, value)
Next
End If
Return result
End Function
It may not be a bad idea to tack <Extension()> on that too to add the capability to Uri itself.
If you don't want the System.Web dependency, just paste this source code from HttpUtility class.
I just whipped this together from the source code of Mono. It contains the HttpUtility and all it's dependencies (like IHtmlString, Helpers, HttpEncoder, HttpQSCollection).
Then use HttpUtility.ParseQueryString.
https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c
If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.
Make sure to add a reference (if you haven't already) to System.Net.Http in your project.
Note that you have to convert the response body to a valid Uri so that ParseQueryString (in System.Net.Http)works.
string body = "value1=randomvalue1&value2=randomValue2";
// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();
I just realized that Web API Client has a ParseQueryString extension method that works on a Uri and returns a HttpValueCollection:
var parameters = uri.ParseQueryString();
string foo = parameters["foo"];
private void button1_Click( object sender, EventArgs e )
{
string s = #"p1=6&p2=7&p3=8";
NameValueCollection nvc = new NameValueCollection();
foreach ( string vp in Regex.Split( s, "&" ) )
{
string[] singlePair = Regex.Split( vp, "=" );
if ( singlePair.Length == 2 )
{
nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );
}
}
}
Just access Request.QueryString. AllKeys mentioned as another answer just gets you an array of keys.
HttpUtility.ParseQueryString(Request.Url.Query) return is HttpValueCollection (internal class). It inherits from NameValueCollection.
var qs = HttpUtility.ParseQueryString(Request.Url.Query);
qs.Remove("foo");
string url = "~/Default.aspx";
if (qs.Count > 0)
url = url + "?" + qs.ToString();
Response.Redirect(url);
Since everyone seems to be pasting his solution.. here's mine :-)
I needed this from within a class library without System.Web to fetch id parameters from stored hyperlinks.
Thought I'd share because I find this solution faster and better looking.
public static class Statics
public static Dictionary<string, string> QueryParse(string url)
{
Dictionary<string, string> qDict = new Dictionary<string, string>();
foreach (string qPair in url.Substring(url.IndexOf('?') + 1).Split('&'))
{
string[] qVal = qPair.Split('=');
qDict.Add(qVal[0], Uri.UnescapeDataString(qVal[1]));
}
return qDict;
}
public static string QueryGet(string url, string param)
{
var qDict = QueryParse(url);
return qDict[param];
}
}
Usage:
Statics.QueryGet(url, "id")
Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.
To get all Querystring values try this:
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
Dim sb As New StringBuilder("<br />")
For Each s As String In qscoll.AllKeys
Response.Write(s & " - " & qscoll(s) & "<br />")
Next s
var q = Request.QueryString;
NameValueCollection qscoll = HttpUtility.ParseQueryString(q.ToString());
I translate to C# version of josh-brown in VB
private System.Collections.Specialized.NameValueCollection ParseQueryString(Uri uri)
{
var result = new System.Collections.Specialized.NameValueCollection(4);
var query = uri.Query;
if (!String.IsNullOrEmpty(query))
{
var pairs = query.Substring(1).Split("&".ToCharArray());
foreach (var pair in pairs)
{
var parts = pair.Split("=".ToCharArray(), 2);
var name = System.Uri.UnescapeDataString(parts[0]);
var value = (parts.Length == 1) ? String.Empty : System.Uri.UnescapeDataString(parts[1]);
result.Add(name, value);
}
}
return result;
}
let search = window.location.search;
console.log(search);
let qString = search.substring(1);
while(qString.indexOf("+") !== -1)
qString = qString.replace("+", "");
let qArray = qString.split("&");
let values = [];
for(let i = 0; i < qArray.length; i++){
let pos = qArray[i].search("=");
let keyVal = qArray[i].substring(0, pos);
let dataVal = qArray[i].substring(pos + 1);
dataVal = decodeURIComponent(dataVal);
values[keyVal] = dataVal;
}
This is my code, I think it's very useful:
public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null )
{
System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (ItemToRemoveOrInsert != null)
{
filtered.Remove(ItemToRemoveOrInsert);
if (!string.IsNullOrWhiteSpace(InsertValue))
{
filtered.Add(ItemToRemoveOrInsert, InsertValue);
}
}
string StrQr = string.Join("&", filtered.AllKeys.Select(key => key + "=" + filtered[key]).ToArray());
if (!string.IsNullOrWhiteSpace(StrQr)){
StrQr="?" + StrQr;
}
return StrQr;
}
I have a url site.com/test.php which has the following code
<?php
$num1 = $_REQUEST['num1'] ;
$num2 = $_REQUEST['num2'] ;
$tot = $num1 + $num2 ;
?>
From an android application using POST/GET num1 and num2 parameters are passed to www.site.com/test.php
How can I make the response in such a way that the android application will be able to get the response from this request.
I tried this
header('Content-Type: application/json');
echo json_encode($response);
but all it does is echo it in the web view and im not able to get the response.Is there someway I can get the response as standard json response,which is not displayed but get it as soon as I hit the url as a response ?
** UPDATE **
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if(flag) {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// read inputstream to get the json..
...
...
return true;
}
return false
}
#override
public void onPageFinished (WebView view, String url) {
if (url contains "form.html") {
flag = true;
}
}
this is the java code I got from SO , which Im planning to use in the android appication
Seems to be a problem in the handling of the response, not the generation of the JSON. Are you clicking a link to the JSON on a page that is has "form.html" in it? Because that is what seems to be assumed in the code you posted.
It seems to be better to just overload the shouldOverrideUrlLoading and check if the url matches your json page. Something like this:
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if(url.toLowerCase().contains("www.site.com/test.php")) {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// read inputstream to get the json..
...
...
return true;
}
return false;
}
It might be a good idea to start an activity and load the JSON in that activity using, for example, an AsyncTask (network operations aren't allowed on the UI thread in the latest android APIs), instead of doing URL.openConnection immediately.
I have created and Android app that has to communicate with my website using JSON. JSON (on client, Android side) looks like this:
private static String JSONSend(Context ctx, JSONObject obj, String ObjName, String address) {
IHttpDispatcher disp = new HttpDispatcher();
Vector<String> ss = new Vector<String>();
String link = address;
String locale = uzmiLocale(ctx);
if(locale=="")
return "";
try {
obj.put("Lokal", locale);
ss.add(ObjName + obj.toString());
String ID = disp.getHttpResponse_POST(link, ss);
return ID;
} catch (Exception e) {
return "";
}
}
Above method is called from here:
public static String sendReq(Context ctx, String txt, String number) {
JSONObject jsn = new JSONObject();
try {
jsn.put("TextPoruke", txt);
jsn.put("BrTel", number);
return JSONSend(ctx, jsn, "JSNSend=", "www.mysite.com");
} catch (JSONException e1) {
return "";
}
}
Everything works fine on my Wamp server, but after moving my php code to webserver, nightmare started! Apparently, everything is sent the way it should be, but on serverside this php code is creating problems:
if(isset ($_POST['JSNSend']))
{
$argument = $_POST['JSNSend'];
$json = json_decode($argument,true);
$broj = $json['BrTel'];
$jsnLocale = $json['Lokal'];
it seems that result of "json_decode" is NULL, but $argument equals
{"\TextPoruke\": \"sometext\", \"BrTel\":\"111\"}
So passed JSON string seems ok, but for some reason it can't be decoded on webserver. Can anyone help me with this? Why is it not working?
Seems like your JSON got escaped prematurely which triggers a bad syntax error.
If $argument is in the format you state, then the following procedure would work:
<?php
$s = '{"\TextPoruke\": \"sometext\", \"BrTel\":\"111\"}';
echo 'Without stripslashes:' . PHP_EOL;
var_dump( json_decode( $s ) );
echo 'With stripslashes:' . PHP_EOL;
var_dump( json_decode( stripslashes($s) ) );
?>
Result:
Without stripslashes:
NULL
With stripslashes:
object(stdClass)#1 (2) {
["TextPoruke"]=>
string(8) "sometext"
["BrTel"]=>
string(3) "111"
}
Disable magic_quotes_gpc. This was a completely misguided ‘security’ feature that should never be used. It runs addslashes() on all user input, with the premise that this would solve SQL-injection problems (it doesn't).
If the server isn't yours and so you can't disable it, use the “Disabling magic quotes at runtime” hack on that link for now and consider moving to a new host.