I am not very familiar with Android app Development.
In my previous app, I had used SOAP to connect android app with SQL Server using Asp.NET webservice. But then, I came to know that JSON would be the best method because of its parsing capabilities and many other advantages. I found many samples of code but they were all using PHP, whereas I am using asp.net.
Can anyone please help me to solve the problem?
Asp.NET Webservice Code :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCity()
{
DAL dal = new DAL();
try
{
List<City> lstCity = new List<City>();
DataTable dt = dal.GetDataTable("Select CityId, CityName from tblCity", "TEXT");
for (int i = 0; i < dt.Rows.Count; i++)
{
City and = new City();
and.CityId = Convert.ToInt64(dt.Rows[i]["CityId"].ToString());
and.CityName = dt.Rows[i]["CityName"].ToString();
lstCity.Insert(i, and);
}
JavaScriptSerializer jsCity = new JavaScriptSerializer();
return jsCity.Serialize(lstCity);
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
Android App Code:
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
tv.setText("");
for (int i = 0; i < cityList.size(); i++) {
lables.add(cityList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFood.setAdapter(spinnerAdapter);
}
private class GetCities extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CityData.this);
pDialog.setMessage("Fetching Cities..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
ServiceHandler sh = new ServiceHandler();
String json = sh
.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray cities = jsonObj.getJSONArray("GetCity");
for (int i = 0; i < cities.length(); i++) {
JSONObject catObj = (JSONObject) cities.get(i);
City cat = new City(catObj.getInt("CityId"),
catObj.getString("CityName"));
cityList.add(cat);
}
}
} catch (JSONException e) {
// e.printStackTrace();
result = e.getMessage().toString();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
tv.setText(result);
}
}
I am getting Error Value html of type java.lang.String cannot be converted to JSONObject
you need to using asp.net web services and converting your data in json format and from android code you will request the service data
try this example
http://osmosee.wordpress.com/2013/07/20/calling-a-json-based-asp-net-web-service-from-an-android-phone/
Related
I am practicing the consumption of a web service made in soap from xamarin, but I am having problems when trying to consume the service, because what I want to do is obtain its return values, both the id and another value, but at the moment of receiving the y values read them in a para, the id is just the position of the array, but not the value I need.
This is my stored procedure:
IF #Action = 1 --Traer Surtidor
BEGIN
SELECT
Id_Surtidor,
Numero_Surtidor
FROM
Bit_V3.dbo.Surtidores
WHERE
Id_Eds = #Id_Eds
END
This is my service:
[WebMethod]
public DataTable SpinnerSurtidorConsulta(string id_eds)
{
try
{
DataTable Dt;
DCL.Apertura_Combustible Consumible = new DCL.Apertura_Combustible();
Consumible.Id_Eds = id_eds;
Dt = Apertura_Combustible_BLR.SelectTable(Consumible, 1);
return Dt;
}
catch (Exception Op)
{
throw Op;
}
}
This is my archive.cs:
ServicesConsultas.ServiceCombustible proxy = new ServicesConsultas.ServiceCombustible();
proxy.SpinnerSurtidorConsultaCompleted += Proxy_SpinnerSurtidorConsultaCompleted;
var ta = 2;
proxy.SpinnerSurtidorConsultaAsync(ta.ToString());
Dictionary<int, string> dict_surtidor = new Dictionary<int, string>();
private void Proxy_SpinnerSurtidorConsultaCompleted(object sender, ServicesConsultas.SpinnerSurtidorConsultaCompletedEventArgs e)
{
dtb = e.Result;
if (dtb.Rows.Count > 0)
{
dict_surtidor.Clear();
for (int i = 0; i < dtb.Rows.Count; i++)
{
dict_surtidor.Add(Convert.ToInt32(dtb.Rows[i][0].ToString()), dtb.Rows[i][1].ToString());
}
}
ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, dict_surtidor.Values.ToArray());
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spinner2.Adapter = adapter;
spinner2.ItemSelected += Spinner2_ItemSelected;
}
I'm facing an exception in the business layer at line:
PeriodicConsumptionItemRepository.Save();
I'm not able to save my data to database. This is my code:
public HttpResponseMessage Post(PeriodicConsumption value)
{
int result = 1;
PeriodicConsumption objPeriodicConsumption = new PeriodicConsumption();
using (var uof = new UnitOfWork())
{
try
{
uof.StartTransaction();
PeriodiConsumptionRepository.Insert(value);
PeriodiConsumptionRepository.Save();
int IPeriodicConsumptionId = PeriodiConsumptionRepository.GetAllData().ToList().Last().Id;
foreach (PeriodicConsumptionItem objPeriodicConsumptionItem in value.PeriodicConsumptionItems)
{
PeriodicConsumptionItem ObjPeriodicConsumptionItem = new PeriodicConsumptionItem();
ObjPeriodicConsumptionItem.Consumption = objPeriodicConsumptionItem.Consumption;
ObjPeriodicConsumptionItem.Cost = objPeriodicConsumptionItem.Cost;
ObjPeriodicConsumptionItem.InventoryItemId = objPeriodicConsumptionItem.InventoryItemId;
ObjPeriodicConsumptionItem.PeriodicConsumptionId = IPeriodicConsumptionId;
PeriodicConsumptionItemRepository.Insert(ObjPeriodicConsumptionItem);
PeriodicConsumptionItemRepository.Save();
result = 1;
}
}
catch (Exception ex)
{
uof.RollBackTransaction();
ErrorLog.ErrorLogging(ex);
result = 0;
}
uof.CommitTransaction();
}
return result;
}
I have a function that saves multiple clients one client at a time. I am struggling to create and populate one of the parameters IEnumerable with string type client properties: clientKey , clientName, and clientTypeCode
public void SaveMultipleClients(IEnumerable<IClient> clients, TransactionMetadata metadata)
{
try
{
if (clients == null)
{
throw new ArgumentNullException("clients");
}
var abstractClients = clients.ToList();
var concreteClients = new List<Client>();
for (int i = 0; i < abstractClients.Count; i++)
{
concreteClients.Add(abstractClients[i].ToConcreteType<IClient, Client>());
var cleanClients = this.RemoveErroneousClient(concreteClients[i]);
foreach (var client in cleanClients)
{
this.SaveClient(client, metadata);
}
}
this.SavePending(concreteClients, metadata);
}
catch (Exception e)
{
throw e.WrapException();
}
}
Thanks in advance for the help!
I was able to instantiate and populate a list of clients and passed it to the clients parameter.
var myClientsList = new List<IClient>();
myClientsList.Add(individualClient);
myClientsList.Add(individualClient1);
var clients = clientDataManager.SaveMultipleClientsOneAtATime(myClientsList, new TransactionMetadata(DateTime.UtcNow));
This code is showing the address on a google maps sending the address text to an url and then retrieving it in a Json object, Is there a way to transalate this code to Monodroid using Httppost from apache libraries or not?
public class MapsActivity extends MapActivity {
Geocoder geocoder = null;
MapView mapView = null;
ProgressDialog progDialog = null;
List<Address> addressList = null;
double latitude;
double longitude;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.geoMap);
progDialog = ProgressDialog.show(MapsActivity.this, "Processing...",
"Finding Location...", true, false);
TextView txtAddress = (TextView)findViewById(R.id.location);
String locationName = "Av. Venezuela 1234 Lima Peru";
txtAddress.setText(locationName);
JSONObject location = getLocationInfo(locationName);
Boolean bool = getLatLong(location);
if(location!=null && bool != false){
int lat = (int) (latitude * 1000000);
int lng = (int) (longitude * 1000000);
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(16);
mapView.getController().setCenter(pt);
mapView.getController().animateTo(pt);
}else {
Dialog foundNothingDlg = new AlertDialog.Builder(
MapsActivity.this).setIcon(0)
.setTitle("Failed to Find Location")
.setPositiveButton("Ok", null)
.setMessage("Location Not Found...").create();
foundNothingDlg.show();
}
}
public JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
Log.i("JSONOBJECT: ", stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public boolean getLatLong(JSONObject jsonObject) {
try {
longitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
progDialog.dismiss();
return true;
}
}
HttpPost isn't bound, and it's currently very hard to bind your own Java libraries.
The easiest way to do this would be to use the equivalent .NET classes, like HttpWebRequest or WebClient.
I am trying to fetch json data in android application using REST services of c#. it is throwing an error:
org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
I have searched on SO in previous question but couldn't find any useful.
What I have tried is:-
In c#
public DataTable TestCheckEgrasUserLogin()
{
DataTable dt = new DataTable();
GenralFunction gf = new GenralFunction();
SqlParameter[] PM = new SqlParameter[2];
PM[0] = new SqlParameter("#UserName", SqlDbType.VarChar, 50) { Value = UserName };
PM[1] = new SqlParameter("#Password", SqlDbType.VarChar, 50) { Value = Password };
dt = gf.Filldatatablevalue(PM, "TestegAndroidUserLoginInfo", dt, null);
return dt;
}
I have tested it by running in visual studio, it is working fine and bringing data.
In android:-
public class MainActivity extends Activity {
private final static String SERVICE_URI = "`serviceUrl`";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try
{
final EditText usernametxt = (EditText) findViewById(R.id.txtUser);
final EditText passwordtxt = (EditText) findViewById(R.id.txtPassword);
String username;
String Password;
username=usernametxt.getText().toString();
Password=passwordtxt.getText().toString();
if(username=="" || Password=="")
{
MessageBox("Please Enter UserName or Password");
}
else if (username.length()<1 || Password.length()<1)
{
MessageBox("Please Enter Credential Details");
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
final HttpGet request = new HttpGet(SERVICE_URI+username+"/Password/"+Password);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type","application/json; charset=utf-8");
final DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
final HttpResponse response = httpClient.execute(request);
final HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
String tmpStr10 = String.valueOf(buffer.length);
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
int sizeOfJSONFile = stream.available();
reader.read(buffer);
stream.close();
JSONObject vehicle = new JSONObject(new String(buffer)); ** /////Error Comes here**
JSONArray plates=new JSONArray(vehicle.getString("CheckEgrasLoginResult"));
Bundle B=new Bundle();
String UserName= null;
String UserId =null;
Intent i = new Intent(getApplicationContext(), com.example.nic.newdemosecond.detailsact.class);
for (int j = 0; j < plates.length(); ++j) {
JSONObject Veh = new JSONObject(plates.getString(j));
UserName = Veh.getString("UserName");
UserId = Veh.getString("UserId");
}
i.putExtra("UserName", UserName);
i.putExtra("UserId", UserId);
startActivity(i);
}
catch (Exception e)
{
MessageBox("Invalid Login");
}
}
}) ;
}
error is coming at where I declared JsonObject. As I am newbie on android, I am unable to catch this error.
Any help would be appreciated !
HttpClient, DefaultHttpClient are deprecated they drain battery, more bandwidth in android. use HttpURLConnection instead follow this tutorial http://terrapinssky.blogspot.in/2015/10/android-get-and-parse-json-file-from.html
You have to return Json instead of XML by using JavaScriptSerializer like shown here
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
and at last return Json like,
return serializer.Serialize(rows);
NOTE: see this answer for details, and modify this as required.