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"))
Related
I am trying to call this method from another class; it should return true or false after checking user ID and password on the server.
It always returns false even if the login process is successful because it returns the default value false before i got the request response!
I made a lot of search before posting this question but there is no clear answer on how to solve this problem.
MyHelper myHelper = new MyHelper();
myHelper.setVolleyResponseListener(new MyHelper.OnVolleyResponse()
{
#Override
public void onResponse(JSONObject jsonObject)
{
// do watever you want here with response.
}
});
if (myHelper.doBackgroundLogin(getApplicationContext())) {
uploadImageToServer();
}else{
finish();
startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
}
package com.company.testApp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by Aly on 1/11/2017.
*/
public class MyHelper {
private static AlertDialog.Builder builder;
public static Context ctx;
public static ValuesManager vm;
public static boolean status = false;
public static boolean doBackgroundLogin(final Context context) {
vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
String user_email = vm.retrieveSharedPreferences("user_email");
String user_password = vm.retrieveSharedPreferences("user_password");
Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();
//------------------------------------------------------------------------------------------
// final MyProgressDialog progressDialog;
// progressDialog = MyProgressDialog.show(context, "title", "message");
// //------------------------------------------------------------------------------------------
String url = context.getString(R.string.server_path);
Log.d("URL : ", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response : ", response); // log the error to trace it and print message to user
// progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
if( code.equals("login_true") ) {
status = true;
vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
Log.d("trace","code = " + code);
Log.d("trace","statusUpdated = " + status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user
// progressDialog.dismiss();
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("action","account_login");
params.put("email_address",vm.retrieveSharedPreferences("user_email"));
params.put("password",vm.retrieveSharedPreferences("user_password"));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
//------------------------------------------------------------------------------------------
Log.d("trace","status = " + status);
return status;
}
public interface OnVolleyResponse
{
void onResponse(JSONObject jsonObject);
}
public void setVolleyResponseListener(OnVolleyResponse responseListener)
{
this.volleyResponse = volleyResponse;
}
}
You have to use interface callback for this.
Why?
Because this is asynchronous call, and work on different thread. so your Main Thread will not wait for result of it.
Solution
Create interface in your MyHelper class
Edit
OnVolleyResponse onVolleyResponse;
public interface OnVolleyResponse
{
void onResponse(JSONObject jsonObject);
}
Create setter method for callback
public void setVolleyResponseListener(OnVolleyResponse responseListener)
{
this.volleyResponse = volleyResponse;
}
Now call this method from your Activity
MyHelper myHelper = new MyHelper();
myHelper.setVolleyResponseListener(new OnVolleyResponse()
{
#Override
public void onResponse(JSONObject jsonObject)
{
// do watever you want here with response.
}
});
if (myHelper.doBackgroundLogin(getApplicationContext())) {
uploadImageToServer();
}else{
finish();
startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
}
Note
Remove static from doBackgroundLogin method, and call it with instance of MyHelper.
Make an interface
public interface VolleyCallback{
public void onSuccess(boolean status);}
After this when you get a response you should change your doBackgroundLogin() method like this.
public static boolean doBackgroundLogin(final Context context,VolleyCallback callback) {
vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
String user_email = vm.retrieveSharedPreferences("user_email");
String user_password = vm.retrieveSharedPreferences("user_password");
Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();
String url = context.getString(R.string.server_path);
Log.d("URL : ", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response : ", response); // log the error to trace it and print message to user
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
if( code.equals("login_true") ) {
status = true;
vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
Log.d("trace","code = " + code);
Log.d("trace","statusUpdated = " + status);
callback.onSuccess(status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("action","account_login");
params.put("email_address",vm.retrieveSharedPreferences("user_email"));
params.put("password",vm.retrieveSharedPreferences("user_password"));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
Log.d("trace","status = " + status);
return status; }
Just see this callback.onSuccess(status);
This would send the response as soon as the login is successful.
onResponse method is for you volley handle this waiting for you and call onResponse method after fetching data or response from specific url.
final TextView mTextView = (TextView) findViewById(R.id.text);
...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
This is my first time making an android application that parses JSON data.
However, I'm encountering an error regarding JSON parsing. I've tried Googling the problem but most of the solutions didn't work for me.
Here are my codes:
MainActivity.java
package com.example.jsonparser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.AsyncTask;
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://pastebin.com/raw/79D93HR4";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetItems().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetItems 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 {
//JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray items = new JSONArray("");
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String ItemCode = c.getString("ItemCode");
String ItemName = c.getString("ItemName");
// tmp hash map for single item
HashMap<String, String> item = new HashMap<>();
// adding each child node to HashMap key => value
item.put("ItemCode", ItemCode);
item.put("ItemName", ItemName);
// adding item to item list
itemList.add(item);
}
} 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, itemList,
R.layout.list_item, new String[]{"ItemCode", "ItemName"}, new int[]{R.id.ItemCode,
R.id.ItemName});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java
package com.example.jsonparser;
/**
* Created by Me on 1/3/2017.
*/
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();
}
}
And here is the error code:
01-04 00:13:05.366 10069-10112/com.example.jsonparser E/MainActivity: Response from url: [{"ItemCode":"C0100001 ","ItemName":"UBNT CRM-P-CRM Point","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"},{"ItemCode":"C0100002 ","ItemName":"UBNT ETH-SP-Ethernet Surge Protector","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"}]
01-04 00:13:05.367 10069-10112/com.example.jsonparser E/MainActivity: Json parsing error: End of input at character 0 of
What am I doing wrong?
JSONArray need a json string. Pass your json in JSONArray initialize
JSONArray items = new JSONArray(jsonStr );
JSONArray items = new JSONArray("");
You're passing in an empty string to convert from json. Since there's no data in the string, its failing at character 0 with invalid input (the input isn't valid JSON).
i am just a beginner in developing android applications, i wanted to connect my application to a server so i could get data from MySQL. so i tried to make login part first but i have some problems. my code doesn't work for reading JSON.
my codes are as below:
LoginActivity(MainActivity) :
package ir.naserpour.sportclub;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class LoginActivity extends AppCompatActivity {
String link;
String response;
//get values
String username,password;
#Override
protected void attachBaseContext (Context newBase){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//define things
TextView menu = (TextView) findViewById(R.id.menu);
final EditText login_username = (EditText) findViewById(R.id.login_username);
final EditText login_password = (EditText) findViewById(R.id.login_password);
Button login_login = (Button) findViewById(R.id.login_login);
Button login_register = (Button)findViewById(R.id.login_register);
CheckBox rememberme = (CheckBox)findViewById(R.id.login_remeberme);
//set icon type face
Typeface fonticon = Typeface.createFromAsset(getAssets(), "fonts/icon.ttf");
menu.setTypeface(fonticon);
login_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = login_username.getText().toString();
password = login_password.getText().toString();
//check values
if (username.length() <1 || password.length() < 1) {
Toast.makeText(getApplicationContext(), "fields cannot be empty", Toast.LENGTH_SHORT).show();
} else {
//generate link
link = "http://localhost:8080/login.php?username="+username+"&password="+password;
login();
if(response=="true"){
Toast.makeText(getApplicationContext(), "true", Toast.LENGTH_SHORT).show();
}else if(response=="false"){
Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
protected void onPause () {
super.onPause();
finish();
}
public String login() {
new JSONParse().execute();
return response;
}
public class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"getting data ...",Toast.LENGTH_SHORT).show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(link);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
try {
JSONArray result = json.getJSONArray("result");
JSONObject c = result.getJSONObject(0);
try {
String res = new String(c.getString("response").getBytes("ISO-8859-1"), "UTF-8");
response = res;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java:
package ir.naserpour.sportclub;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.io.UnsupportedEncodingException;
/**
* Created by Mohammad Naserpour on 9/22/2016.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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 = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try 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;
}
}
and also my login.php script:
<?php
define("HOST","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("NAME","users");
$con = mysqli_connect(HOST,USERNAME,PASSWORD,NAME);
$username = $_GET["username"];
$password = $_GET["password"];
$sql = "SELECT * FROM userinfo WHERE username ='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo '{"result":[{"response":"true"}]}';
}else{
echo '{"result":[{"response":"false"}]}';
}
mysqli_close($con);
?>
i would be so happy if i find out the problem. thank you.
see this tutorial :
its a full tutorial about login process using google volley
First : On device side, Use volley, its simple and easy to use
Second : On server, what is {"result":[{"response":"true"}]}
any problem with {"result":true} ??
Last but not the least : Did you use JSON before or this code is trial and error copy paste from some tutorials?
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.....
}
});
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"