Sending periodic location updates to server using async task android - java

I am trying to develop an application that send locations periodically to a server through http post. I have tried the async task in the following code. I am new to android programming. I get the error "failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)" and "E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1" when I run this code. Please help me out
package com.example.vikram.locationinterval;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownServiceException;
import java.nio.charset.Charset;
import java.security.Permission;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
protected LocationManager locationManager;
TextView txtLat,content;
protected static int intervalInMillis = 500;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
content = (TextView)findViewById( R.id.content );
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, intervalInMillis, 0.5f, this);
}
#Override
public void onLocationChanged(Location location) {
long now = System.currentTimeMillis();
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude() + "\n now = " + now);
try{
System.out.println("\nTesting 2 - Send Http POST request");
new MyAsyncTask(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude())).execute();
}
catch(Exception ex)
{
//System.out.println(ex.getCause());
}
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double> {
protected String latitude,longitude;
protected MyAsyncTask(String lat,String lon){
this.latitude = lat;
this.longitude = lon;
}
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
try {
postData(this.latitude, this.longitude);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result){
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
public void postData(String Lat,String Lon) throws UnsupportedEncodingException {
// Create data variable for sent values to server
String data = URLEncoder.encode("Latitude", "UTF-8")
+ "=" + URLEncoder.encode(Lat, "UTF-8");
data += "&" + URLEncoder.encode("Longitude", "UTF-8") + "="
+ URLEncoder.encode(Lon, "UTF-8");
System.out.println(data);
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://10.0.2.2:8080/GetSomeRest/webresources/service");
// Send POST data request
String charset = "UTF-8";
URLConnection conn = url.openConnection();
conn.setReadTimeout(5000);
System.out.println("coonnected.: ");
Permission p = conn.getPermission();
System.out.println("permission: " + p.toString());
conn.setDoOutput(true);
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
System.out.println("output gate opened.."+conn.toString());
OutputStream wr;
try {
//conn.connect();
wr = conn.getOutputStream();
if(wr == null){
System.out.println("-> no stream!");
}
else {
wr.write(data.getBytes(Charset.forName(charset)));
//wr.flush();
wr.close();
}
} catch (UnknownServiceException use){
System.out.println("error unknown server: "+use.getMessage());
} catch (IOException connOI){
System.out.println("error io stream: "+connOI.getMessage());
} catch (Exception connOSW){
System.out.println("error writing to stream: "+connOSW.getMessage());
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response on activity
content.setText( text );
}
}
}

Related

I have taken text from JSON format of an API now I want to add image to it from same API in my android app

I'm new to android and finding it tough to update realtime text and images from API's in JSON format. I've successfully added text to my listview. Now I want to add image beside it. Thanks in advance.
MainActivity.java file
package com.example.android.samplelayout;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.net.Uri;
import android.graphics.drawable.Drawable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://webhose.io/search?token=9c55cbb1-2f1c-4700-9c1e-67e685152506&format=json&q=Indian%20Startup";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONObject responseObject = jsonObj.getJSONObject("response");
JSONArray responseArray = jsonObj.getJSONArray("posts");
// looping through All Contacts
for (int i = 0; i < responseArray.length(); i++) {
JSONObject firstObject = responseArray.getJSONObject(i);
//JSONObject titleObject = firstObject.getJSONObject("title");
// Extract out the title, time, and tsunami values
//String image = firstObject.getString("main_image");
String title = firstObject.getString("title");
// tmp hash map for single contact
HashMap<String , String> contact = new HashMap<>();
// adding each child node to HashMap key => value
//contact.put("pic", image);
contact.put("name", title);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,R.layout.list_item, new String[]{"name"}, new int[]{ R.id.name});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java file
package com.example.android.samplelayout;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I would suggest using a library that automatically puts an Image into an ImageView only using the Url of the image you want to use. Picasso would be a good Library for your use. You have to fetch the Image URL off the Json object and load it into the ImageView using Picasso's load().into()

Where do I place the intent code?

Following are the .java files I had written to login to the app using mysql. I had found help on http://easyway2in.blogspot.in/2015/07/android-mysql-database-connect.html
MainActivity.java
package com.example.soumya.attendance;
import android.app.Activity;
import android.content.Intent;
import android.os.StrictMode;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity{
EditText ET_NAME,ET_PASS;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET_NAME = (EditText)findViewById(R.id.editText1);
ET_PASS = (EditText)findViewById(R.id.editText2);
}
public void userLogin(View view)
{
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
}
#Override
public void onBackPressed() {
return;
}
}
BackgroundActivity.java
package com.example.soumya.attendance;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
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;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2/webapp/register.php";
String login_url = "http://10.0.2.2/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
Now, I want to add an intent code so that if the user logs in successfully, he/she will be taken to the other activity. But, if I try to place it in MainActivity.java, it does not check for successful login or not. Please help me with it. Many others also have the same question on the source. Here, my login.php returns a result to notify whether the login is successful or not through echo.
Its Simple,
Just place on the Intent code on Post Execute when the login Success
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
//Place the Intent Code Here.
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName("com.your.package","com.your.package.MainActivity");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
Happy Coding :)

Android misfit API OAuth 2 : How to save access token

With the following android code, i manage to do this:
Display authentification page, on my Android smartphone, to my user
Login, as a valid user, through this page with my credentials
Catch the Auth code
See, on my smarthpone webview, the access_token
public class MainActivity extends AppCompatActivity
{
public static String OAUTH_URL = "https://api.misfitwearables.com/auth/dialog/authorize";
public static String OAUTH_ACCESS_TOKEN_URL = "https://api.misfitwearables.com/auth/tokens/exchange";
public static String CLIENT_ID = "my id";
public static String CLIENT_SECRET = "my secret code";
public static String CALLBACK_URL = "just a simple url";
public static String SCOPE = "public,birthday,email,tracking,session,sleep";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
String url = OAUTH_URL+ "?response_type=code" +"&client_id=" + CLIENT_ID+ "&redirect_uri=" + CALLBACK_URL + "&scope=" + SCOPE;
WebView webview = (WebView) findViewById(R.id.aaa);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String accessTokenFragment = "access_token=";
String accessCodeFragment = "code=";
if (url.contains(accessCodeFragment))
{
String accessCode = url.substring(url.indexOf(accessCodeFragment));
String query = "grant_type=authorization_code" + "&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&" + accessCode + "&redirect_uri=" + CALLBACK_URL;
view.postUrl(OAUTH_ACCESS_TOKEN_URL, query.getBytes());
System.out.println("url:" + url);
System.out.println(accessCode);
}
System.out.println(url);
if (url.contains(accessTokenFragment)) {
String accessToken = url.substring(url.indexOf(accessTokenFragment));
url = url.replace("#", "?");
//view.loadUrl(url);
System.out.println("token=" + accessToken);
}
}
});
webview.loadUrl(url);
}
}
Like I said above, I manage to display the access_token on my webview, on my smarthpone. But I am not able to catch this token, to make get request in order to recover user's data.
I am novice in java/android, but I have some skills in C.
I just took the time to discover Java, so my skills in this area are limited.
Is that someone could advise me?
I have found some piece of code, and made an Android App that works well.
Main
package com.example.vta.webview_example;
/*
* Note that I was a complete novice in Java and Android when I was writting this.
* Note that I found pieces of code that I adapted for my needs.
*/
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
public class MainActivity extends Activity
{
private static String CLIENT_ID = "your ID_CLIENT code";
private static String CLIENT_SECRET ="your SECRET_CLIENT code";
private static String REDIRECT_URI="http://localhost";
private static String GRANT_TYPE="authorization_code";
private static String TOKEN_URL ="https://api.misfitwearables.com/auth/tokens/exchange";
private static String OAUTH_URL ="https://api.misfitwearables.com/auth/dialog/authorize";
private static String OAUTH_SCOPE="public,birthday,email,tracking,session,sleep";
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
auth = (Button)findViewById(R.id.auth);
auth.setOnClickListener(new View.OnClickListener()
{
Dialog auth_dialog;
#Override
public void onClick(View arg0)
{
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(OAUTH_URL+"?redirect_uri="+REDIRECT_URI+"&response_type=code&client_id="+CLIENT_ID+"&scope="+OAUTH_SCOPE);
web.setWebViewClient(new WebViewClient()
{
boolean authComplete = false;
Intent resultIntent = new Intent();
String authCode;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
if (url.contains("?code=") && authComplete != true)
{
Uri uri = Uri.parse(url); //Create an uri, identical to the url
System.out.println("=====> uri <===== \n" + uri);
authCode = uri.getQueryParameter("code"); //Parse the uri to fond the first occurence of "code", and extract his value
Log.i("", "CODE : " + authCode);
System.out.println("=====> code <===== \n" + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
MainActivity.this.setResult(Activity.RESULT_OK, resultIntent);
setResult(Activity.RESULT_CANCELED, resultIntent);
SharedPreferences.Editor edit = pref.edit();
edit.putString("Code", authCode);
edit.commit();
auth_dialog.dismiss();
new TokenGet().execute();
Toast.makeText(getApplicationContext(),"Authorization Code is: " +authCode, Toast.LENGTH_SHORT).show();
}
else if(url.contains("error=access_denied"))
{
Log.i("", "ACCESS_DENIED_HERE");
resultIntent.putExtra("code", authCode);
authComplete = true;
setResult(Activity.RESULT_CANCELED, resultIntent);
Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_SHORT).show();
auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Misfit");
auth_dialog.setCancelable(true);
}
});
}
private class TokenGet extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
String Code;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Contacting Misfit ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
Code = pref.getString("Code", "");
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
GetAccessToken jParser = new GetAccessToken();
JSONObject json = jParser.gettoken(TOKEN_URL,Code,CLIENT_ID,CLIENT_SECRET,REDIRECT_URI,GRANT_TYPE);
System.out.println("=====> json <===== \n" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
if (json != null)
{
try
{
final String tok = json.getString("access_token");
Log.d("Token Access", tok);
System.out.println("TOKN = " + tok);
auth.setText("Authenticated");
Access.setText("Access Token:" + tok);
}
catch (JSONException e)
{
e.printStackTrace();
}
getRequestToMisfit(json);
}
else
{
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
}
public void getRequestToMisfit(JSONObject json)
{
try
{
URL url;
HttpURLConnection connection;
String tok;
InputStream is;
BufferedReader rd;
String line;
String responseStr;
StringBuffer response;
String end_date;
String today;
String start_date;
Context context;
File file;
File file_value;
String filepath;
String filepath_value;
String result;
result = null;
context = MyApp.getContext();
connection = null;
rd = null;
tok = json.getString("access_token");
FileManagement fm = new FileManagement();
Calendar c = Calendar.getInstance();
String d = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String m = String.valueOf((c.get(Calendar.MONTH) + 1));
String y = String.valueOf(c.get(Calendar.YEAR));
today = y + "-" + m + "-" + d;
end_date = new String(today);
filepath = context.getFilesDir().getPath().toString() + "/sync_date.txt";
filepath_value = context.getFilesDir().getPath().toString() + "/sync_value.txt";
file = new File(filepath);
file_value = new File(filepath_value);
//IF YOU WANT TO SIMULATE AN OLD SYNC
//fm.writeToFile("2016-03-28", filepath);
//If you want to delete file that contain previous synchronisation date
//fm.deleteFile(file);
if ((start_date = fm.readFromFile(filepath, file)) == null)
start_date = new String(today);
//String dataUrl = "https://api.misfitwearables.com/move/resource/v1/user/me/profile?access_token=" + tok;
String dataUrl = "https://api.misfitwearables.com/move/resource/v1/user/me/activity/summary?start_date="+start_date+"&end_date="+end_date+"&access_token=" + tok;
System.out.println("=====> access_token <===== \n" + tok);
try
{
// Create connection
url = new URL(dataUrl);
setContentView(R.layout.activity_main);
TextView wv = (TextView) findViewById(R.id.misfit);
System.out.println("=====> url <===== \n" + url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
//if setDoOutput is set to "true", HttpUrlConnection will send POST request.
connection.setDoOutput(false);
// Send request
int status = connection.getResponseCode();
// Get Response
if(status >= HttpStatus.SC_BAD_REQUEST)
is = connection.getErrorStream();
else
is = connection.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
response = new StringBuffer();
while ((line = rd.readLine()) != null)
{
System.out.println("line = " + line);
response.append(line);
response.append('\r');
}
rd.close();
responseStr = response.toString();
JSONObject json_res = new JSONObject(responseStr);
System.out.println("JSON_OBJ" + json_res);
result = json_res.getString("points");
Log.d("Server response", responseStr);
System.out.println(responseStr);
System.out.println(start_date);
System.out.println(end_date);
System.out.println(result);
wv.setText("nombre de point :\ndu " + start_date + " au " + end_date + "\n" + "*** " + result + " ***");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if (connection != null)
connection.disconnect();
if (rd != null)
{
try
{
rd.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
if (!file.exists())
{
try
{
file.createNewFile();
file.mkdir();
}
catch (IOException e)
{
e.printStackTrace();
}
}
fm.writeToFile(today, filepath);
if (!file_value.exists())
{
try
{
file_value.createNewFile();
file_value.mkdir();
}
catch (IOException e)
{
e.printStackTrace();
}
}
fm.writeToFile(result, filepath_value);
System.out.println(fm.readFromFile(filepath_value, file));
Toast.makeText(context, "Result added to file ==> OK", Toast.LENGTH_LONG);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
GetAccessToken
package com.example.vta.webview_example;
/*
* Find on
* http://stackoverflow.com/questions/22499066/invalid-client-in-jsonresponse-in-oauth2-android
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class GetAccessToken
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
Map<String, String> mapn;
DefaultHttpClient httpClient;
HttpPost httpPost;
public GetAccessToken()
{
}
public JSONObject gettoken(String address,String token,String client_id,String client_secret,String redirect_uri,String grant_type)
{
// Making HTTP request
try
{
// DefaultHttpClient
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(address);
params.add(new BasicNameValuePair("code", token));
params.add(new BasicNameValuePair("client_id", client_id));
params.add(new BasicNameValuePair("client_secret", client_secret));
params.add(new BasicNameValuePair("redirect_uri", redirect_uri));
params.add(new BasicNameValuePair("grant_type", grant_type));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader;
StringBuilder sb;
String line;
reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
line = null;
while ((line = reader.readLine()) != null)
{
System.out.println("=+=+=+> getAccessToken : line <+=+=+= \n" + line);
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("=+=+=+> getAccessToken : json <+=+=+= \n" + json);
Log.e("JSONStr", json);
}
catch (Exception e)
{
e.getMessage();
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Parse the String to a JSON Object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return JSON String
return jObj;
}
}
The entire project :
https://github.com/v3t3a/android/tree/master/marvin_project/webview_example/app/src/main/java/com/example/vta/webview_example

Sending json Post date in android with parameter

I'm trying to make a POST request with Android, but I'm not succeeding. I think the problem is in how to set the parameters for resquisição and Header. Below is my method I do the request ...
public void testPostDate() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
Gson gson = new Gson();
CrimePOST.Crime crime = new CrimePOST().new Crime(10, "São Paulo",
"descrição", 10.00, 30.00);
CrimePOST crimePost = new CrimePOST();
crimePost.setCrime(crime);
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJa6JhMs="));
String json = gson.toJson(crimePost);
String paramString = URLEncodedUtils.format(params, Utils.ENCODE);
try {
HttpPost post = new HttpPost(
"http://safe-sea-4024.herokuapp.com/crimes/mobilecreate"
+ "?" + paramString);
post.setHeader("Content-Type", "application/json");
StringEntity entitty = new StringEntity(json);
entitty.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(entitty);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = toString(in);
System.out.println(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This method is responsible for converting an inputStream to String
private String toString(InputStream is) throws IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0) {
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
Really I am passing the Header correctly?
You have to do this in an AsyncTask
I wrote this tutorial while back. it does send json data via HTTP Post to a url. Check it out. Original post can be found here:http://androidhappenings.blogspot.com/2013/03/android-app-development-201-1st.html
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity implements LocationListener{
private TextView textView =null;
LocationManager locationManager=null;
Location location=null;
protected String url;
protected JSONObject jsonData=null;
private EditText urlText=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(gpsEnabled!=true) {
Toast.makeText(getApplicationContext(), "GPS Disbled! Please Enable to Proceed!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
textView = (TextView)findViewById(R.id.textView);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
urlText = (EditText)findViewById(R.id.urlTextbox);
Button submitButton = (Button)findViewById(R.id.submitUrl);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (urlText.getText()!=null) {
url=urlText.getText().toString();
System.out.println(url);//for testing only, not required
Toast.makeText(getApplicationContext(), "Url Submitted, Sending data to Web Service at url: " + url, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString());//not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public class HttpPostHandler extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity dataEntity = null;
try {
dataEntity = new StringEntity(jsonData.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(dataEntity);
httpPost.setHeader("Content-Type", "application/json");
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Android Emulator connecting to Local Web service

Hi all I have a local web service set up on my machine, it is a web service which was built in netbeans using the JPA. I have it connecting locally to a mySQL server also. I have both the database and web service connecting. The webservice can display XML/JSON. My problem is getting the android emulator to consume the JSON from the web service. The URL we are using is "http://10.0.2.2:8080/Web4/resources/hotel2s/" this should allow the emulator to connect to the web service am I correct? When I try to launch and consume the emulator crashes. Here is some source code. We are sure that it should read in and parse with GSON etc but we are not sure if it is connecting or not.
RESULT CLASS
public class hotel_Result
{
#SerializedName("hotelAddress")
protected String hotelAddress;
#SerializedName("HotelDescription")
protected String hotelDescription;
#SerializedName("hotelName")
protected String hotelName;
#SerializedName("hotelRating")
protected int hotelRating;
}
HOTEL RESPONSE CLASS
public class hotel_Response
{
public List<hotel_Result> hotelresults;
public String query;
}
MAIN CLASS
public class connectRest extends Activity
{
// We tried Reg's machines ip here as well and it crashed also used different ips is this correct for the emulator to connect to it?
String url = "http://10.0.2.2:8080/Web4/resources/hotel2s/";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputStream source = retrieveStream(url); // Stream in the URL
Gson gson = new Gson(); // GSON object
Reader reader = new InputStreamReader(source); // Read in the stream
hotel_Response response = gson.fromJson(reader,hotel_Response.class); // Fill in the variables in the class hotel_response
Toast.makeText(this,response.query,Toast.LENGTH_SHORT).show();
List<hotel_Result> hotelresults = response.hotelresults;
for(hotel_Result hotel_Result : hotelresults)
{
Toast.makeText(this,hotel_Result.hotelName,Toast.LENGTH_SHORT).show();
}
}
private InputStream retrieveStream(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(),"Error" + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch(IOException e)
{
getRequest.abort();
Log.w(getClass().getSimpleName(),"Error for URL " + url, e);
}
return null;
}
}
Make sure you have the allow internet access permission in your manifest.
Here's a better try-catch implementation and it does the work in an AsyncTask() to keep the UI thread happy :) The original article can be found on Java Code Geeks (http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html) but it lacks my improvements!
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;
public class JsonParsingActivity extends Activity {
private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
protected InitTask _initTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_initTask = new InitTask();
_initTask.execute( getApplicationContext() );
}
});
}
#Override
public void onStop() {
super.onStop();
_initTask.cancel(true);
}
protected class InitTask extends AsyncTask<Context, String, SearchResponse>
{
#Override
protected SearchResponse doInBackground( Context... params )
{
InputStream source = retrieveStream(url);
SearchResponse response = null;
if (source != null) {
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
try {
response = gson.fromJson(reader, SearchResponse.class);
publishProgress( response.query );
reader.close();
} catch (Exception e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
}
}
if (!this.isCancelled()) {
return response;
} else {
return null;
}
}
#Override
protected void onProgressUpdate(String... s)
{
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( SearchResponse response )
{
super.onPostExecute(response);
StringBuilder builder = new StringBuilder();
if (response != null) {
String delim = "* ";
List<Result> results = response.results;
for (Result result : results) {
builder.append(delim).append(result.fromUser);
delim="\n* ";
}
}
if (builder.length() > 0) {
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try {
getRequest = new HttpGet(url);
HttpResponse getResponse = client.execute(getRequest);
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (Exception e) {
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
}
}
}
Here's a full try-catch implementation of the code above. I implemented this first and then realized all I really needed to know was pass/fail. Anyway, might help someone. Again, props go to Java Code Geeks for getting me started ... Android JSON Parsing with GSON Tutorial
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;
public class JsonParsingActivity extends Activity {
private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
protected InitTask _initTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_initTask = new InitTask();
_initTask.execute( getApplicationContext() );
}
});
}
#Override
public void onStop() {
super.onStop();
_initTask.cancel(true);
}
protected class InitTask extends AsyncTask<Context, String, SearchResponse>
{
#Override
protected SearchResponse doInBackground( Context... params )
{
InputStream source = retrieveStream(url);
SearchResponse response = null;
if (source != null) {
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
try {
response = gson.fromJson(reader, SearchResponse.class);
publishProgress( response.query );
} catch (JsonSyntaxException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
return null;
} catch (JsonIOException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
return null;
} finally {
try {
reader.close();
} catch (IOException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
}
}
}
if (!this.isCancelled()) {
return response;
} else {
return null;
}
}
#Override
protected void onProgressUpdate(String... s)
{
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( SearchResponse response )
{
super.onPostExecute(response);
StringBuilder builder = new StringBuilder();
if (response != null) {
String delim = "* ";
List<Result> results = response.results;
for (Result result : results) {
builder.append(delim).append(result.fromUser);
delim="\n* ";
}
}
if (builder.length() > 0) {
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try {
getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
try {
return getResponseEntity.getContent();
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
} catch (ClientProtocolException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
} catch (IllegalArgumentException e) {
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
}

Categories

Resources