I'm relatively new to Android app development and wonder what I'm doing wrong. I have an AsyncTask that connects to my web server with username and password and returns the user dataset as json object. Unfortunately I can't get the json string, because onPostExecute() in my AsyncHttpReading class doesn't seem to get called. Why?
MainActivity.java
package com.alphavoice.sampleproject;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import com.alphavoice.sampleproject.community.user.User;
import com.alphavoice.sampleproject.util.HttpReader;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = (appPrefs.getInt("userId", 0) != 0) ? true : false;
if (isLoggedIn) {
renderCommunityView();
}
else {
setContentView(R.layout.activity_main);
final Button btnLogin = (Button) findViewById(R.id.btn_login);
final EditText etUsername = (EditText) findViewById(R.id.et_username);
final EditText etPassword = (EditText) findViewById(R.id.et_password);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String loginUrl = "http://example.com/websrv/get_user.php?username=" + username + "&password=" + password;
AsyncHttpReading httpReading = new AsyncHttpReading();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
int corePoolSize = 60;
int maximumPoolSize = 80;
int keepAliveTime = 10;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maximumPoolSize);
Executor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
// httpReading.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, loginUrl);
httpReading.executeOnExecutor(threadPoolExecutor, loginUrl);
}
else {
httpReading.execute(loginUrl);
}
if (httpReading.getLoggedInUser() != null) {
// renderCommunityView();
btnLogin.setBackgroundColor(Color.GREEN);
}
else {
// wrong combination of username & password => try again
etUsername.setBackgroundColor(Color.rgb(255, 204, 204));
etPassword.setBackgroundColor(Color.rgb(255, 204, 204));
}
}
});
}
}
private void renderCommunityView() {
setContentView(R.layout.activity_community);
}
private class AsyncHttpReading extends AsyncTask<String, Void, String> {
private String response = "";
private User loggedInUser = null;
public AsyncHttpReading() { }
public String getResponse() {
return response;
}
public User getLoggedInUser() {
return loggedInUser;
}
#Override
protected String doInBackground(String... urls) {
HttpReader httpReader = new HttpReader(urls[0]);
response = httpReader.getResponse();
return response;
}
#Override
protected void onPostExecute(String response) {
try {
JSONObject userData = new JSONObject(this.getResponse()).getJSONObject("0");
if (userData != null) {
loggedInUser = new User(userData);
}
} catch (JSONException e) {
Log.e("SAMPLEPROJECT", "Could not parse json data!");
}
}
}
}
HttpReader.java
package com.alphavoice.sampleproject.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class HttpReader {
private String url = "";
public HttpReader(String url) {
this.url = url;
}
public String getURL() {
return url;
}
public String getResponse() {
URL urlObj = null;
HttpURLConnection connection = null;
// http request
try {
urlObj = new URL(url);
connection = (HttpURLConnection) urlObj.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
} catch (Exception e) {
Log.e("SAMPLEPROJECT", "Could not connect to web server!");
}
// read stream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
StringBuffer buffer = new StringBuffer();
char[] chars = new char[1024];
int read = 0;
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
Log.e("SAMPLEPROJECT", "Could not open stream!");
}
return null;
}
}
User.java
package com.alphavoice.sampleproject.community.user;
import org.json.JSONObject;
public class User {
public User(JSONObject dataset) {
}
}
Related
So whenever I Enter a city name in the EditText and press the button my app just crashes and does not show a toast
shows this error in logcat : used by: java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
Does anyone know who to fix this error?
im using android studio
package com.example.whatstheweather;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView resultTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editTextTextPersonName);
resultTextView = findViewById(R.id.resultTextView);
}
public void getWeather(View view){
try {
DownloadTask task = new DownloadTask();
String encodedCityName = URLEncoder.encode(editText.getText().toString(), "UTF-8");
task.execute("http://openweathermap.org/data/2.5/weather?q=" + encodedCityName + "&APPID=9eebb30a9664baf113136d98e764ffb5");
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not find weather :(",Toast.LENGTH_SHORT).show();
}
}
public class DownloadTask extends AsyncTask<String, Void, String >{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}catch(Exception e){
e.printStackTrace();;
Toast.makeText(getApplicationContext(),"Could not find weather :(",Toast.LENGTH_SHORT).show();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
String message = "";
for (int i = 0; i< arr.length(); i++){
JSONObject jsonPart =arr.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
if (!main.equals("") && !description.equals("")) {
message += main + ": " + description + "\r\n";
}
}
if (!message.equals("")){
resultTextView.setText(message);
}else{
Toast.makeText(getApplicationContext(),"Could not find weather :(",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not find weather :(",Toast.LENGTH_SHORT).show();
}
}
}
}
try {
//add her code
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in
the correct input",
Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return true; // attention here
}
Method in onCreate :
private void toastPublic(final String message){
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(),""+message,
4 /*Toast.LENGTH_SHORT*/).show();
}});
}
Next : use in inside asyncTask or Thread
I am trying to build an app for class and am having trouble with handling data that is gathered in another thread. The data does not seems to being passed through the handlers handleMessage method.
This is my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
ArrayList<Book> names;
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
// Handler bookHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
names = new ArrayList<Book>();
final EditText searchBar = findViewById(R.id.searchbar);
final Handler bookHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
String response = (String) msg.obj;
try{
JSONArray tmp = new JSONArray(response);
for(int i = 0; i < tmp.length(); i++){
JSONObject a = tmp.getJSONObject(i);
int id = a.getInt("book_id");
String title = a.getString("title");
Log.d("BOOK_id", a.getInt("book_id")+"");
String author = a.getString("author");
int published = a.getInt("published");
String coverUrl = a.getString("cover_url");
Book book = new Book(id,title,author,published,coverUrl);
names.add(book);
}
} catch (Exception e){
Log.d("FAIL", e.toString());
}
return false;
}
});
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
Log.d("Handler", response);
Message msg = Message.obtain();
msg.obj = response;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.e("Fail", e.toString());
}
}
};
t.start();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
JSONArray bookOBJ= new JSONArray(response);
Message msg = Message.obtain();
msg.obj = bookOBJ;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.d("Fail", e.toString());
}
}
};
t.start();
}
});
}
The code is suppose to get data from an api and then in the handleMessage method it is suppose to parse the data into a book object that contains two int and three string variables. The problem is that the handler never executes any code.
The execution should be that the debugger log should have the response string with the data from the API and then the id of every book in the JSON file, but it only has the data from the api displayed.
I am building an app that displays details of a book you have searched. The problem is that every time I change the orientation of my device the list view elements disappear. I want help in how to make them not disappear. I have a feeling that I need to use a Loader but I have no idea in how to implement it. Here are my activities.
MainActivity :-
package com.example.visha.booklistingapp;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BookAdapter mAdapter;
EditText searchtext;
ListView earthquakeListView;
TextView empty;
TextView authorcheck;
TextView titlecheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
earthquakeListView = (ListView) findViewById(R.id.listView);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
earthquakeListView.setAdapter(mAdapter);
searchtext = (EditText) findViewById(R.id.editText);
empty = (TextView) findViewById(R.id.textView);
earthquakeListView.setEmptyView(empty);
}
public void searchclick(View view) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
String parturl = searchtext.getText().toString();
parturl = parturl.replaceAll("\\s","");
StringBuilder urlbuilder = new StringBuilder();
urlbuilder.append(" https://www.googleapis.com/books/v1/volumes?q=");
urlbuilder.append(parturl);
urlbuilder.append("&maxResults=5");
String url = urlbuilder.toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(url); }
else{
Toast.makeText(getApplicationContext(), "You are not connected to the internet",
Toast.LENGTH_LONG).show();
}
}
private class BookAsyncTask extends AsyncTask<String, Void, List<Book>> {
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
QueryUtils :-
package com.example.visha.booklistingapp;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by visha on 14-10-2016.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Book> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Book> Books = extractFeatureFromJson(jsonResponse);
return Books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Book JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Book> extractFeatureFromJson(String BookJSON) {
if (TextUtils.isEmpty(BookJSON)) {
return null;
}
List<Book> Books = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(BookJSON);
JSONArray BookArray = baseJsonResponse.getJSONArray("items");
for (int i = 0; i < BookArray.length(); i++) {
JSONObject currentBook = BookArray.getJSONObject(i);
JSONObject properties = currentBook.getJSONObject("volumeInfo");
String author;
if(properties.has("authors")) {
author = properties.getString("authors");
}
else {
author = "";
}
String title = properties.getString("title");
Book Book = new Book(author, title);
Books.add(Book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the Book JSON results", e);
}
return Books;
}
}
You need to override onSaveInstanceState and onRestoreInstanceState methods of Activity Class.
In onSaveInstanceState, save the list data into the Bundle.
In onRestoreInstanceState, restore the list with the Bundle data and re-create the list adapter.
Cheers!!!
if you do not have a different layout for the activity landscape mode then simply putting android:configChanges="orientation|screenLayout|screenSize" will do the job for you.
Example:
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenLayout|screenSize" />
and if you do have different layout for landscape mode the you need to override the savedInstanceState and save and restore the list accordingly in OnCreate
i have to create simple login page where after entering username and password we click to submit button. when we click on submit button then it goes to server and check the username and other information if the info matches then it moves to next activity otherwise nothing will happen . below is my code . i dont know how to do after getting response from the server.
package com.example.dev_1.myapplication;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.ReferenceQueue;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
public class MainActivity extends AppCompatActivity {
Button button;
String connectionString, params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username = (EditText) findViewById(R.id.editText);
final EditText password = (EditText) findViewById(R.id.editText2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
String userNameString = username.getText().toString();
String passwordString = password.getText().toString();
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
String params = null;
try {
params = "user=" + URLEncoder.encode(userNameString, "UTF-8") + "&password=" + URLEncoder.encode(passwordString, "UTF-8") + "&appVersion=1.26";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONArray dataJsonArr = null;
new Mytask().execute(url, params);
}
}
}));
}
private void checkLogin(String result) throws JSONException {
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
JSONArray user = null;
try{
// Creating new JSON Parser
///JSONParser jParser = new JSONParser();
// Getting JSON from URL
// JSONObject json = jParser.getJSONFromUrl(url);
if (result != null)
{
//JSONObject emp=(new JSONObject(url).getJSONObject("username"));
JSONObject emp = new JSONObject(result.toString());
String username=emp.getString("userName");
//String empspassword=emp.getString("password");
String str="username:"+username;
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("username", str);
startActivity(intent);}
}catch (Exception e) {
e.printStackTrace();
}
}
// EditText usernameString = (EditText) findViewById(R.id.editText);
// String str = usernameString.getText().toString();
// if (sharedPreferences.equals(str)) {
// Intent intent = new Intent(MainActivity.this, Main2Activity.class);
// intent.putExtra("username", str);
//startActivity(intent);
// To retrieve value from shared preference in another activity
// sharedPreferences = getApplicationContext().getSharedPreferences(
// "sharedPrefName", 0);
// id = sharedPreferences.getString("key_name", "defaultvalue");
class Mytask extends AsyncTask<String, Void, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
setProgressBarVisibility(true);
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
return getFromServer(params[0], params[1]);
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
try {
checkLogin(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getFromServer(String connectionString, String params) {
String response = "";
try {
// android.os.Debug.waitForDebugger();
URL url = new URL(connectionString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(10 * 1000); //10 Seconds
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
InputStream is = con.getInputStream();
response = read(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
return response;
}
}
private String read(InputStream in) {
BufferedReader reader;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return response.toString();
}
}
}
}
I want to use run keeper API in my Code as I am developing Application which will track walking distance etc . This can be done by using Run Keeper API.
During registering my app, it ask me to enter post call back URL , I don't know from where to get The CALL BACK URL :(
Here is the code where I am stuck.
package com.example.testapp;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button button;
private WebView webView;
private final static String CLIENT_ID = "b25ef732fdea4fc1a5d59036f05cfad0";
private final static String CLIENT_SECRET = "741a1216e5f14c38b5768840d6720d2c";
private final static String CALLBACK_URL = "";
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Force to login on every launch.
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
button = (Button) findViewById(R.id.button);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
}
#Override
public void onClick(View v) {
button.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
getAuthorizationCode();
}
private void getAuthorizationCode() {
String authorizationUrl = "https://runkeeper.com/apps/authorize";
authorizationUrl = String.format(authorizationUrl, CLIENT_ID,CALLBACK_URL);
Toast.makeText(MainActivity.this, "Milestone 1", Toast.LENGTH_SHORT).show();
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();
if (url.startsWith(CALLBACK_URL)) {
final String authCode = Uri.parse(url).getQueryParameter("code");
webView.setVisibility(View.GONE);
getAccessToken(authCode);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.loadUrl(authorizationUrl);
}
private void getAccessToken(String authCode) {
Toast.makeText(MainActivity.this, "Milestone 3", Toast.LENGTH_SHORT).show();
String accessTokenUrl = "https://runkeeper.com/apps/token";
final String finalUrl = String.format(accessTokenUrl, authCode,CLIENT_ID, CLIENT_SECRET);
Thread networkThread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(finalUrl);
HttpResponse response = client.execute(post);
String jsonString = EntityUtils.toString(response
.getEntity());
final JSONObject json = new JSONObject(jsonString);
String accessToken = json.getString("access_token");
getTotalDistance(accessToken);
} catch (Exception e) {
displayToast("Exception occured:(");
e.printStackTrace();
resetUi();
}
}
});
networkThread.start();
}
private void getTotalDistance(String accessToken) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://api.runkeeper.com/user/");
get.addHeader("Authorization", "Bearer " + accessToken);
get.addHeader("Accept", "*/*");
HttpResponse response = client.execute(get);
String jsonString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(jsonString);
findTotalWalkingDistance(jsonArray);
} catch (Exception e) {
displayToast("Exception occured:(");
e.printStackTrace();
resetUi();
}
}
private void findTotalWalkingDistance(JSONArray arrayOfRecords) {
try {
// Each record has activity_type and array of statistics. Traverse
// to activity_type = Walking
for (int ii = 0; ii < arrayOfRecords.length(); ii++) {
JSONObject statObject = (JSONObject) arrayOfRecords.get(ii);
if ("Walking".equalsIgnoreCase(statObject
.getString("activity_type"))) {
// Each activity_type has array of stats, navigate to
// "Overall" statistic to find the total distance walked.
JSONArray walkingStats = statObject.getJSONArray("stats");
for (int jj = 0; jj < walkingStats.length(); jj++) {
JSONObject iWalkingStat = (JSONObject) walkingStats
.get(jj);
if ("Overall".equalsIgnoreCase(iWalkingStat
.getString("stat_type"))) {
long totalWalkingDistanceMeters = iWalkingStat
.getLong("value");
double totalWalkingDistanceMiles = totalWalkingDistanceMeters * 0.00062137;
displayTotalWalkingDistance(totalWalkingDistanceMiles);
return;
}
}
}
}
displayToast("Something went wrong!!!");
} catch (JSONException e) {
displayToast("Exception occured:(");
e.printStackTrace();
resetUi();
}
}
private void resetUi() {
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
}
});
}
private void displayTotalWalkingDistance(double totalWalkingDistanceMiles) {
final String milesWalkedMessage = (totalWalkingDistanceMiles < 1) ? "0 miles?, You get no respect, Start walking already!!!"
: String.format("Cool, You have walked %.2f miles so far.",
totalWalkingDistanceMiles);
displayToast(milesWalkedMessage);
resetUi();
}
private void displayToast(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
}
});
}
}
I found this Runkeeper CallBack Hope it works for you. All the best.
com.example.runkeeperapi://RunKeeperIsCallingBack"