android: how to convert gps coordinates and send it to mysql server using post method - http-post

I'm trying to send data in my php server, but the data is in latitude and longitude format.
Here's the error: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
private class sendlocation extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... args0)
{
double latlat = gps.getLatitude();
double longlong = gps.getLongitude();
String resultlat = Double.toString(latlat);
String resultlong = Double.toString(longlong);
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("Latitude",resultlat));
params.add(new BasicNameValuePair("Longitude",resultlong));
JSONObject json = jsonParser.makeHttpRequest(url_send_loc,"POST", params);
Log.d("Create Response", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if(success == 1)
{
Toast.makeText(getApplicationContext(),"Location Successfully sent: \nLat "+resultlat+" nLong" + resultlong ,Toast.LENGTH_LONG).show();
}
else
{ pdialog.dismiss();
Toast.makeText(getApplicationContext(), "Unknown error! Location not sent", Toast.LENGTH_LONG).show();
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
};
}

Related

loopj JsonObject with inside JsonArray JsonObjects

I have a Webservice which give me back this:
{"result":[{"Id":"20","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:19:42"},{"Id":"21","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:34:42"},{"Id":"22","temperatura":"35","humedad":"28","Insertado":"2016-07-01 12:49:43"},{"Id":"23","temperatura":"35","humedad":"19","Insertado":"2016-07-01 13:29:06"},{"Id":"24","temperatura":"31","humedad":"18","Insertado":"2016-07-01 13:44:07"},{"Id":"25","temperatura":"33","humedad":"16","Insertado":"2016-07-01 13:59:10"}]}
This is an Object, which has and Array, and the array has many objects.
Here is my code. I am using loopj library-
private void CaptarParametros(String idObjeto) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(UtilitiesGlobal.SENSOR_ID, idObjeto);
RequestHandle post = client.post(this, SENSORS_URL, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// called when response HTTP status is "200 OK"
JSONObject jsonobject = null;
JSONObject dht11JSONbject = null;
JSONArray dht11JSONarray = null;
try {
jsonobject = new JSONObject(String.valueOf(response));
dht11JSONbject = jsonobject.getJSONObject("result");
dht11JSONarray = new JSONArray(dht11JSONbject);
JSONArray dht11 = dht11JSONarray.getJSONArray(0);
for (int i = 0; i < dht11JSONarray.length(); i++) {
JSONObject item = dht11.getJSONObject(i);
String temperatura = item.getString("temperatura");
String humedad = item.getString("temperatura");
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + temperatura + humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get error like this:
org.json.JSONException: Value [{"Id":"19","temperatura":"35","humedad":"16","Insertado":"2016-07-01 12:19:24"}] at result of type org.json.JSONArray cannot be converted to JSONObject
I would appreciate any help.- I need to extract "temperature" and humedad" in separate arrays since later I have to use it in MPAndroidChat to make tow linechart, one chart for one set of parameters and another one for other parameters.
Solution is here:
try {
jsonobject = new JSONObject(String.valueOf(response));
//dht11JSONbject = jsonobject.getJSONObject("result");
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonobject.getJSONArray("result");
for (int i=0; i<cast.length(); i++) {
JSONObject parametrosdht11 = cast.getJSONObject(i);
String temperatura = parametrosdht11.getString("temperatura");
String humedad = parametrosdht11.getString("humedad");
allNames.add(temperatura);
allNames.add(humedad);
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " +"temperatura: "+ temperatura +" humedad: " +humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
We have a String with many sub_objects, then we have to put them into an array or List.
Take the solution from:
how to parse JSONArray in android

Android Asynctask return problems

I am facing a problem in value 'return' in Asynctask class in doInBackground method. I am getting an error, about 'missing return statement in below code.
`public class ForecastNetwork extends AsyncTask {
public final String TAG = ForecastNetwork.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}`
What Should I return at the end?
I assume that you forgot to return the processing result
forecastJsonStr = buffer.toString();
return forecastJsonStr;

Xamarin http webservice issue

I m trying to use http request webservice issue is that when we post wrong username and password the login service generate exception and it can't return any value in async calls.
A code snippet would help assist with the problem ...
However using a try catch should help you catch your exception and prevent application from crashing and handling the exceptions accordingly.
As seen in my sample code below I cater for the incorrect details entered / connectivity problems. I peform the http async request then parse the xml to my model handling the exceptions accordingly
var response = await WebRequestHelper.MakeAsyncRequest(url, content);
if (response.IsSuccessStatusCode == true)
{
Debug.WriteLine("Login Successfull" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
var result = response.Content.ReadAsStringAsync().Result;
result = result.Replace("<xml>", "<LoginResult>").Replace("</xml>", "</LoginResult>");
loginResult = XMLHelper.FromXml<LoginResult>(result);
if (loginResult != null)
{
login.Type = ResultType.OK;
login.Result = loginResult;
}
else
{
login.Type = ResultType.WrongDetails;
}
}
else
{
Debug.WriteLine("Login Failed" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
login.Type = ResultType.WrongDetails;
}
}
catch (Exception ex)
{
login.Type = ResultType.ConnectivityProblem;
}
Web Request
public static async Task<HttpResponseMessage> MakeAsyncRequest(string url, Dictionary<string, string> content)
{
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 5, 0);
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");
if (content == null)
{
content = new Dictionary<string, string>();
}
var encodedContent = new FormUrlEncodedContent(content);
var result = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);
return result;
I would recommend wrapping the response in a generic ServiceResponse where you can store the exceptions. await methods can be included in try/catch blocks so the standard process can be followed.
E.G.
public async Task<ServiceResponse<T>> PostAsync<T>(String address, object dto){
var content = Serializer.SerializeObject (dto);
var response = await client.PostAsync (
address,
new StringContent (content));
if (response.IsSuccessStatusCode) {
try {
var responseString = await response.Content.ReadAsStringAsync ();
return new ServiceResponse<T> (Serializer.DeserializeObject<T> (responseString),
response.StatusCode);
} catch (Exception ex) {
return new ServiceResponse<T> (response.StatusCode, ex);
}
} else {
return new ServiceResponse<T> (response.StatusCode);
}
}
With the ServiceResponse defined as :
public class ServiceResponse<T>
{
public HttpStatusCode StatusCode { get; set;}
public T Value { get; set;}
public String Content { get; set;}
public Exception Error {get;set;}
public ServiceResponse(T value, HttpStatusCode httpStatusCode){
this.Value = value;
this.StatusCode = httpStatusCode;
}
public ServiceResponse(HttpStatusCode httpStatusCode, Exception error = null){
this.StatusCode = httpStatusCode;
this.Error = error;
}
}
This will give you a clean way of managing all your HTTP responses and any errors that may occur.

Birt Report not opening in PDF

Hello guys
I am sending my form values to controller and controller to rptdesign file my it is generating the report in temp folder with proper value but my requirement is that it should user to save or open dialog so that user can save the report or open
i think ajax request will not allow to download any file so if some one know to better solution plz reply
my controller is below
#RequestMapping("/leave/generateEmpLeaveReport.json")
public void generateEmployeeLeaveReport(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String reportName = "D:/git-repositories/cougar_leave/src/java/com//report/myLeaveSummary.rptdesign";
File designTemplateFile = new File(reportName);
if (!designTemplateFile.exists()) {
throw new FileNotFoundException(reportName);
}
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("empId", NumberUtils.toInt(request.getParameter("id")));
parameters.put("reportTitle", "EMPLOYEE LEAVE");
parameters.put("fromDate", request.getParameter("fromDate"));
parameters.put("toDate", request.getParameter("toDate"));
parameters.put("leaveType",
NumberUtils.toInt(request.getParameter("leaveType")));
parameters.put("transactionType",
NumberUtils.toInt(request.getParameter("transactionType")));
reportManager.addSystemParams(parameters, null,
RequestUtils.getUser(request));
File file = null;
try {
ReportType reportType = ReportType.PDF;
OfflineReportContext reportContext = new OfflineReportContext(
reportName, reportType, parameters, null,
"EMPLOYEE LEAVE SUMMARY");
StringBuffer buffer = new StringBuffer();
file = offlineReportGenerator.generateReportFile(reportContext,
buffer);
ControllerUtils
.openFile(file.getParent(), response, file.getName());
} catch (Exception e) {
log.error(e, e);
} finally {
if (file != null && file.exists()) {
file.canExecute();
}
}
}
my ajax request is below
generateReport : function() {
if (this.form.valid()) {
fromDate = new Date($("input[name='fromDate']").val())
toDate = new Date($("input[name='toDate']").val())
if (fromDate > toDate) {
GtsJQuery
.showError("To date should be greater or equals than From date !")
} else {
var request = GtsJQuery.ajax3(GtsJQuery.getContextPath()
+ '/leave/generateEmpLeaveReport.json', {
data : {
id : $("input[name='employeeId']").val(),
fromDate : $("input[name='fromDate']")
.val(),
toDate : $("input[name='toDate']").val(),
leaveType : $("select[name='leaveType']")
.val(),
transactionType : $("select[name='transactionType']")
.val(),
orderBy : $("select[name='orderBy']").val()
}
});
request.success(this.callback("onSubscribeSuccess"))
}
}
},
The controller response should be the temp file itself, just adjust the content-type.

WP7 - POST form with an image

I need to send an image from the Windows Phone 7 to some e-mail addresses.
I use this class to submit text values to a PHP script, wich parses data and sends a formatted e-mail to the addresses.
The problem is that I can't figure out how to send an image to that script, to attach the image to the e-mail. The PHP script can be changed in any way. If I have an Image object, how can I change this class to allow sending images?
public class PostSubmitter
{
public string url { get; set; }
public Dictionary<string, string> parameters { get; set; }
public PostSubmitter() { }
public void Submit()
{
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Prepare Parameters String
string parametersString = "";
foreach (KeyValuePair<string, string> parameter in parameters)
{
parametersString = parametersString + (parametersString != "" ? "&" : "") + string.Format("{0}={1}", parameter.Key, parameter.Value);
}
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(parametersString);
// Write to the request stream.
postStream.Write(byteArray, 0, parametersString.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
//Action<string> act = new Action<string>(DisplayResponse);
//this.Dispatcher.BeginInvoke(act, responseString);
}
I use the class in this way:
Dictionary<string, string> data = new Dictionary<string, string>()
{
{"nom", nom.Text},
{"cognoms", cognoms.Text},
{"email", email.Text},
{"telefon", telefon.Text}
};
PostSubmitter post = new PostSubmitter() { url = "http://example.com/parserscript.php", parameters = data };
post.Submit();
Thank you very much!
I've converted the above code to the following, I'm sure it will help:
public class PostSubmitter
{
public string url { get; set; }
public Dictionary<string, object> parameters { get; set; }
string boundary = "----------" + DateTime.Now.Ticks.ToString();
public PostSubmitter() { }
public void Submit()
{
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
myRequest.Method = "POST";
myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
writeMultipartObject(postStream, parameters);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
public void writeMultipartObject(Stream stream, object data)
{
StreamWriter writer = new StreamWriter(stream);
if (data != null)
{
foreach (var entry in data as Dictionary<string, object>)
{
WriteEntry(writer, entry.Key, entry.Value);
}
}
writer.Write("--");
writer.Write(boundary);
writer.WriteLine("--");
writer.Flush();
}
private void WriteEntry(StreamWriter writer, string key, object value)
{
if (value != null)
{
writer.Write("--");
writer.WriteLine(boundary);
if (value is byte[])
{
byte[] ba = value as byte[];
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg");
writer.WriteLine(#"Content-Type: application/octet-stream");
//writer.WriteLine(#"Content-Type: image / jpeg");
writer.WriteLine(#"Content-Length: " + ba.Length);
writer.WriteLine();
writer.Flush();
Stream output = writer.BaseStream;
output.Write(ba, 0, ba.Length);
output.Flush();
writer.WriteLine();
}
else
{
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""", key);
writer.WriteLine();
writer.WriteLine(value.ToString());
}
}
}
}
To convert an image from the camera to an byte array I've used the follwing:
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
try
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
foto.Source = image;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(image);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, image.PixelHeight, 0, 100);
byteArray = ms.ToArray();
}
}
catch (ArgumentNullException) { /* Nothing */ }
}
And I use the class this way:
Dictionary<string, object> data = new Dictionary<string, object>()
{
{"nom", nom.Text},
{"cognoms", cognoms.Text},
{"email", email.Text},
{"telefon", telefon.Text},
{"comentari", comentari.Text},
{"foto", byteArray},
};
PostSubmitter post = new PostSubmitter() { url = "http://example.com/parserscript.php", parameters = data};
post.Submit();
I don't know if it's the best way to send an image from the phone to a server, but I couldn't find anything, so I made my own class just reading this and that, and it has taken me several days. If anybody wants to improve the code or write any comment will be welcomed.
There are lots of questions/answers on here to help already
e.g.
Post with WebRequest - although i couldn't spot any specifically for photos.
Perhaps the best way is to use something like Hammock on Codeplex - http://hammock.codeplex.com/ - or perhaps something like RESTSharp - http://restsharp.org/ - they provide standard REST POST functions.
e.g. if you look within Hammock, then you'll find others who've posted images direct from the camera to tumblr - see http://hammock.codeplex.com/discussions/235650
The above code works perfect. I just use a different method to convert the file to an array of bytes which works perfect with Audio
public static class FileHelper
{
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
}

Resources