I'm trying search a beacon device and get the Majoy & Minor, then send the data to request, but I got the problems is I don't know how to send the data between the two part ..
I want to put the beacon.getMajor()
to jsonObject.put("uuid", a)
Thank you !
Here is my code.
private List<String> placesNearBeacon(Beacon beacon) {
int a = beacon.getMajor();
final String b = String.valueOf(beacon.getMajor());
Log.v("show", String.valueOf(a));
Intent intent = new Intent(this,AsyncLogin.class);
intent.putExtra("MAJOR",a);
startActivity(intent);
if (a == 258){
new AsyncLogin().execute(String.valueOf(a));
}
String beaconKey = String.format("%d:%d", beacon.getMajor(), beacon.getMinor());
return Collections.emptyList();
}
enter code here
private class AsyncLogin extends AsyncTask<String, String, String>
{
HttpURLConnection conn;
URL url = null;
Uri a = new Intent().getData();
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://etriplay.com/app/beacon_GetInform.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// JSON
JSONObject jsonObject = new JSONObject();
jsonObject.put("userid", "membe00001");
jsonObject.put("mail", "test#mail.com");
jsonObject.put("uuid", a);
Log.v("v", String.valueOf(jsonObject));
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(String.valueOf(jsonObject));
writer.flush();
writer.close();
os.close();
conn.connect();
In this case If you want object or something to put in json you can do ie by-:
try
{
jsonObject.put("value",chatMessage.getDate());
}
catch (JSONException e)
{
e.printStackTrace();
}
as in jsonobject.put("key",value);
You can assign the int value,string value,boolean value or whatever you want
Related
How can I get the response message returned from my DJANGO view and place it into a textview? Most of the answers talk about using Httpresponse but as I've read, it has be deprecated. I'm using SDK v28.
Java code in Android Studio:
private class HTTPAsyncTask_wdgt extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
try {
return HttpPost_wdgt(urls[0]);
} catch (JSONException e) {
e.printStackTrace();
return "Error!";
}
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
}
private String HttpPost_wdgt(String myUrl) throws IOException, JSONException {
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
JSONObject jsonObject = buildJsonObject_wdgt(); //Just takes some data from the app and returns JSON to be posted.
setPostRequestContent_wdgt(conn, jsonObject);
conn.connect();
return conn.getResponseMessage()+"";
}
private void setPostRequestContent_wdgt(HttpURLConnection conn,
JSONObject jsonObject) throws IOException {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonObject.toString());
writer.flush();
writer.close();
os.close();
}
Django view: (Right now it just returns 'mac' from the posted JSON)
#csrf_exempt
def req_exec(request):
ret = request.POST
data = json.loads(request.body)
return HttpResponse(data['mac'])
I normally use OKHttp for getting and processing requests, here is a Vogella tutorial helping to get start.
I am new to android and mongodb.
I have problem with inserting data to my mLab database using my android application.
My code is this:
final class MongoLabSaveData extends AsyncTask<Object, Void, Boolean> {
#Override
protected Boolean doInBackground(Object... params) {
SignupData signupData = (SignupData) params[0];
Log.d("Sign_Up", ""+signupData);
try {
SupportDataAPI sd = new SupportDataAPI();
URL url = new URL(sd.buildSignupSaveURL());
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.append(sd.createSignupData(signupData));
osw.flush();
osw.close();
if(connection.getResponseCode() <205)
{
return true;
}
else
{
return false;
}
} catch (Exception e) {
e.getMessage();
Log.d("Got error", e.getMessage());
return false;
}
}
}
Here, the data gets inserted to every 0th index of json data due to this line:
SignupData signupData = (SignupData) params[0];
How can I make this in such a way that it appends my json data with the existing data. Not in the 0th index.
i want to send data from android application to tomcat java server.
Data is just one is client_id which is 1 and second is staff_id which is 2.
after authenticate the client id and staff id from tomcat show me a toast of success....please help...
Code is here
public class MyAsyncTasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
}
#Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.1.13:8080/digitaldisplay/s/m/data");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);
}
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(Register.this, "success", Toast.LENGTH_SHORT).show();
Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);
JSONObject oneObject = jsonArray.getJSONObject(0);
// Pulling items from the array
client = Integer.parseInt(oneObject.getString("client"));
staff = Integer.parseInt(oneObject.getString("staff"));
} catch (JSONException e) {
e.printStackTrace();
}
} }}
The logic in your code looks off to me. This is the pattern I usually follow when making a REST call from an activity using HttpURLConnection:
try {
String endpoint = "http://192.168.1.13:8080/digitaldisplay/s/m/data";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // but maybe you want GET here...
con.setConnectTimeout(10000);
con.setDoInput(true);
con.setDoOutput(true);
JSONObject inputJSON = new JSONObject();
inputJSON.put("Client_id", 1);
inputJSON.put("Staff_id", 2);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(inputJSON.toString());
writer.flush();
writer.close();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} catch (SocketTimeoutException se) {
// handle timeout exception
responseCode = -1;
} catch (Exception e) {
// handle general exception
responseCode = 0;
}
The only major change in adapting the above code for GET would be that you wouldn't write your input data to the connection. Instead, you would just append query parameters to the URL. I am possibly guessing that you need POST here, since your URL doesn't have any query parameters in it.
Can anyone help me? I'm developing an android app in android studio which will implement a Date Range search. the user will select the between date the "FROM" date and the "TO" date then the result will filter in a recyclerview. I'm using php mysql as our query. Hoping for a good and better reply. Thanks in advance
private class FilterDate extends AsyncTask {
ProgressDialog pdLoading = new ProgressDialog(Complaint.this);
HttpURLConnection conn;
URL url = null;
String from;
String to;
public FilterDate(String from,String to) {
this.from = from;
this.to = to;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.0.100/Android/filter.php");
} catch (MalformedURLException e) {
e.printStackTrace();
// TODO Auto-generated catch block
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
// add parameter to our above url
Uri.Builder builder1 = new Uri.Builder().appendQueryParameter("from", from);
String query1 = builder1.build().getEncodedQuery();
OutputStream os1 = conn.getOutputStream();
BufferedWriter writer1 = new BufferedWriter(new OutputStreamWriter(os1, "UTF-8"));
writer1.write(query1);
writer1.flush();
writer1.close();
os1.close();
conn.connect();
Uri.Builder builder2 = new Uri.Builder().appendQueryParameter("to", from);
String query2 = builder2.build().getEncodedQuery();
OutputStream os2 = conn.getOutputStream();
BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os1, "UTF-8"));
writer2.write(query2);
writer2.flush();
writer2.close();
os2.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread suggestion
ArrayList<String> dataList = new ArrayList<String>();
pdLoading.dismiss();
// pdLoading.dismiss();
List<DataComplaints> data = new ArrayList<>();
pdLoading.dismiss();
if (result.equals("no rows")) {
Toast.makeText(Complaint.this, "No Results found for entered query", Toast.LENGTH_SHORT).show();
} else {
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataComplaints healthData = new DataComplaints();
healthData.idNum = json_data.getString("student_number");
healthData.lastName = json_data.getString("lastname");
healthData.firstName = json_data.getString("firstname");
healthData.middleName = json_data.getString("middlename");
healthData.complaint = json_data.getString("common_type");
healthData.medicine = json_data.getString("medicinetype");
healthData.date = json_data.getString("date");
healthData.time = json_data.getString("time");
data.add(healthData);
dataList.add(json_data.getString("date"));
}
strArrData = dataList.toArray(new String[dataList.size()]);
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.studentList);
mAdapter = new AdapterComplaints(Complaint.this, data);
mRVFish.setAdapter(mAdapter);
mRVFish.setLayoutManager(new LinearLayoutManager(Complaint.this));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(Complaint.this, "Error in Fetching Data", Toast.LENGTH_LONG).show();
Toast.makeText(Complaint.this, "Error!", Toast.LENGTH_LONG).show();
}
}
}
}
This is my query in php:
<?php
$host='127.0.0.1';
$username='root';
$pwd='';
$db="cjc_clinic";
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$From=$_POST['from'];
$To=$_POST['to'];
//$sql="SELECT * from studentcomplaint_view where lastname LIKE '%$name%'";
//$sql="SELECT * FROM studentcomplaint_view where CONCAT(lastname,' ',firstname) LIKE '%$name%'";
//$sql="SELECT * FROM studentcomplaint_view WHERE Date >= '$From' AND Date <='$To'";
$sql="SELECT * FROM studentcomplaint_view WHERE Date BETWEEN '$From' AND '$To'";
$query=mysqli_query($con,$sql);
if($query){
while($row=mysqli_fetch_array($query))
{
$data[]=$row;
}
print(json_encode($data));
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>
I have to post the comment of a user to a web service. However I fail.
I have a AsyncTask class in which I do the following :
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsobj = null;
HttpURLConnection conn = null;
String urlStr = params[0];
String message = params[2];
String name = params[1];
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
jsobj.put("name", name);
jsobj.put("text", message);
jsobj.put("id", news_id);
DataOutputStream writer
= new DataOutputStream(conn.getOutputStream());
writer.writeBytes(jsobj.toString());
writer.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsobj;
}
In initialization I do the following:
DataTask4 tsk = new DataTask4();
tsk.execute("http://94.138.207.51:8080/NewsApp/service/news/savecomment",commentowner,message)
I don't know what I am doing wrong but seems that I can put the json object correctly to the web-service.