How to Implement / Link Run Keeper API in Android using Eclipse? - java

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"

Related

caused by: Can't toast on a thread that has not called Looper.prepare()

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

How to use user input to open api JSON [duplicate]

This question already has answers here:
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
(5 answers)
Closed 3 years ago.
I am working on an Android app in which I am making a weather app. The application opens api data from a JSON and displays this information. More specifically it takes the user input of a city or zip code and adds this info to the URL for the API and then executes the URL.
MainActivity.java
package com.shanehampcsci3660.weather;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//import static com.shanehampcsci3660.weather.GetJsonData.*;
public class MainActivity extends AppCompatActivity
{
public static TextView tempTV, jsonTV;
public EditText cityORZipET;
private Button getWeather;
public String zip, cityOrZip;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTV = (TextView) findViewById(R.id.tempTV);
jsonTV = (TextView) findViewById(R.id.jsonFeedTV);
cityORZipET = (EditText) findViewById(R.id.cityORZipET);
getWeather = (Button) findViewById(R.id.getWeatherButton);
//cityOrZip = cityORZipET.getText().toString();
getWeather.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
GetJsonData getJsonData = new GetJsonData();
//getJsonData.execute();
cityOrZip = cityORZipET.getText().toString();
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
jsonTV.setText(cityOrZip);
/*if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=x");
}*/
}
});
}
}
GetJsonData.java
package com.shanehampcsci3660.weather;
import android.os.AsyncTask;
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;
public class GetJsonData extends AsyncTask<Void, Void, Void>
{
public String data= "", line = "", name = "";
double temp, minTemp, maxTemp;
#Override
protected Void doInBackground(Void... voids)
{
try
{
URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q=30528&appid=id");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while(line != null)
{
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jsonObject = new JSONObject(data);
JSONObject main = jsonObject.getJSONObject("main");
name = jsonObject.getString("name");
temp = main.getDouble("temp");
minTemp = main.getDouble("min_temp");
maxTemp = main.getDouble("max_temp");
/*JSONObject jsonObject = new JSONObject(result);
JSONObject jsonData = new JSONObject(jsonObject.getString("main"));
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
String description, icon, iconURI;
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonData1 = jsonArray.getJSONObject(i);
description = jsonData1.getString("description");
MainActivityController.description.setText(description);
icon = jsonData1.getString("icon");
iconURI = "http://openweathermap.org/img/w/" + icon + ".png";
Picasso.get().load(iconURI).into(MainActivityController.conditionImageView);
}*/
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
//MainActivity.jsonTV.setText(data);
MainActivity.tempTV.setText("City:\t" + name + "\tTemp:\t" + temp);
Log.d("Json Feed", name + "Temp: " + temp);
}
public static void execute(String s) {
}
}
My issue is that no matter where I put...
if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=id");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=id");
}
...It will only show the data of the default Url opened in GetJsonData.java. My question is what am I doing wrong and what should I correct in order to make my app work with the user input like it should.
you are calling an GetJsonData.execute with the url that contains the client data, but it has no code in it. Looking at your current code the zip that the client inputs does not get stored into the worker class.
This is because you always use the same URL in GetJsonData class. According to question What arguments are passed into AsyncTask? your class declaration should look like:
public class GetJsonData extends AsyncTask<String, Void, YourPojo> {
#Override
protected YourPojo doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]);
...
} catch (Exception e) {
handle(e);
}
}
}
where YourPojo is a class you need to create to store all properties you need to read from JSON payload:
class YourPojo {
private String data;
private String line;
private String name;
private double temp;
private double minTemp
private double maxTemp;
// getters, setters
}

onPostExecute of AsyncTask not called

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) {
}
}

Android string.equals() doesn't match condition

I've been working with Volley on Android, it seems that I can't really get this particular part working
this is my json
{
"code": 1,
"status": ​200,
"data": "bla... bla..."
}
and this is Activity.class
try
{
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
if (status.equals("200"))
{
do something
}
else
{
Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG).show();
}
}
it always skips that condition as it doesn't match, and toast print value 200 as a proof that status returns with value and that value is 200
I did try
int status = json_response.getInt("status");
if (status == 200)
which return "JSONException: Value of type java.lang.String cannot be converted to JSONObject", any insights?
Edit:
here is complete LoginActivity.java
package my.sanik.loginandregistration.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import my.sanik.loginandregistration.R;
import my.sanik.loginandregistration.app.AppConfig;
import my.sanik.loginandregistration.app.AppController;
import my.sanik.loginandregistration.helper.SessionManager;
public class LoginActivity extends Activity
{
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn())
{
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty())
{
// login user
checkLogin(email, password);
}
else
{
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
finish();
}
});
}
private void checkLogin(final String email, final String password)
{
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try
{
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
if (status.equals("200"))
{
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
// Error in login. Get the error message
Toast.makeText(getApplicationContext(), "Wrong username or password", Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams()
{
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog()
{
if (!pDialog.isShowing()) pDialog.show();
}
private void hideDialog()
{
if (pDialog.isShowing()) pDialog.dismiss();
}
}
First try to print your response check what is your response say or some extra thing is there or not.
try{
Log.d(TAG, "Json response :" + response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and then compare with your value.
{
"code": 1,
"status": ​200, // Need this
"data": "bla... bla..."
}
Your status is not String format so,
Call this
int getStatus = Integer.parseInt(json_response.getString("status"));
Then
if (getStatus==200)
{
// Your code
}
Note :
You can use getInt directly instead of getString .
Use this class to get json string
ServiceHandler.java
package com.example;
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.URL;
import android.util.Log;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeMyServiceCall(url, method);
}
public String makeMyServiceCall(String myurl, int method) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(myurl);
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
}
} catch (Exception e) {
Log.d("tag", e.getLocalizedMessage());
}
return response;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
/* Close Stream */
if (null != inputStream) {
inputStream.close();
}
return result;
}
}
in MainActivty.java
package com.example;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
String jsonStr = "";
JSONObject jo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetDatas().execute();
}
class GetDatas extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// put your url here...
// Making a request to url and getting response
jsonStr = sh.makeServiceCall("http://192.168.1.51/sumit/temp.txt",
ServiceHandler.GET);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
jo = new JSONObject(jsonStr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (jo.getInt("status") == 200) {
Toast.makeText(getApplicationContext(), "do something",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"" + jo.getInt("status"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ok if the problem is that either String or Integer is throwing an exception (which I cannot replicate in Android Studio 1.5.1), I recommend you to do this:
try
{
JSONObject json_response = new JSONObject(response);
Object status = json_response.getString("status");
if (json_response.get("status") instanceof Integer)
{
// it's an integer
}
else if (json_response.get("status") instanceof String)
{
// it's a String
} else {
// let's try to find which class is it
Log.e("MYTAG", "status is an instance of "+json_parse.get("status").getClass().getName());
}
} catch (Exception e) {
Log.e("MYTAG", "Error parsing status => "+e.getMessage());
}
Also you can try doing this first:
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
int statint = Integer.parseInt(status);
I hope it helps.
Try with this
if(status.equalsIgnoreCase("200"))

Android App Crashes when no internet connection due to Can't create handler inside thread that has not called Looper.prepare()

I'm developing my android app for a conference. In, my login page I printed an error message when no internet connection. but, the app crashes when no internet connection and following error message display in logcat.
I followed many questions from stack overflow and may be I can't understand, I couldn't find my answer.
08-19 10:01:21.840
8931-9124/com.NICT.nict E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-691
java.lang.RuntimeException: Can't create handler inside thread that hasnot called Looper.prepare()
at android.os.Handler.<init>(Handler.java:205)
at android.os.Handler.<init>(Handler.java:119)
atandroid.widget.Toast$TN.<init>(Toast.java:325)
atandroid.widget.Toast.<init>(Toast.java:91)
atandroid.widget.Toast.makeText(Toast.java:239)
at com.NICT.nict.services.MessageHandler.showMessage(MessageHandler.java:9)
at com.NICT.nict.LoginActivity$1$1.run(LoginActivity.java:117)
at java.lang.Thread.run(Thread.java:838)
Here is my login activity
package com.NICT.nict;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.NICT.nict.WorkShopActivity.HttpAsyncTask;
import com.NICT.nict.services.EmailValidator;
import com.NICT.nict.services.MessageHandler;
import com.NICT.nict.services.ServiceHandler;
public class LoginActivity extends Activity {
public final static String URL = "http://demo.et.lk/nitcapi/api/login";
public static String Uid;
private Button loginBtn;
private EditText codeEdit;
private EditText nameEdit;
private EditText emailEdit;
private ServiceHandler sh = new ServiceHandler();
private boolean errorStatus;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginBtn = (Button) findViewById(R.id.loginBtn);
codeEdit = (EditText) findViewById(R.id.codeEdit);
nameEdit = (EditText) findViewById(R.id.nameEdit);
emailEdit = (EditText) findViewById(R.id.emailEdit);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
new Thread(new Runnable() {
public void run() {
String code = codeEdit.getText().toString();
String email = emailEdit.getText().toString();
String name = nameEdit.getText().toString();
if (code.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter the app code",
getApplicationContext());
errorStatus = true;
}
});
;
} else if (name.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Name",
getApplicationContext());
errorStatus = true;
}
});
;
} else if (email.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Email",
getApplicationContext());
errorStatus = true;
}
});
;
}
EmailValidator emailValidator = new EmailValidator();
if(!emailValidator.validate(email)){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Invalid Email",
getApplicationContext());
errorStatus = true;
}
});
;
}
String jsonStr = null;
if (!errorStatus) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
} else {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// notify user you are online
try{
runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.VISIBLE);
}
});
;
jsonStr = sh.makeServiceCall(URL + "/" + code + "/"
+ name + "/" + email, ServiceHandler.GET);
System.out.println(URL + "/" + code + "/" + name + "/"
+ email);
}
catch (Exception e){
spinner.setVisibility(View.GONE);
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
});
;
}
}
if (jsonStr != null) {
String status = "";
String msg = "";
try {
JSONObject jsonObj = new JSONObject(jsonStr);
runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.GONE);
}
});
;
if (jsonObj != null
&& jsonObj.has("status")) {
status = jsonObj.getString("status");
msg = jsonObj.getString("message");
if(jsonObj.has("uid"))
Uid = jsonObj.getString("uid");
System.out.println(jsonObj);
if (status.equals("OK")) {
Intent myIntent = new Intent(
getBaseContext(),
MainMenuActivity.class);
startActivityForResult(myIntent, 0);
} else if (status.equals("ERROR")) {
final String errorMsg = msg;
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
errorMsg,
getApplicationContext());
}
});
;
} else {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
"Oops..! something wrong with the service. Please try again Later.",
getApplicationContext());
}
});
;
}
}
} catch (Exception e) {
System.out
.println("Creation of json object failed");
}
}
}
}
}).start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
Here is my serviceHandler.
package com.NICT.nict.services;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public static boolean isOnline(Context ctx) {
ConnectivityManager cm;
NetworkInfo info = null;
try {
cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
info = cm.getActiveNetworkInfo();
} catch (Exception e) {
e.printStackTrace();
}
return (info!=null&&!info.equals(null));
}
}
add this following snippet in your if condition::
if (!ServiceHandler.isOnline(getApplicationContext())) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable()
{
#Override
public void run()
{
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
}
);
}
Try this.when you see runtimeException due to Looper not prepared before handler.
Handler handler = new Handler(Looper.getMainLooper());
From Android Docs:
LOOPER
Class used to run a message loop for a thread. Threads by default do
not have a message loop associated with them; to create one, call
prepare() in the thread that is to run the loop, and then loop() to
have it process messages until the loop is stopped.
Looper.getMainLooper()
Returns the application's main looper, which
lives in the main thread of the application.
I hope it helps!
Android basically works on two thread types namely UI thread and background thread.
Try this,
activity.runOnUiThread(new Runnable() {
public void run() {
//run your code here.....
}
});

Categories