**hello dear friends ,In my project i have an arraylist that filling from beacons data every second , is it possible to convert this arrayL to JSONArray and post it to an URL at the same time ??? **
'private ArrayList<Beacon> arrayL = new ArrayList<>();
#Override
public void onBeaconServiceConnect() {
iBeaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(final Collection<Beacon> iBeacons, Region region) {
runOnUiThread(new Runnable() {
#Override
public void run() {
arrayL.clear();
arrayL.addAll((ArrayList<Beacon>) iBeacons);
}
});
}
});'
enter image description here
You could try something like that:
1) Build the JSON object
ArrayList<Beacon> arrayL = new ArrayList<>();
JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));
2) Post to server
public void postData() {
ArrayList<String> arrayL = new ArrayList<>();
JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));
URL url = null;
try {
url = new URL("http://www.android.com/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
for(int i = 0; i < mJSONArray.length(); i++)
{
try {
JSONObject objects = mJSONArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Iterate through the elements of the array i.
//Get thier value.
//Get the value for the first element and the value for the last element.
}
JSONObject json = new JSONObject();
byte[] outputBytes = new byte[0];
try {
outputBytes = json.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
OutputStream os = null;
try {
os = connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.write(outputBytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Hope it helps.
Related
I am really struggling with this for some time now and I am really lost in terms of how this works.
I have written a REST service in netbeans and I have passed through Json data and tested that it works using Postman and it is successfully saving to the database.
Now, I want the variables in my mobile application to be sent to that REST api so that they can then be saved to the database.
I have looked at many answers on this but can get none which fully explain to me how to do this.. Ideally I am trying to POST or PUT data from my mobile app into my database.
Here is what I have tried so far:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
details = editTextDetails.getText().toString();
getCurrentDateandTime();
String url = "http://localhost:8080/engAppApi/webservices/engineerTable/";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
JSONObject params = new JSONObject();
try {
params.put("machinetype", machineType);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("workordernumber", workOrderNumber);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("employeename", employee);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("activity", activity);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationhours", durationHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationmins", durationMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimehours", downTimeHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimemins", downTimeMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("currentdateandtime", currentDateandTime);
} catch (JSONException e) {
e.printStackTrace();
}
StringEntity jsonEntity = null;
try {
jsonEntity = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
request.setEntity(jsonEntity);
try {
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
can someone please point me in the right direction
Thanks in advance!
just use retrofit 2 for connect to server.
see this link
You have an idea in how to do the post petition, but you have a couple of problems. The first and more important problem is that if you want to retrieve information from a server, you must put your code in an async task. You can't do it in UI Thread. So, i'm gonna share with you a class that implements all the logic you need and you just have to use it. First you need to use gson, look how to use it here
https://github.com/google/gson
and the code is here. It have two methods, one for GET and other for POST.
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrador on 4/27/2017.
*/
public class JsonReaderFromUrl {
public static final int SUCCESS = 0;
public static final int FAILED = 1;
public static final int PROGRESS = 2;
public interface OnJesonInterface{
void OnJsonReceive(int status, JSONObject jsonObject, int key);
}
public JsonReaderFromUrl() {
}
public void getJsonFromUrlPost(final String url, final OnJesonInterface onJesonInterface, final String body, final int key){
new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
if(android.os.Debug.isDebuggerConnected())
android.os.Debug.waitForDebugger();
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(body);
writer.flush();
writer.close();
outputStream.close();
connection.connect();
StringBuilder stringBuilder = new StringBuilder();
int httpStatus = connection.getResponseCode();
if (httpStatus == HttpURLConnection.HTTP_CREATED){
BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"utf-8")
);
String line = "";
while ((line = br.readLine()) != null){
stringBuilder.append(line + "\n");
}
br.close();
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,key);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
public void getJsonFromUrl(final String url, final OnJesonInterface onJesonInterface){
AsyncTask<Void,String,String> asyncTask = new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null){
stringBuffer.append(line + "\n");
Log.d("RESPONDE JSON: ",">" + line);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,0);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
}
import this class where you need and use it PD: The key value is an int that can be used to retrieve what response correspond to each petition, this in case you use this class with a lot of petitions.
Here is the code i had tried with multiple times to get multiple rows values in a single text view with json.
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("survey_textresponse"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hiding progress bar after done loading TextView.
progressbar.setVisibility(View.GONE);
}
}
}
when i run php file in chrome directly it shows all values from database while in android app it shows only the first row value.
Because you are only storing the last value of JSONobject in json reference
// assume JArray length = 5
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
// only have last object value , in last iteration jArray.getJSONObject(4)
}
There can be many solutions to this
Collect data as list of Values
Collect in a String or StringBuilder Object
StringBuilder sb = new StringBuilder();
// or List<String> list = new ArrayList<>();
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
sb.append(json.optString("survey_textresponse")+"\n");
// or list.add(json.optString("survey_textresponse"));
}
and later
textview.setText(sb.toString());
// or can collect list as string using loop and display it
The loop that you've written for retrieving the values from the JSONArray is not proper. Its only storing the last object while iterating through the loop. You could store the retrieved values in a collection of string.
Here's an example code you could follow:
private class RetrieveTask extends AsyncTask<Void,Void,Void>{
List<String> jsonResults;
String str;
JSONObject json;
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonResults=new ArrayList<>();
}
#Override
protected void onPostExecute(Void aVoid) {
for(String data:jsonResults)
textview.append(data);
}
#Override
protected Void doInBackground(Void... voids) {
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
if(json.optString("survey_textresponse")!=null){
jsonResults.add(json.getString("survey_textresponse"));
}
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Your json variable contains only last element of JsonArray when it is finished. You can display on TextView while retrieving your values from JsonArray.
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
textview.setText(textview.getText() + json.getString("survey_textresponse") + "\n");
}
I am calling a url to fetch data and insert in my database. I have provided a no internet check. If I open the app without internet connection, it works fins, a pop up comes.. But if I connect to the url when I have internet and the internet goes in middle the process, my app crashes, How to fix it?
My code:
public class DoPOSTPen extends AsyncTask<String, Void, Boolean> implements OnCancelListener {
#SuppressWarnings("deprecation")
#Override
protected Boolean doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://testapi.pharmeazy.in/api/MediEazy/GetAllInvoices");
request.addHeader("Authorization", " basic NDlyaWNva2pvaWQwM2ptZGlraWRES09qZGZpamRmNzY0dDA4NWp6MzcyOHdzMkpJS1M4MTA0c2NvcTJ1OTRkazphd0VEMzI3MkA4WWFzZEU3MjI3IUBeIypVSFMq");
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
System.out.println("PRIINTING");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream inputStream = response.getEntity().getContent();
String result = Utils.convertInputStreamToString(inputStream);
System.out.println("server response is :" + result + "\n" + inputStream);
try {
ja=new JSONArray(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (Exception e) {
Log.e("ClientServerDemo", "Error:", e);
toastText2 = "Connection Error !";
}
return true;
}
protected void onPreExecute() {
//display the progress dialog
mProgressHUD2 = ProgressHUD.show(Med.this,"Getting Rejected Orders", true,false,this);
}
#Override
protected void onPostExecute(Boolean valid) {
mProgressHUD2.dismiss();
// if server response is successful
for(int i=0;i<ja.length();i++){
try {
jo=ja.getJSONObject(i);
db.insertLabel(jo.get("Id").toString(), jo.get("CustomerId").toString(), jo.get("PharmacyId").toString(),
jo.get("DeliveryAddress").toString(), jo.get("DeliveryName").toString(),
jo.get("OrderStatus").toString(),jo.get("PrescriptionAttached").toString(),jo.get("Discount").toString());
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
new DoPOST3().execute();
}
Please help
why you don't go for httpurlconection
#Override
protected String doInBackground(String... params) {
String finalResult = null;
URL url = null;
HttpsURLConnection urlConnection = null;
try {
url=new URL(URL);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.connect();
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonObjSend.toString());
out.close();
starttime = System.currentTimeMillis();
try {
mResponseCode = urlConnection.getResponseCode();
totaltime = System.currentTimeMillis() - starttime;
Log.e("HTTP POST Response Code:", ""
+ mResponseCode);
} catch (SSLPeerUnverifiedException e) {
Log.e("Exception", Log.getStackTraceString(e));
} catch (IOException e) {
Log.e("Exception", Log.getStackTraceString(e));
Log.e("HTTP POST Response Code(2):", ""
+ mResponseCode);
}
}
check before calling asynctask
if(Util.haveNetworkConnection(this))
{
HttpPostData req=new HttpPostData(URL, createJsonObject(),this) ;
req.execute();
}
I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.
final String[] ar={"1","2","3",.............,"25"}
filename="test_file";
myFile = new File("/sdcard/"+filename);
try {
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
//
// // Read content & Log
// inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONObject jArray = new JSONObject(result);
String name = jArray.getString("name");
if (name!=null) {
Log.w("idname", name);
//
myOutWriter.append(name).append("\r\n");
//
Toast.makeText(getBaseContext(), name, 5).show();
}
// End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.
You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:
void onPostExecute(Void v) {
.....
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = taskCount.decrementAndGet()
if(count == 0 ) {
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // protected void onPostExecute(Void v)
the definition of taskCount is like this:
AtomicInteger taskCount = new AtomicInteger(ar.length - 1);
At last, I think Thread and CountDownLatch is better option
check if entity not null then write to db
HttpEntity entity = response.getEntity();
if(entity!=null ){
inputStream = entity.getContent();
}
Sir,,
I would like to try my application to test push-notification by typing this link below , but it comes to trying , there is no effect.Would you please tell me what is the correct format for the hyperlink to test my Application program ?
The below is my link
https://android.googleapis.com/gcm/send?registration_ids=
APA91bHhJQJGK1OJxYHcZeH81JoAprU97CAvMHQ58cHj3MYHD204MTn1W9Kl_i51UV8ej5qwLfkwvK-vihfuWjXG6iBvkUZJuclqoNbAjx_K2mN_P2ai4rI82P0dax_tm7NHc-k_1FsBn6hvwxjxxPdgMdtYpSIdwA
&data.message="hello testing"
collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "
You can actually test it from the Android device itself:
public class PushTester {
final static private String deviceId = "YOUR_DEVICE_ID";
final static private String apiId = "YOUR_API_ID";
final static private String sendUrl = "https://android.googleapis.com/gcm/send";
static void testPush() {
URL url;
HttpsURLConnection urlConnection;
OutputStream os = null;
InputStream is = null;;
try {
url = new URL(sendUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("User-Agent", "Android Push tester");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "key="+apiId);
JSONObject message = new JSONObject();
JSONArray regIds = new JSONArray();
JSONObject data = new JSONObject();
regIds.put(deviceId);
message.put("registration_ids", regIds);
//message.put("collapse_key", value)
data.put("something", "value");
message.put("data", data);
urlConnection.setDoOutput(true);
os = urlConnection.getOutputStream();
os.write(message.toString().getBytes());
os.flush();
int status = urlConnection.getResponseCode();
is = urlConnection.getInputStream();
byte[] response = new byte[4096];
is.read(response);
String responseText = String.valueOf(response);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
os = null;
is = null;
}
}
}