insert data to mssql with webservice from Android - android

my webservice codes here:
namespace AndWeb
{
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e1)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
List<Employee> eList = new List<Employee>();
string temp = "";
try
{
SqlConnection connection = new SqlConnection(
WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
connection.Open();
string query = "select * from AndLogin";
SqlCommand cmd = new SqlCommand(sorgu, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Employee e = new Employee();
e.ID = Convert.ToInt32(reader["ID"].ToString());
e.Name = reader["Name"].ToString();
e.SurName = reader["SurName"].ToString();
e.Password = reader["Password"].ToString();
eList.Add(e);
}
}
catch (Exception ex)
{
temp = "Hata : " + ex.Message;
}
string ans = JsonConvert.SerializeObject(eList, Newtonsoft.Json.Formatting.Indented);
temp = "{\"login\":" + ans + "}";
Response.Write(temp);
}
}
public class Employee
{
public int ID;
public string Name;
public string SurName;
public string Password;
}
}
webservice Json output is:
{"login":[ { "ID": 1112602055, "Name": "david", "SurName": "suarez", "Password": "****" }, { "ID": 1112602056, "Name": "damon", "SurName": "gomez", "Password": "****" }, { "ID": 1112602057, "Name": "kinsella", "SurName": "mark", "Password": "****" } ]}
i can read my datas from mssql with JSON but how can i insert data to sql from my android application??

There are many tutorials out there explaining how to execute a SQL statement from .Net
You should try reading some of them.
By the way, What you're showing is not a traditional .Net Webservice, it's a WebForm.
Your approach can still work, but your application would need to post data to the web form, same as the user clicking the submit button in a browser.
I don't want to go into too much detail, because I feel you should try and find the answer yourself, but
To insert the data, instead of calling
SqlDataReader reader = cmd.ExecuteReader();
You need to add parameters to your cmd object. Yyou should be able to read them from the Request.Form object if your post was successful.. i.e.
cmd.Parameters.Add("SomeName", Request.Form["SomeName"]);
you would then use
cmd.ExecuteNonReader();

Related

Couldn't get "name" value from json via Retrofit

I have a problem for getting "ad" value from mysql database.
Here is my listele.php code to get a json format including values.
<?php
//If the values are not blank
//Connecting to our database by calling dbConnect script
include('connection.php');
Class Kullanici{
public $id = "";
public $ad = "";
public $soyad = "";
}
$kl = new Kullanici();
$sql = "SELECT * FROM kullanici";
$list = mysqli_query($conn,$sql);
$resultFromSql = mysqli_num_rows($list);
$sayac = 0;
echo("[");
while($result = mysqli_fetch_assoc($list)){
$sayac = $sayac + 1;
$kl->id = $result["id"];
$kl->ad = $result["ad"];
$kl->soyad = $result["soyad"];
echo json_encode($kl,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
if($resultFromSql != $sayac){
echo(",");
}
}
echo("]");
?>
When I run the code snippet, I get the json format
[{ "id": "27", "ad": "Aslı", "soyad": "Şafak" },{ "id": "29", "ad": "Ali", "soyad": "Ak" },{ "id": "30", "ad": "Ersin", "soyad": "Demir" },{ "id": "31", "ad": "Sercan", "soyad": "Demirbaş" }]
When I get these values from json format to insert all them into the listview, "ad" value is null but others have their values.
kullanicilist = new ArrayList<>();
Call<List<Kullanici>> x = Manager.getInstance().goster();
x.enqueue(new Callback<List<Kullanici>>() {
#Override
public void onResponse(Call<List<Kullanici>> call, Response<List<Kullanici>> response) {
Log.i(LOG,"istek | onResponse is working");
if (response.isSuccessful()) {
kullanicilist = response.body();
Log.i(LOG,"istek | kullanicilist : " + kullanicilist.toString());
adp = new KullaniciAdapter(kullanicilist, getApplicationContext(), MainActivity.this);
listView.setAdapter(adp);
}
}
#Override
public void onFailure(Call<List<Kullanici>> call, Throwable t) {
Log.i(LOG,"istek | onFailure is working");
Log.i(LOG,t.getMessage());
}
});
First Log statement in onResponse
I/com.example.dbtojson.activity.MainActivity: istek | kullanicilist : [Kullanici{id='27', isim='null', soyad='Şafak'}, Kullanici{id='29', isim='null', soyad='Ak'}, Kullanici{id='30', isim='null', soyad='Demir'}, Kullanici{id='31', isim='null', soyad='Demirbaş'}]
Data you get from server is
{ "id": "27", "ad": "Aslı", "soyad": "Şafak" }
Data you are printing in retrofit client is
Kullanici{id='27', isim='null', soyad='Şafak'}
Server is sending value "Asli" in key name ad. Your client has member variable isim which is a different key name, that's why it is not getting mapped.
In client,
Change your member variable name from isim to ad
OR
if you are using GSON then put annotation above it.
#SerializedName("ad")
String isim
This will map value of key ad to isim

Getting element of JSON object when key isn't the same [Android]

I want to learn a bit more about android and wanted to create an app that will track the price of cryptocurrencies. I choosed this API: https://www.cryptocompare.com/api/#introduction
My problem is the following: When I want to get the list of all the coin the JSON response looks like this:
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"42": {
"Id": "4321",
"Url": "/coins/42/overview",
"ImageUrl": "/media/19984/42.png",
"Name": "42",
"CoinName": "42 Coin",
"FullName": "42 Coin (42)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"FullyPremined": "0",
"TotalCoinSupply": "42",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "34"
},
"365": {
"Id": "33639",
"Url": "/coins/365/overview",
"ImageUrl": "/media/352070/365.png",
"Name": "365",
"CoinName": "365Coin",
"FullName": "365Coin (365)",
"Algorithm": "X11",
"ProofType": "PoW/PoS",
"FullyPremined": "0",
"TotalCoinSupply": "2300000000",
"PreMinedValue": "299000000",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "916"
},
(here is the URL I use (https://www.cryptocompare.com/api/data/coinlist/)
I want to keep all the informations about the coin (everything from "Data") but the key isn't the same.
How can I get those informations to create my differents coins?
Thank's in advance
You can use JSONObject#names() to get all the keys as JSONArray and loop the JSONArray.
JSONObject data = response.getJSONObject("Data");
JSONArray array = data.names(); // contains all the keys inside Data
// now loop the array
for (int i = 0; i < array.length(); i++ ) {
String key = array.getString(i); // 42 or 365 for your example code
JSONObject obj = data.getJSONObject(key); // contains the JSONObject of the key 42 or 365
}
Another way is to use JSONObject#keys() but that uses Iterator and hasNext() for iteration which is less performance efficient than the above normal for loop approach in Android.
The accepted answer is fine. I would like to show the way of parsing using Gson from your JSON. Here's how it can be parsed using Gson.
You need to have two classes.
Here's your APIResponse.java
public class APIResponse {
public String Response;
public String Message;
public String BaseImageUrl;
public String BaseLinkUrl;
public HashMap<String, DataObject> Data;
}
And the DataResponse class should look like
public class DataObject {
public String Id;
public String Url;
public String ImageUrl;
public String Name;
public String CoinName;
public String FullName;
public String Algorithm;
public String ProofType;
public String FullyPremined;
public String TotalCoinSupply;
public String PreMinedValue;
public String TotalCoinsFreeFloat;
public String SortOrder;
}
Now its pretty easy.
Type type = new TypeToken<APIResponse>(){}.getType();
APIResponse response = new Gson().fromJson(yourJsonString, type);
Now iterate the HashMap for getting the keys and corresponding values.
You can fetch all the keys and iterate as below
try {
JSONObject dataObj = obj.getJSONObject("Data"); //obj is the parent json object.
Iterator<?> keys = dataObj.keys();
while(keys.hasNext()) {
JSONObject coinObj = dataObj.getJSONObject(keys.next().toString());
}
} catch (JSONException e) {
e.printStackTrace();
}

parse JSON response and add it into List

I've got problem with parsing JSON. I've got response from webservice like this :
{
   "data": {
      "1": [
         {
            "id": "2",
            "name": "Szelki bezpieczeństwa",
            "quantity": "1",
            "note": null,
            "picture_id": null,
            "code": "CCCCCCCCCCCCCC"
         },
         {
            "id": "3",
            "name": "Kalosze do brodzenia, wysokie lub biodrowe",
            "quantity": "2",
            "note": "Do wymiany",
            "picture_id": null,
            "code": "DDDDDDDDDDDDDD"
         }
      ],
      "2": [
         {
            "id": "1",
            "name": "Spodnie dla pilarza z ochroną przed przecięciem, klasa min. 1 (wg PN-EN 381-5)",
            "quantity": "2",
            "note": "Uszkodzone",
            "picture_id": null,
            "code": "DAAD086F690E1C36"
         }
      ]
   }
}
I try to parse it into PART object and add it to List but somewhere I'm making mistake because object is not being parsed.
public void onResponse(String response) {
Log.e(TAG, "onResponse WHOLE: " + response);
try {
JSONObject responseJSONObject = new JSONObject(response);
String arrayString = responseJSONObject.getJSONArray("data").toString();
JSONArray responseJSONArray = new JSONArray(arrayString);
Part tempCarEquipment;
int index = 1;
for (int i = 0; i < responseJSONArray.length(); i++,index++) {
JSONObject object = responseJSONArray.getJSONObject(index);
JSONArray response2 = object.getJSONArray(Integer.toString(index));
String id = object.getJSONObject(Integer.toString(i)).getString("id");
String name= object.getJSONObject(Integer.toString(i)).getString("name");
String quantity= object.getJSONObject(Integer.toString(i)).getString("quantity");
String picture_id= object.getJSONObject(Integer.toString(i)).getString("picture_id");
String code= object.getJSONObject(Integer.toString(i)).getString("code");
tempCarEquipment = new Part(name,quantity,"",picture_id,code,id,"",0);
wholeList.add(tempCarEquipment);
Log.e(TAG, "wholeList: " + wholeList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance fo every help! :)
JSON Parsing
You have to use the iterator for this kind of response
basic example of iterator is in this link.
You are trying to parse map as an array here:
String arrayString = responseJSONObject.getJSONArray("data").toString();
Try something like this instead:
List<JSONArray> objects = new ArrayList<>();
Iterator<String> keys = responseJSONObject.getJSONObject("data").keys();
while(keys.hasNext()) {
objects.add(responseJSONObject.getJSONObject("data").get(keys.next());
}
// rest of your stuff
Alternatively, consider using GSON to parse JSON responses using POJOs.

Nested Json parsing using Gson

I have tried to parse this JSON using gson but I couldn’t.
Can anyone help me to parse this JSON using gson?
JSON:
{
"status": "ok",
"results": {
"favourites": [
{
"id": "UB3172",
"name": "Masdar Headquarters"
},
{
"id": "UB1438",
"name": "Guggenheim Abu Dhabi on Saadiyat Island"
},
{
"id": "UB4838",
"name": "Watani Residential Development in Abu Dhabi - 600 Villas and 48 Buildings"
},
{
"id": "UB4795",
"name": "Two Mosques in Mohammed Bin Zayed City"
},
{
"id": "UB1274",
"name": "2 Workers Residential City at Al Ain Industrial City"
}
]
}
}
I tried this one for JSON parser class:
public class ProjectList {
public String status;
public String results;
public class Favourites{
public String id;
public String name;
}
}
In MainActivit
Reader reader = new InputStreamReader(result);
Gson gson=new Gson();
List<ProjectList.Favourites> fav=new ArrayList<ProjectList.Favourites>();
fav=Arrays.asList(gson.fromJson(reader, ProjectList.Favourites.class));
Create a POJO class as follows
class MyResponse {
public String status;
public Result results;
public static class Favourites {
public String id;
public String name;
}
public static class Result {
public List<Favourites> favourites;
}
}
and pass it to gson as
MyResponse response = new Gson().fromJson(yourResponse, MyResponse.class);
idea is that maintain the hierarchy of key-value pairs with appropriate POJO's
You can generate your pojos here : http://www.jsonschema2pojo.org/
Sometimes gson cannot convert your objects from json. In this case you have to write your own deserializer and use it with gson builder.
Edit: If you use proguard before release your project (if you set proguard to change your pojos variable names) gson cannot match class variable names, json names so it cannot convert your objects. You have to add #SerializedName("your_variable_name") annotaion.
Try this way,hope this will help you to solve your problem.
String jsonRespone = "{\"status\":\"ok\",\"results\":{\"favourites\":[{\"id\":\"UB3172\",\"name\":\"Masdar Headquarters\"},{\"id\":\"UB1438\",\"name\":\"Guggenheim Abu Dhabi on Saadiyat Island\"},{\"id\":\"UB4838\",\"name\":\"Watani Residential Development in Abu Dhabi - 600 Villas and 48 Buildings\"},{\"id\":\"UB4795\",\"name\":\"Two Mosques in Mohammed Bin Zayed City\"},{\"id\":\"UB1274\",\"name\":\"2 Workers Residential City at Al Ain Industrial City\"}]}}";
String status;
ArrayList<HashMap<String,String>> favouritesList = new ArrayList<HashMap<String, String>>();
try{
JSONObject responseJson = new JSONObject(jsonRespone);
status = responseJson.getString("status");
JSONArray favouriteJsonArray = responseJson.getJSONObject("results").getJSONArray("favourites");
for (int i=0;i<favouriteJsonArray.length();i++){
HashMap<String,String> favourite = new HashMap<String, String>();
favourite.put("id",favouriteJsonArray.getJSONObject(i).getString("id"));
favourite.put("name",favouriteJsonArray.getJSONObject(i).getString("name"));
favouritesList.add(favourite);
}
System.out.print("status : "+status);
for (HashMap<String, String> favourite : favouritesList) {
System.out.print("id : "+favourite.get("id"));
System.out.print("name : "+favourite.get("name"));
}
}catch (Throwable e){
e.printStackTrace();
}

Phrasing Json Array using Gson for google search api

First of all Sorry for the really long post, now
And this is my class structure, no idea if it's right or wrong
public class GoogleResponse {
public ResponseDate responseData;
public String responseDetails;
public String responseStatus;
}
public class ResponseData {
public List<Result> results;
//public Cursor cursor;
}
public class Result {
public String titleNoFormatting;
public String unescapedUrl;
}
And this is the code for deserialization
Gson gson = new Gson();
GoogleResponse data[] = gson.fromJson(s, GoogleResponse[].class);\\s is the JSON string
In this program i just want to extract titlenoformating and unescapedurl, that's why i left out rest of the content from the class's.
I don't know if this is right or wrong, but when i do System.out.print(data);
I get nothing in logcat, i don't know how to access the data that is stored in data[].
What i want is to populate a listview using the titleNoFormating and open the corresponding unescapedurl on clicking any results via intent.
EDIT:
{
"results": [
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.mediafire.com/?zcnqy5mmwmj",
"url": "http://www.mediafire.com/%3Fzcnqy5mmwmj",
"visibleUrl": "www.mediafire.com",
"cacheUrl": "http://www.google.com/search?q=cache:f6cE2lmmCioJ:www.mediafire.com",
"title": "Redman Funk From <b>Hell</b> 2010.zip",
"titleNoFormatting": "Redman Funk From Hell 2010.zip",
"content": "Redman Funk From <b>Hell</b> 2010.zip. <b>...</b> Share “Redman Funk From <b>Hell</b> 2010.zip”. Info . Facebook/Twitter. Email. Share by IM. Embed. HTML Embed Code. Sharing URL <b>...</b>",
"clicktrackUrl": "//www.google.com/url?q=http://www.mediafire.com/?zcnqy5mmwmj&sa=T&usg=AFQjCNGhKqruZDyj614zfvjuitABOJFrNQ&ei=BUQdTtbGLeWTmQWElOHzBw&ved=0CAQQFjAA"
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.mediafire.com/?ymto5mjznwz",
"url": "http://www.mediafire.com/%3Fymto5mjznwz",
"visibleUrl": "www.mediafire.com",
"cacheUrl": "http://www.google.com/search?q=cache:aXARYHERXiQJ:www.mediafire.com",
"title": "This Routine is <b>Hell</b> - The Verve Crusade.zip - This, Routine, is <b>...</b>",
"titleNoFormatting": "This Routine is Hell - The Verve Crusade.zip - This, Routine, is ...",
"content": "Debut full-length The Verve Crusade by hardcore punk band This Routine is <b>Hell</b> from the Netherlands. Released by Shield Recordings in 2010.",
"clicktrackUrl": "//www.google.com/url?q=http://www.mediafire.com/?ymto5mjznwz&sa=T&usg=AFQjCNGd4xVGQkOlb8TMCdpH5tEIn2Ln5A&ei=BUQdTtbGLeWTmQWElOHzBw&ved=0CAYQFjAB"
}
]
}
This becomes valid so i guess i'll have to make up mu own method to get out this content
when i do System.out.print(data); I get nothing in logcat
Use android.util.Log.(), not System.out.println();
Concerning parsing the JSON, unfortunately the JSON listed in the original question is invalid, which leaves folks that might help guessing a bit. And the example JSON on Google's own search API documentation page is also invalid (though in a different way) -- it escapes the '[' and ']' characters, but the JSON spec does not allow those characters to be escaped.
Following is a corrected version of the example JSON from the Google search API documentation.
{
"responseData": {
"results": [
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://en.wikipedia.org/wiki/Paris_Hilton",
"url": "http://en.wikipedia.org/wiki/Paris_Hilton",
"visibleUrl": "en.wikipedia.org",
"cacheUrl": "http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org",
"title": "<b>Paris Hilton</b> - Wikipedia, the free encyclopedia",
"titleNoFormatting": "Paris Hilton - Wikipedia, the free encyclopedia",
"content": "[1] In 2006, she released her debut album..."
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.imdb.com/name/nm0385296/",
"url": "http://www.imdb.com/name/nm0385296/",
"visibleUrl": "www.imdb.com",
"cacheUrl": "http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com",
"title": "<b>Paris Hilton</b>",
"titleNoFormatting": "Paris Hilton",
"content": "Self: Zoolander. Socialite <b>Paris Hilton</b>..."
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
},
{
"start": "8",
"label": 3
},
{
"start": "12",
"label": 4
}
],
"estimatedResultCount": "59600000",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/search?oe=utf8&ie=utf8..."
}
},
"responseDetails": null,
"responseStatus": 200
}
And here is an example program using Gson to deserialize this JSON to a Java data structure, and then retrieving the two target data elements.
import java.io.FileReader;
import java.math.BigInteger;
import java.util.List;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
Response response = gson.fromJson(new FileReader("input.json"), Response.class);
for (Result result : response.responseData.results)
{
System.out.println("titleNoFormatting: " + result.titleNoFormatting);
System.out.println("unescapedUrl: " + result.unescapedUrl);
}
// output:
// titleNoFormatting: Paris Hilton - Wikipedia, the free encyclopedia
// unescapedUrl: http://en.wikipedia.org/wiki/Paris_Hilton
// titleNoFormatting: Paris Hilton
// unescapedUrl: http://www.imdb.com/name/nm0385296/
}
}
class Response
{
ResponseData responseData;
String responseDetails;
int responseStatus;
}
class ResponseData
{
List<Result> results;
Cursor cursor;
}
class Result
{
String GsearchResultClass;
String unescapedUrl;
String url;
String visibleUrl;
String cacheUrl;
String title;
String titleNoFormatting;
String content;
}
class Cursor
{
List<Page> pages;
BigInteger estimatedResultCount;
int currentPageIndex;
String moreResultsUrl;
}
class Page
{
int start;
int label;
}

Categories

Resources