I'm facing an issue with AsyncTask doInBackground method, I don't know how to stop this method from running.
I'm working on an application that has a login screen which retrieves information about the logged user. The problem is when I enter a wrong password or username and then when I re-enter the correct data, my application crashes and I get
"java.lang.IllegalStateException: Cannot execute task: the task has
already been executed"
How can I stop this thread from running? Here is the code:
LoginActivity.java
public class LoginActivity extends Activity implements LoginParser.GetLoginListener{
public LoginParser parser1;
public EditText ETUsername;
public EditText ETPassword;
//private LoginParser lb;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
parser1 = new LoginParser();
ETUsername = (EditText)findViewById(R.id.ET1);
ETPassword = (EditText)findViewById(R.id.ET2);
final Button button = (Button) findViewById(R.id.loginBut);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String UserName = ETUsername.getText().toString();
String Password = ETPassword.getText().toString();
Log.e("LoginAct .. userName: ", UserName);
Log.e("LoginAct .. Password: ", Password);
if (UserName.isEmpty() || Password.isEmpty()) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Please Enter your Username and Password")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
else{
parser1.getLoginInfo(UserName, Password);
parser1.setListener(LoginActivity.this);
}
} // end of button on click
} );
}
#Override
public void didReceivedUserInfo(String displayName) {
if(displayName != null) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Welcome").setMessage("Welcome " + displayName)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent (LoginActivity.this, MainActivity.class);
startActivity(in);
}
}).show();
}
else {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Error in login ID or Password, Please try again later")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
LoginParser.java
public class LoginParser extends AsyncTask <Void,Void,String> {
private String requestURL;
public String UserName ;
public String Password ;
public interface GetLoginListener
{
public void didReceivedUserInfo (String displayName);
}
private GetLoginListener listener;
public GetLoginListener getListener() {
return listener;
}
public void setListener(GetLoginListener listener) {
this.listener = listener;
}
public void getLoginInfo(String userName , String password)
{
requestURL = "some link";
this.UserName = userName ;
this.Password = password ;
execute(); // it will call doInBackground in secondary thread
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(requestURL);
HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();
String jsonString = "LID="+ UserName +"&PWD="+Password+"&Passcode=****";
Log.e("LoginParser","JSONString: " + jsonString);
urlConnection1.setDoOutput(true);
urlConnection1.setRequestMethod("POST");
urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection1.setRequestProperty("charset","utf-8");
PrintWriter out = new PrintWriter(urlConnection1.getOutputStream());
// out.print(this.requestMessage);
out.print(jsonString);
out.close();
int statusCode = urlConnection1.getResponseCode();
Log.d("statusCode", String.valueOf(statusCode));
StringBuilder response = new StringBuilder();
byte[] data = null;
if (statusCode == HttpURLConnection.HTTP_OK)
{
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection1.getInputStream()));
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
data = response.toString().getBytes();
}
else {
data = null;// failed to fetch data
}
String responseString = new String(data);
Log.e("doInBackground", "responseString" + responseString);
JSONObject jsonObject2 = new JSONObject(responseString);
String Status = jsonObject2.getString("Status");
Log.e("Status", Status);
if (Status.equals("s")) {
Log.i("Status:", "Successful");
String displayName = jsonObject2.getString("DisplayName");
return displayName;
}
else {
return null;
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String displayName) {
super.onPostExecute(displayName);
Log.e("onPost: ","onPost");
listener.didReceivedUserInfo(displayName);
}
}
Thank you for your help.
The "can't re-execute task" error can be solved by creating a new instance of the AsyncTask. You can't call execute twice on the same instance, but you can make as many instances as you want.
Stopping the execution won't help that error. The problem isn't that its currently running, the problem is that you need to create a new instance and run that instead.
You can cancel Async task using continuous check of isCancel in your doInBackground method.
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
Hope this will help you.
Related
I updated the code again and after calling the API its show the null. I don't understand it why i getting this problem in my code. I parse it properly but still i getting problem in signup and login in API. How its work to show the data in the sql database?
MainActivity.java (This is a Registration form )
public class MainActivity extends AppCompatActivity {
Button register, log_in;
EditText Username, Email, Password, Mobile ;
String Username_Holder, Email_Holder, PasswordHolder, MobileHolder;
String finalResult ;
String HttpURL = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
Boolean CheckEditText ;
ProgressDialog progressDialog;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Assign Id'S
Username = (EditText)findViewById(R.id.username);
Email = (EditText)findViewById(R.id.Email);
Password = (EditText)findViewById(R.id.password);
Mobile = (EditText)findViewById(R.id.mobile);
register = (Button)findViewById(R.id.Submit);
log_in = (Button)findViewById(R.id.Login);
//Adding Click Listener on button.
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Checking whether EditText is Empty or Not
CheckEditTextIsEmptyOrNot();
if(CheckEditText){
// If EditText is not empty and CheckEditText = True then this block will execute.
UserRegisterFunction(Username_Holder,Email_Holder, PasswordHolder, MobileHolder);
}
else {
// If EditText is empty then this block will execute .
Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
log_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,UserLoginActivity.class);
startActivity(intent);
}
});
}
public void CheckEditTextIsEmptyOrNot(){
Username_Holder = Username.getText().toString();
Email_Holder = Email.getText().toString();
PasswordHolder = Password.getText().toString();
MobileHolder = Mobile.getText().toString();
if(TextUtils.isEmpty(Username_Holder) || TextUtils.isEmpty(Email_Holder) || TextUtils.isEmpty(PasswordHolder) || TextUtils.isEmpty(MobileHolder))
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
public void UserRegisterFunction(final String Username, final String Email, final String Password, final String Mobile){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog.dismiss();
Toast.makeText(MainActivity.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
hashMap.put("username",params[0]);
hashMap.put("email",params[1]);
hashMap.put("password",params[2]);
hashMap.put("mobileno",params[3]);
finalResult = httpParse.postRequest(hashMap, HttpURL);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(Username,Email,Password,Mobile);
}
}
UserLoginActivity.java
public class UserLoginActivity extends AppCompatActivity {
EditText Email, Password;
Button LogIn ;
String PasswordHolder, EmailHolder;
String finalResult ;
String HttpURL = "http://codexpertise.com/codexpertise.com/apitest/login.php";
Boolean CheckEditText ;
ProgressDialog progressDialog;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
public static final String UserEmail = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
Email = (EditText)findViewById(R.id.email);
Password = (EditText)findViewById(R.id.password);
LogIn = (Button)findViewById(R.id.Login);
LogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckEditTextIsEmptyOrNot();
if(CheckEditText){
UserLoginFunction(EmailHolder, PasswordHolder);
}
else {
Toast.makeText(UserLoginActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
}
public void CheckEditTextIsEmptyOrNot(){
EmailHolder = Email.getText().toString();
PasswordHolder = Password.getText().toString();
if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
public void UserLoginFunction(final String email, final String password){
class UserLoginClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(UserLoginActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog.dismiss();
if(httpResponseMsg.equalsIgnoreCase("Data Matched")){
finish();
Intent intent = new Intent(UserLoginActivity.this, DashboardActivity.class);
intent.putExtra(UserEmail,email);
startActivity(intent);
}
else{
Toast.makeText(UserLoginActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMap.put("username",params[0]);
hashMap.put("password",params[1]);
finalResult = httpParse.postRequest(hashMap, HttpURL);
return finalResult;
}
}
UserLoginClass userLoginClass = new UserLoginClass();
userLoginClass.execute(email,password);
}
}
HttpParse.java
public class HttpParse {
String FinalHttpData = "";
String Result ;
BufferedWriter bufferedWriter ;
OutputStream outputStream ;
BufferedReader bufferedReader ;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
I made the login and signup page in android. I want correct data enter in the login form and than its login but when i use incorrect username and password its still login and shows the error like this :- org.json.JSONException: No value for res_response because when i signup the page my data going on the server through url in the format of JSON object.
Registration.java
public class Registration extends Activity {
EditText username, email, password, mobile;
String url = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
Button btnRegister;
ImageButton btnfb;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
username = (EditText) findViewById(R.id.editname);
email = (EditText) findViewById(R.id.editemail);
password = (EditText) findViewById(R.id.editpassword);
mobile = (EditText) findViewById(R.id.editmobile);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnfb = (ImageButton) findViewById(R.id.btnfb);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = username.getText().toString().trim();
final String emaill = email.getText().toString().trim();
final String passwordd = password.getText().toString().trim();
final String mobilee = mobile.getText().toString().trim();
compare_version();
Log.e("TAG","Message");
if (TextUtils.isEmpty(name)) {
username.setError("Please enter username");
username.requestFocus();
return;
}
if (TextUtils.isEmpty(emaill)) {
email.setError("Please enter your email");
email.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) {
email.setError("Enter a valid email");
email.requestFocus();
return;
}
if (TextUtils.isEmpty(passwordd)) {
password.setError("Enter a password");
password.requestFocus();
return;
}
if (TextUtils.isEmpty(mobilee)) {
mobile.setError("Enter a mobile number");
mobile.requestFocus();
return;
}
}
});
btnfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.facebook.com/"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
private void compare_version() {
JSONObject parameters = new JSONObject();
try {
parameters.put("type", "signup");
parameters.put("username", username.getText().toString());
parameters.put("email", email.getText().toString());
parameters.put("mobileno", mobile.getText().toString());
parameters.put("password", password.getText().toString());
} catch (JSONException e) {
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, parameters,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String resp_code = jsonObject.getString("resp_code");
String resp_msg = jsonObject.getString("res_response");
System.out.println("response version =====" + response);
resp_code = "200";
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
}
Mainactivity.java (Its login)
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
String url = "http://codexpertise.com/codexpertise.com/apitest/login.php";
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, passwordd;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
passwordd = (EditText)findViewById(R.id.password);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = username.getText().toString().trim();
final String pass = passwordd.getText().toString().trim();
compare_version();
Log.e("TAG","Message");
if (TextUtils.isEmpty(name)) {
username.setError("Please enter username");
username.requestFocus();
return;
}
if (TextUtils.isEmpty(pass)) {
passwordd.setError("Please enter your Password");
passwordd.requestFocus();
return;
}
else {
Intent i = new Intent(MainActivity.this,Userlist.class);
startActivity(i);
}
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private void compare_version() {
JSONObject parameters = new JSONObject();
try {
parameters.put("type", "userlogin");
parameters.put("username", username.getText().toString());
parameters.put("password", passwordd.getText().toString());
} catch (JSONException e) {
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, parameters,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String resp_code = jsonObject.getString("resp_code");
String resp_msg = jsonObject.getString("res_response");
System.out.println("response version =====" +response);
resp_code = "200";
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg=="+resp_msg);
Toast.makeText(MainActivity.this, "response msg=="+resp_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
Change this:
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
}
To:
if (resp_code.equals("200")) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Registration.this,"Donot Match",Toast.LENGTH_SHORT).show();
}
call compare_version() method in else condition
First you have to understand the different between the login success response and the login failed(on a wrong username password combination) response.
You are reading "res_response" value from your JSON response although it is not in your login failed response.
Also you did a mistake in your code by hard-coding resp_code = "200";
I am working with android studio and whenever I try to connect to internet it show Dialog that "Unfortunately 'app name' stopped" and then if crashes.
I have updated the manifest file for permission as well. please provide any assistance, It might helpful.
Here is the code:
public class Login extends Activity {
TextView msg;
String user,pass;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText password;
TextView regLabel;
Button loginbt;
final EditText username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
regLabel = (TextView) findViewById(R.id.register_label);
msg = (TextView) findViewById(R.id.alert);
regLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent register_form = new Intent(Login.this,Register.class);
startActivity(register_form);
}
});
loginbt = (Button) findViewById(R.id.login);
loginbt.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
user = username.getText().toString();
pass = password.getText().toString();
if(user.length()>0 && pass.length()>0) {
try {
new LoginProcess().execute("http://url.com");
} catch (Exception le) {
msg.setText("Error:" + le);
}
}else{
msg.setText("Please Enter Username and Password!");
}
}
});
}
public class LoginProcess extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Login.this);
protected void onPreExecute(){
Dialog.setMessage("Checking Authentication..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
if (Error != null) {
msg.setText("Error in Login: " + Error);
} else {
try {
JSONObject jsonObj = new JSONObject(Content);
String orgPass = jsonObj.getString("password");
if (orgPass.equals(pass)) {
Intent rp = new Intent(Login.this, Menu.class);
startActivity(rp);
finish();
} else {
msg.setText("Wrong Password");
}
} catch (Exception je) {
msg.setText("Error:" + je);
}
}
}
}
}
I am new to android JSON programming. I want to use set and get function in this program ,but when i used get() for full_name,getting null.
public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
private void getLogin(JSONObject response) {
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
LoginBean loginBean = new LoginBean();
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
LoginBean loginBean = new LoginBean();
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
}
JSON Input:
"{
""user_name"":""ashish#soms.in"",
""user_password"":""123456"",
""device_token"":""1111"",
""mac_address"":""1111"",
""gps_latitude"":""1111"",
""gps_longitude"":""1111""
}"
Here is JSON Response:
{
""data"": {
""user_id"": ""90"",
""full_name"": ""ashish"",
""display_name"": ""ashish"",
""user_image"": ""images/noimage.png"",
""gender"": ""0"",
""authorization_key"": ""4eef1d65f7b470dbca881fe6452ec11457f54489""
}
}
pls comment line LoginBean loginBean = new LoginBean(); then try .
try this code
private void getLogin(JSONObject response) {
LoginBean loginBean=null;
if (response != null){
try {
loginBean = new LoginBean();
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}
I'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});
Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.