here is my java file and i used onclick function in my xml file as same method working for login button but not for signup please help me to solve this issue.
public class signup extends ActionBarActivity {
EditText username, pass, cpass, mail, phn;
String uname, password, confirmpass, email, phone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
username = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
cpass = (EditText) findViewById(R.id.comfirmpass);
mail = (EditText) findViewById(R.id.email);
phn = (EditText) findViewById(R.id.phone);
Button signupbutton = (Button) findViewById(R.id.signupbutton);
}
//When the send button is clicked
public void sign(View v) {
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
//Method to get list value pair and form the query
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
//Data intialization and Validation
public void validate() {
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
if (password.equals(confirmpass)) {
post();
} else {
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
public void error(boolean flag, String etext) {
if (flag == true) {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
//Code to handle failure
} else {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
setContentView(R.layout.login);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Method to post data to webservice
public void post() {
try
{
// Calling async task to get json
new DownloadOperation().execute();
}
catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadOperation extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
String uname = "";
String email = "";
String password = "";
String confirmpass = "";
String phone = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
//Initiate ProgressBar
dialog = ProgressDialog.show(signup.this, "Please Wait", "Registering ...");
}
#Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
dialog.dismiss();
Log.d("tag", "Result:\n" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String message = jsonObj.getString("message");
boolean error = jsonObj.getBoolean("error");
error(error,message);
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
}
Have you mention android:onClick="sign" in your signup.xml under layout directory? Please make sure it.
I think your code is corect.
add Log to sign function:
public void sign(View v) {
Log.e("tag","sign function called");
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
if corect, you can show log is: "sign function called"
simply add this on your onCreate() method
signupbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"Button is clicked", 3000).show();
///what ever you want to do on signupbtn comes here
//add this try block if you need same functionality as `sign() method`
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
});
and every time you cliecked signupbutton this method(Listener) will called.
Or
add this line in you xml file where you define the signupbutton
android:onClick="sign"
But the best way for me is to add clickListener as it makes it very clear from java class side that what is beaing called on clicking the button.
Related
Android code is here
public class NewLogin extends ActionBarActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(NewLogin.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myusername", uname));
nameValuePairs.add(new BasicNameValuePair("mypassword", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"www.sample.com/home_webservice.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(NewLogin.this, Sample.class);
/* intent.putExtra(USER_NAME, username);
finish();*/
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
JSON CODE IS HERE
<?php
require '../db_connect.php';
if (isset($_GET['username']) && isset($_GET['password']))
{
$myusername = $_GET['username'];
$mypassword = $_GET['password'];
$sql = "SELECT * FROM user_registration WHERE (username = '$myusername' or email = '$myusername' or phone = '$myusername')";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0){
$response["VerifiedMember"] = array();
$row = mysqli_fetch_array($result);
$VerifiedMember = array();
$id=$row['id'];
$phone=$row['phone'];
$reg_type=$row['register_type'];
$stored_salt = $row['salt'];
$stored_hash = $row['hashed_password'];
$check_pass = $stored_salt . $mypassword;
$check_hash = hash('sha512',$check_pass);
if($check_hash == $stored_hash){
$VerifiedMember['user_id'] = $id;
$VerifiedMember['first_name']=$row['first_name'];
$VerifiedMember['phone']=$row['phone'];
array_push($response["VerifiedMember"], $VerifiedMember);
if(!empty($phone)&& $reg_type==1){
$sql="select * from user_otps where user_id='".$id."'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_array($result);
if($row['verified']==0)
{
//no product found
$response["success"] = 0;
$response["message"] = "failure";
// echo no users JSON
echo json_encode($response);
}
else
{
//no product found
$response["success"] = 1;
$response["message"] = "success";
// echo no users JSON
echo json_encode($response);
}
}
}
else{
//no product found
$response["success"] = 1;
$response["message"] = "success";
// echo no users JSON
echo json_encode($response);
}
//echo json_encode($response);
}
else{
//no product found
$response["success"] = 0;
$response["message"] = "invalid";
// echo no users JSON
echo json_encode($response);
}
}
else{
//no product found
$response["success"] = 0;
$response["message"] = "invalid";
// echo no users JSON
echo json_encode($response);
}
}
?>
Here i m getting Invalid username and password please help me to get users details from json file in android
how to solve this can anyone tell me ??
Here i m getting Invalid username and password please help me to get users details from json file in android
how to solve this can anyone tell me ??
Simply You try,
public class NewLogin extends ActionBarActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
}
public void invokeLogin(View view){
new loginAccess().execute();
}
class loginAccess extends AsyncTask<String, String, String> {
String access;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
String url = "http://uat.ziplife.in/mobileapp/login_webservice.php";
JSONObject json = null;
try {
params.add(new BasicNameValuePair("myusername", username));
params.add(new BasicNameValuePair("mypassword", password));
json = jsonParser.makeHttpRequest(url, "POST", params);
Log.d("TESS :: ", json.toString());
String status = json.getString("sucess");
Log.d("Success Response :: ", status);
if (status.equals("success")) {
Intent i = new Intent(NewLogin.this, Sample.class);
startActivity(i);
}
else if(json.getString("status").trim().equalsIgnoreCase("failed"))
{
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
Try this
<?php
require '../db_connect.php';
if (isset($_POST['myusername']) && isset($_POST['mypassword']))
{
$myusername = $_POST['myusername']; \\ change
$mypassword = $_POST['mypassword']; \\ change
Edit your 2 line
This question already has answers here:
Android Gradle Apache HttpClient does not exist?
(15 answers)
Closed 6 years ago.
I have code for login activity in android studio using php sql with it
this is the code :-
public class MainActivity extends ActionBarActivity {
protected EditText username;
private EditText password;
protected String enteredUsername;
private final String serverUrl = "http://192.168.0.103/androidlogin/index.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.username_field);
password = (EditText)findViewById(R.id.password_field);
Button loginButton = (Button)findViewById(R.id.login);
Button registerButton = (Button)findViewById(R.id.register_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enteredUsername = username.getText().toString();
String enteredPassword = password.getText().toString();
if(enteredUsername.equals("") || enteredPassword.equals("")){
Toast.makeText(MainActivity.this, "Username or password must be filled", Toast.LENGTH_LONG).show();
return;
}
if(enteredUsername.length() <= 1 || enteredPassword.length() <= 1){
Toast.makeText(MainActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(serverUrl, enteredUsername, enteredPassword);
}
});
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", params[1]));
nameValuePairs.add(new BasicNameValuePair("password", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == 0){
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if(jsonResult == 1){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result){
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
with 21 sdk version it work so perfect but when i try to change the gradle file to 25 version i had many red lines under http connection code
so what's the solution how can i upgrade the sdk to 25 without get any problems ?
thanks alot
HttpCLient has been removed in SDK 23. You should add Apache Http library manually:
android {
useLibrary 'org.apache.http.legacy'
}
You have to replace the HttpClient with HttpURLConnection. Check this link for more info: Android Gradle Apache HttpClient does not exist?
I am developing an app in which a login screen is visible to user and what I have to send to server is mobilenumber,password and isfirst true to server when user logging in first time and when user logout and again login I have to send isFirst false to server ,How can I achieve this problem.
Note:- I dont have to check value from shared Preference, I have to send isFirst true or false on user login first time and second time,first time is true and second time false to server using Jsons.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://543.168.0.110:8080/ireward/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public ProgressDialog m_PDialog;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public Snackbar m_SnackBar;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
public boolean isFirstTimeLogin = true;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
m_oLoginSession = new CLoginSessionManagement(getActivity());
Toast.makeText(getActivity(), "User Login Status: " + m_oLoginSession.isLogin(), Toast.LENGTH_LONG).show();
init();
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setBackgroundColor(Color.TRANSPARENT);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
m_PDialog = new ProgressDialog(getActivity());
m_PDialog.setMessage("Please wait while Logging...");
m_PDialog.setCancelable(false);
m_PDialog.show();
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
// httpPost.setHeader("Accept", "application/json"); ///not required
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
}
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
m_PDialog.dismiss();
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter valid mobile number", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Invalid Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
m_SnackBar = Snackbar.make(m_MainLayout, "You are bloacked", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Connection Lost", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
m_SnackBar = Snackbar.make(m_MainLayout, "User not found ! Kindly Register", Snackbar.LENGTH_LONG);
m_SnackBar.show();
}
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
}
}
This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.
Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.
Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.
i am building an application in which i prompt users to register. I have a django-restful server running at back end , and i m trying to make HTTP post requests to my server on android client with DefaultHttpClient class. I get email, username etc from user and at the button's onClick event, i create an AsnycTask to execute the request. Here is the code for the activity:
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String userName = usernameEditText.getText().toString();
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if( userName != null && email != null && password != null) {
new RegisterEventHandler().execute(userName , email , password);
}
}
});
....
class RegisterEventHandler extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
RequestHandler handler = new RequestHandler();
return handler.register(params[0], params[1], params[2]);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if( result ) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterSuccessfullTitle);
builder.setMessage(R.string.RegisterSuccessfullMessage);
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent redirect = new Intent(getApplicationContext() , SmartMapMainActivity.class);
startActivity(redirect);
}
});
builder.create().show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterFailedTitle);
builder.setMessage(R.string.RegisterFailedMessage);
builder.create().show();
}
}
}
The RequestHandler class :
public class RequestHandler {
public boolean register(String userName , String email , String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.0.1/users/");
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", userName);
jsonObj.put("email", email);
jsonObj.put("password", password);
StringEntity entity = new StringEntity(jsonObj.toString());
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200)
return true;
else
return false;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
The problem is, DefaultHttpClient's connManager(ClientConnectionManager) is always null and on the execute() method of the HttpClient, it always throws an IOException. I tried initializing the DefaultHttpClient in my activity , rather than in the AsyncTask's doInBackground method , but the result was the same.