Android misfit API OAuth 2 : How to save access token - java

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

Related

ANDROID - how to display JSONArray into textview

I've set up a php script to create json here, but when i try to display the JSONArray i got some error like this on my Android Monitor..
Value (html)(body)(script of type java.lang.String cannot be converted to JSONArray
can someone tell me how to fix it?
MainActivity.java
package flix.yudi.okhttp1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://zxccvvv.cuccfree.com/send_data.php";
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();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan");
// looping through All Contacts
for (int i = 0; i < pertanyaan.length(); i++) {
JSONObject c = pertanyaan.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
// tmp hash map for single contact
HashMap<String, String> pertanyaans = new HashMap<>();
// adding each child node to HashMap key => value
pertanyaans.put("id", id);
pertanyaans.put("ask", ask);
// adding contact to contact list
contactList.add(pertanyaans);
}
} 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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"ask"}, new int[]{R.id.ask});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java
package flix.yudi.okhttp1;
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 got the reference code from here
any idea/ another reference method to solve?
EDIT
send_data.php
<?php
include 'dbconfig.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, ask FROM pertanyaan";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$json = json_encode($row);
}
} else {
echo "0 results";
}
mysql_close($dbname);
echo $json;
?>
you are trying to get a jsonarray from jsonObj with key pertanyaan which in-fact is a string value so just traverse through array while fetching the json object using indexes
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan"); problem
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
HashMap<String, String> pertanyaans = new HashMap<>();
pertanyaans.put("id", id);
pertanyaans.put("ask", ask);
contactList.add(pertanyaans);
}
Note : There is no such jasonarray with key pertanyaan in your response
PHP update : Use
echo json_encode($json);
According to your service, while Response received you will get JSONArray like this [{"id":"1","ask":"pertanyaan ke 1"},{"id":"2","ask":"pertanyaan ke 2"},{"id":"3","ask":"pertanyaan ke 3"},{"id":"4","ask":"pertanyaan ke 4"},{"id":"5","ask":"pertanyaan ke 5"}]
you just need to store this response in JSONArray
JSONArray jsonArray = new JSONArray();
jsonArray = (response);
now you have respons in your jsonArray so you can opt out value from it.
here is the sample code snippet
for (int i = 0; i < jsonArray.length(); i++) {
try {
String id = jsonArray.getJSONObject(i).getString("id");
String ask = jsonArray.getJSONObject(i).getString("ask");
Log.i("TAG", "id "+ id + " ask "+ ask);
//you can set value to text view here
textview.settext(id + " "+ ask);
} catch (JSONException e) {
e.printStackTrace();
}
}

I want to implement a remember me functionality in my android code but I am not sure where to start

I want to implement a remember me functionality in my android code but I'm not sure where to start because my code is type of complex. I'm not sure where to put things so please help me
I want to make phone no and password remember only when login is true so please help me. This is my codes and please tell me where to put your suggestions in my code it will be better if you edit it thank you
this is login code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import static example.R.layout.login;
public class login extends Activity {
TextView signup_text;
Button login_button;
EditText PHONE_NO, PASSWORD;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
signup_text = (TextView) findViewById(R.id.sign_up);
signup_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(login.this, register.class));
}
});
PHONE_NO = (EditText) findViewById(R.id.phone_no);
PASSWORD = (EditText) findViewById(R.id.password);
login_button = (Button) findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phone_no = PHONE_NO.getText().toString();
String password = PASSWORD.getText().toString();
if (phone_no.equals("") || password.equals("")) {
builder = new AlertDialog.Builder(login.this);
builder.setTitle("Something went wrong...");
builder.setMessage("Please fill all the fields...");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else {
BackgroundTask backgroundTask = new BackgroundTask(login.this);
backgroundTask.execute("login", phone_no, password);
}
}
});
}
}
and this is backgroundtask.java:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.CheckBox;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.*;
import android.content.SharedPreferences;
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.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
String register_url = "http://10.0.0.4/loginapp/register.php";
String login_url = "http://10.0.0.4/loginapp/login.php";
Context ctx;
ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;
public BackgroundTask(Context ctx) {
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(ctx);
progressDialog.setTitle("Please Wait");
progressDialog.setMessage("Connecting to server .... ");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("register")) {
try {
URL url = new URL(register_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 owner_name = params[1];
String shop_name = params[2];
String phone_no = params[3];
String shop_address = params[4];
String opening_time = params[5];
String closing_time = params[6];
String password = params[7];
String data = URLEncoder.encode("owner_name", "UTF-8") + "=" + URLEncoder.encode(owner_name, "UTF-8") + "&" +
URLEncoder.encode("shop_name", "UTF-8") + "=" + URLEncoder.encode(shop_name, "UTF-8") + "&" +
URLEncoder.encode("phone_no", "UTF-8") + "=" + URLEncoder.encode(phone_no, "UTF-8") + "&" +
URLEncoder.encode("shop_address", "UTF-8") + "=" + URLEncoder.encode(shop_address, "UTF-8") + "&" +
URLEncoder.encode("opening_time", "UTF-8") + "=" + URLEncoder.encode(opening_time, "UTF-8") + "&" +
URLEncoder.encode("closing_time", "UTF-8") + "=" + URLEncoder.encode(closing_time, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (method.equals("login")) {
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 phone_no, password;
phone_no = params[1];
password = params[2];
String data = URLEncoder.encode("phone_no", "UTF-8") + "=" + URLEncoder.encode(phone_no, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonarry = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonarry.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true")) {
showDialog("Registration Success", code, message);
} else if (code.equals("reg_false")) {
showDialog("Registration Failed", code, message);
} else if (code.equals("login_true")) {
Intent intent = new Intent(activity, HomeActivity.class);
intent.putExtra("message", message);
activity.startActivity(intent);
} else if (code.equals("login_false")) {
showDialog("Login Error", code, message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void showDialog(String title, String code, String message) {
builder.setTitle(title);
if (code.equals("reg_true") || code.equals("reg_false")) {
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
} else if (code.equals("login_false")) {
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText phone_no, password;
phone_no = (EditText) activity.findViewById(R.id.phone_no);
password = (EditText) activity.findViewById(R.id.password);
phone_no.setText("");
password.setText("");
dialog.dismiss();
}
});
}
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help Thank you
After clicking on login/SignIn, just check if remember me CheckBox is checked or not, if it is checked store userName/Email and password in SharedPreferences.
In your onCreate() of LoginActivity, check whether you have any userName/Email or password stored in SharedPreferences, if it is there fill your EditText with those UserName/Email and Password.
public class Log_in extends AppCompatActivity {
public static String PREFS_NAME="NAME";
public static String PREF_USERNAME="";
public static String PREF_PASSWORD="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
EditText txtuser=(EditText)findViewById(R.id.txt_user);
EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
CheckBox ch=(CheckBox)findViewById(R.id.ch_rememberme);
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
if (username != null || password != null) {
txtuser.setText(username);
txtpwd.setText(password);
ch.setChecked(true);
}
else {
ch.setChecked(false);
}
}
public void doLogin(View view){
EditText txtuser=(EditText)findViewById(R.id.txt_user);
EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
String username = txtuser.getText().toString();
String password = txtpwd.getText().toString();
CheckBox ch=(CheckBox)findViewById(R.id.ch_rememberme);
String type = "login";
if(ch.isChecked()){
rememberMe(username,password);
}
else{
clear();
}
BackgroundTask bt = new BackgroundTask(this);
bt.execute(type, username, password);
}
public void rememberMe(String user, String password){
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME,user)
.putString(PREF_PASSWORD,password)
.commit();
}
public void clear(){
SharedPreferences sharedPrefs =getSharedPreferences(Log_in.PREFS_NAME,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.clear();
editor.commit();
}
}

How to retrieve weather data in json [android]

I want to retrieve weather data from an API as JSON, but it isn't working. How do I pull in weather data, such as a 5-day forecast, into a text view?
My code is below, but I need to somehow adapt it to pass in the JSON 5-day weather forecast and put that into a text view.
package mytweets.mytweets;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MytweetsActivity extends Activity {
// we are reading weathe
final String URL `enter code here`="http://api.openweathermap.org/data/2.5/forecast/daily?q,gb&mode=json&units=metric&cnt=5&APPID=xxxxxxxxxxxxxxxx";
final String Consumer_Key = "mPfkAwVuuiVYeuZWdHAMzQ"; // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new
final String Consumer_Secret = "bkmiQqellGg9jnJFj41E8zukYSNk0FX1W7v1nU376rE"; // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new
JSONArray tweets = null; //an array of tweets
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mytweets);
Button btn_token = (Button)findViewById(R.id.get_token);
btn_token.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetTokenTask().execute();
}
});
Button btn_feed = (Button)findViewById(R.id.get_tweets);
btn_feed.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView txt_token = (TextView)findViewById(R.id.txt_token);
String token = txt_token.getText().toString();
new GetTweetsTask().execute(token, URL);
}
});
}
protected class GetTokenTask extends AsyncTask<Void, Void, String> { // the class extends AsynTask in order to run as a thread in the background
#Override
protected String d
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token"); //asks for a token
String apiString = Consumer_Key + ":" + Consumer_Secret;
String authorization = "Basic " + Base64.encodeToString(apiString.getBytes(), Base64.NO_WRAP); // twitter ants the authorization in bytes
httppost.setHeader("Authorization", authorization);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httppost.setEntity(new StringEntity("grant_type=client_credentials"));
InputStream inputStream = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); // reading the input stream
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
}catch (Exception e){
Log.e("GetTokenTask", "Error:" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String jsonText){
try {
JSONObject root = new JSONObject(jsonText);
String bearer_token = root.getString("access_token");
TextView txt = (TextView)findViewById(R.id.txt_token);
txt.setText(bearer_token);
}catch (Exception e){
Log.e("GetTokenTask", "Error:" + e.getMessage());
}
}
}
protected class GetTweetsTask extends AsyncTask<String, Void, String> { //the class is run as a thread in the background to get the tweets
#Override
protected String doInBackground(String... params) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpGet httpget = new HttpGet(params[1]);
httpget.setHeader("Authorization", "Bearer " + params[0]);
httpget.setHeader("Content-type", "application/json"); //json content type
InputStream inputStream = null;
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
}catch (Exception e){
Log.e("GetFeedTask", "Error:" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String jsonString){
try {
TextView txt_tweets = (TextView)findViewById(R.id.txt_tweets);
JSONObject forecastJson = new JSONObject(jsonString);
JSONArray forecastArray = forecastJson.getJSONArray("list");
String txt = "";
int i;
double minTemp, maxTemp;
// we are going to parse the json string and only display created_at and text. You can decide to display more objects if you want.
for (i=0;i<tweets.length();i++)
{
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("temp");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
txt_tweets.setText(txt);
txt += "------------\n"; //separtors, check the output
}
}catch (Exception e){
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mytweets, menu);
return true;
}
}
This is the JSON format of weather data:
city: {
id: 2643743,
name: "London",
coord: {
lon: -0.12574,
lat: 51.50853
},
country: "GB",
population: 0
},
cod: "200",
message: 0.0268,
cnt: 5,
list: [
{
dt: 1448535600,
temp: {
day: 8.58,
min: 8.58,
max: 9.18,
night: 9.18,
eve: 8.58,
morn: 8.58
},
pressure: 1025.14,
humidity: 95,
weather: [
{
id: 500,
main: "Rain",
description: "light rain",
icon: "10d"
}
],
speed: 3.67,
deg: 224,
clouds: 92,
rain: 0.35
},
{},
{},
{},
{}
]
Now to access the weather data (e.g. min and max temp) you need to parse as below:
JSONObject forecastJson = new JSONObject(jsonString);
JSONArray forecastArray = forecastJson.getJSONArray("list");
double minTemp, maxTemp;
for(int i = 0; i < forecastArray.length(); i++) {
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("temp");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
}
If you have further doubts, please let me know.
Use arrays and objects and make sure you have a json parser

Android - Get HTTP Post Response in other activity

I created two activities one contains some text fields which accepts data. From other activity(Async Task) this data is sent to the server and gets the response from the server.
I am able to log the response but unable to store that response in variable and user in other activities. Is there any way to do that?
Here is one activity,
RegisterDevice.java
package sys.darpan.tracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegisterDevice extends Activity{
EditText regEmail, regPassword, regImei, regDeviceName, regVehicleNumber;
Button regButton;
AsyncRegisterDevice asd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_device);
regEmail = (EditText)findViewById(R.id.regEmail);
regPassword = (EditText)findViewById(R.id.regPassword);
regVehicleNumber = (EditText)findViewById(R.id.regVehicleNum);
regImei = (EditText)findViewById(R.id.regImei);
regDeviceName = (EditText)findViewById(R.id.regDeviceName);
regButton = (Button)findViewById(R.id.regButton);
regImei.setText("165465416416416");
regDeviceName.setText("GT-I9300");
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerDevice();
}
});
}
protected void registerDevice(){
asd = new AsyncRegisterDevice();
String email = regEmail.getText().toString();
String password = regPassword.getText().toString();
String imei = regImei.getText().toString();
String deviceName = regDeviceName.getText().toString();
String vehicleNo = regVehicleNumber.getText().toString();
String aobj[] = new String[5];
aobj[0] = email;
aobj[1] = password;
aobj[2] = vehicleNo;
aobj[3] = imei;
aobj[4] = deviceName;
asd.execute(aobj);
}
}
Here is Async Task,
package sys.darpan.tracking;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
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 android.os.AsyncTask;
import android.util.Log;
public class AsyncRegisterDevice extends AsyncTask<String, String, String> {
String sb;
String finalResult;
#Override
protected String doInBackground(String... params) {
String email = params[0];
String password = params[1];
String vnumber = params[2];
String imei = params[3];
String deviceName = params[4];
DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logicvibes.com/vts/register-device.php");
ArrayList<BasicNameValuePair> arraylist = new ArrayList<BasicNameValuePair>(5);
arraylist.add(new BasicNameValuePair("email", email));
arraylist.add(new BasicNameValuePair("pass", password));
arraylist.add(new BasicNameValuePair("vno", vnumber));
arraylist.add(new BasicNameValuePair("imei", imei));
arraylist.add(new BasicNameValuePair("dname", deviceName));
try
{
httppost.setEntity(new UrlEncodedFormEntity(arraylist));
httppost.getAllHeaders();
}
catch (UnsupportedEncodingException unsupportedencodingexception)
{
unsupportedencodingexception.printStackTrace();
}
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = defaulthttpclient.execute(httppost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
sb = stringBuilder.toString();
Log.d("Custom resp: ", sb);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String sb) {
Log.d("RESULT", "Result : " + sb);//this returns NULL
finalResult = sb;
}
public String getFinalResult() {
return finalResult;
}
}
I searched a lot but no luck, please tell me the proper way to do this.
Solved it by using,
try {
asd.execute(aobj).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
The main thread waits until the async task finished processing. (good for short processes)

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