Error on Logging in Still prompts but still Logs in - android

I am developing a mobile application that has 2 types of users.
In my php code, I separated the boolean for each user. success for the client and success1 for the stylist.
When I press log in, the error prompts first following is the fast intent for the successful menu profile.
This is my line of codes from LoginRegister.java
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText userLoginUsername = (EditText) findViewById(R.id.loginUser);
final EditText userLoginPassword = (EditText) findViewById(R.id.loginPass);
final Button Login = (Button) findViewById(R.id.buttonLogin);
final Button Register = (Button) findViewById(R.id.buttonRegister);
loading = findViewById(R.id.loadinglogin);
//login
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = userLoginUsername.getText().toString();
final String password = userLoginPassword.getText().toString();
if(!username.isEmpty() && !password.isEmpty()) {
Login.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
boolean success1 = jsonResponse.getBoolean("success1");
//Client's Log in
if (success) {
//gikan sa php (green ones) to strings sa android
String username = jsonResponse.getString("username");
String name = jsonResponse.getString("name");
String number = jsonResponse.getString("number");
String gender = jsonResponse.getString("gender");
String address = jsonResponse.getString("address");
String occupation = jsonResponse.getString("occupation");
String birth_date = jsonResponse.getString("birth_date");
String user_type = jsonResponse.getString("user_type");
Intent intent = new Intent(LoginRegister.this, ProfileActivity.class);
//from strings to pass sa lain intents.
intent.putExtra("username",username);
intent.putExtra("number",number);
intent.putExtra("name", name);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
intent.putExtra("occupation", occupation);
intent.putExtra("birthDate", birth_date);
intent.putExtra("userType", user_type);
LoginRegister.this.startActivity(intent);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginRegister.this);
builder.setMessage("Login Failed! Please provide valid username and password or connect to internet.")
.setNegativeButton("Retry", null)
.create()
.show();
Login.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
//Stylist's Log in
if(success1) {
String user_type = jsonResponse.getString("user_type");
Intent intent = new Intent(LoginRegister.this, ProfileActivity.class);
intent.putExtra("userType", user_type);
LoginRegister.this.startActivity(intent);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginRegister.this);
builder.setMessage("Login Failed! Please provide valid username and password or connect to internet.")
.setNegativeButton("Retry", null)
.create()
.show();
Login.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginRegister.this);
queue.add(loginRequest);
}else if(username.isEmpty() ){
userLoginUsername.setError("Please insert a username");
}else if(password.isEmpty()){
userLoginPassword.setError("Please put your password");
}
}
});
//register
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Register = new Intent(LoginRegister.this, RegisterCustomerOrStylist.class);
LoginRegister.this.startActivity(Register);
}
});
}
PS they have different datas from different tables. What I did is that I have an if condition that if the boolean of success (client) is true, it passes the data and its else is the alertdialog for error login. After it is another if statement for the success1 (stylist) which has the same logic with client.

If simplified, your code looks like this.
//Client's Log in
if (success) {
} else {
AlertDialog.Builder builder = ...
}
//Stylist's Log in
if(success1) {
} else {
AlertDialog.Builder builder
}
This means if a stylist tries to log in, client's log in block alert dialog will be shown, and vice versa.
So, a flag may be needed to check any success exists.
boolean successAny = success || suucess1;
//Client's Log in
if (success) {
} else {
if (!successAny) {
AlertDialog.Builder builder = ...
}
}
...
NB. A person is a client and also be a stylist case is not intended for this sample.

Related

Activity not opening after signing in

I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.
{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}
But while using the app, it does not go to the mainActivity.
This is the login class:-
public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;
EditText mEdtEmail , mEdtPassword ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Answers(), new Crashlytics());
setContentView(R.layout.activity_login);
login1 = (Button) findViewById(R.id.button);
mEdtEmail = (EditText) findViewById(R.id.phone_number);
mEdtPassword = (EditText) findViewById(R.id.password);
session = new Session(login.this);
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(login.this, MainActivity.class);
startActivity(intent);
finish();
}
// sign_in();
login1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mobile = mEdtEmail.getText().toString().trim();
String password = mEdtPassword.getText().toString().trim();
status = checkInternetConnection();
if (status) {
if (mobile.length() == 0) {
mEdtEmail.setError("Required");
} else if (mobile.length() < 10) {
mEdtEmail.setError("Mobile no must be 10 char. long");
} else if (password.length() == 0) {
mEdtPassword.setError("Required");
} else {
new UserLoginTask(mobile, password, login.this).execute();
}
}
else
{
Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
}
}
});
}
private class UserLoginTask extends AsyncTask<String, Void, String> {
private String mUserName;
private String mPassword;
String msg ;
ProgressDialog progressDialog;
Boolean loginStatus = false;
private Activity activity;
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
UserLoginTask(String userName, String password, Activity activity) {
mUserName = userName;
mPassword = password;
this.activity = activity;
}
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result= WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// Log.d("Json Array", "doInBackground: "+jsonObject);
String status = jsonObject.optString("error");
// msg = jsonObject.optString("msg");
// Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
if(status.equals("0")){
loginStatus = true ;
session.setLogin(true);
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject jsonObject1=jsonarray.getJSONObject(0);
status = jsonObject1.getString("msg");
Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));
Driver driver = new Driver();
driver.setId(jsonObject1.getString("id"));
driver.setDriver_name(jsonObject1.getString("driver_name"));
driver.setDriver_lat(jsonObject1.getString("driver_lat"));
driver.setDriver_long(jsonObject1.getString("driver_long"));
driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
driver.setDriver_token(jsonObject1.getString("driver_token"));
driver.setCreated_at(jsonObject1.getString("created_at"));
driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));
sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("driver_name",jsonObject1.getString("driver_name"));
editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
editor.putString("id", jsonObject1.getString("id"));
editor.putString("driver_token", jsonObject1.getString("driver_token"));
editor.putString("driver_image", jsonObject1.getString("driver_image"));
editor.putString("current_order_no", "");
editor.commit();
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return msg ;
}
#Override
protected void onPostExecute(String msg) {
super.onPostExecute(msg);
progressDialog.dismiss();
Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();
}
}
/*public void sign_in(){
login1=(Button)findViewById(R.id.button);
login1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}*/
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce){
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true ;
Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false ;
}
}, 2000);
/*Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);*/
}
public boolean checkInternetConnection()
{
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] inf = connectivity.getAllNetworkInfo();
if (inf != null)
for (int i = 0; i < inf.length; i++)
if (inf[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Please Help!
Thanks!!
EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!
Your jsonObject1.getString("msg"); don't have any msg
{"error":0,"data":[{"id":"2",.....}],"msg":"Login Successfully."}
// ` ^^^^^ part of jsonObject`
|_____________|
| first json object which has no msg key/value pair
|________________|
| jsonarray
|_______________________________________________________________|
|
JSONObject jsonObject = new JSONObject(result);
// response object
String status = jsonObject.optString("error");
// response json contains error , so far so good
..
..
JSONArray jsonarray = jsonObject.getJSONArray("data");
// get the jsonarray
JSONObject jsonObject1=jsonarray.getJSONObject(0);
// get first object
status = jsonObject1.getString("msg");
// there is no msg string in jsonObject1 hence error
so use
jsonObject.optString("msg");
Note : Apparently you are starting your MainActivity twice so remove one and from doInBackground which works on background thread so don't do this
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
Start your activity from onPostExecute
Here you are getting JSONObject in response from server.
This object contains three values:
error
data
msg
error contains error code in integer format.
data contains JSONArray which contain the details of the driver.
msg contains the message in String format.
So you need to write
JSONObject jsonObject = new JSONObject(result);
int code = jsonObject.getString("error");
if (code == 0) {
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject data = jsonarray.getJSONObject(0);
String msg = jsonObject.getString("msg");
driver = new Driver();
...
}
and remove this from doInBackground method
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
and write this code in onPostExecute method after displaying Toast
...
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
...
You need to declare Driver in UserLoginTask after ProgressDialog like
...
ProgressDialog progressDialog;
Driver driver;
From your attached JSONObject, its seems that JSONObject contains two string (error and msg) and one JSONArray named data.
So you have to parse this JSON data as below:
.........
..............
String result = WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// ERROR & STATUS
String status = jsonObject.optString("error");
String msg = jsonObject.optString("msg");
// DATA
JSONArray jsonArrayData = jsonObject.getJSONArray("data");
// First DATA JSONObject
JSONObject jsonObject1 = jsonArrayData.getJSONObject(0);
........
..............
To start MainActivity, use below code in onPostExecute() :
#Override
protected void onPostExecute() {
Intent intent = new Intent(login.this, MainActivity.class);
intent.putExtra("driver_obj" , driver); // driver should be declared as global in `UserLoginTask` class.
activity.startActivity(intent);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
Hope this will help~

When clicking Register button with empty field app crashes with error "NumberFormatException"

my register is working fine, but i want to validate when the fields(EditText) are empty, if i click register the app crashes and if i leave an empty field it crashes too..
public class register extends AppCompatActivity {
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
builder = new AlertDialog.Builder(register.this);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == 0 || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
} else {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(register.this, login.class);
register.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(register.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(register.this);
queue.add(registerRequest);
}
}
});
}
Integer age =null;
if(!etAge.getText().toString().trim().equals(""))
{
age=Integer.parseInt(etAge.getText().toString());
}
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == null || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
return ;
}

Store values from EditText in device's memory and restore back from memory in EditText

I have the following Login Activity that jumps to my MainMenuActivity after successfully login values is given.
I need to store the values from my 2 EdiText fields in the device's memory before Intent and restore it back to the EditText fields the next time i will run my application(LoginActivity).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
md = MediaPlayer.create(LoginActivity.this, R.raw.tick);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
final Button bLogin = (Button) findViewById(R.id.bSignIn);
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(lock==1) {
lock = 0;
md.release();
md = MediaPlayer.create(LoginActivity.this, R.raw.tick);
md.start();
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
finish();
}
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
if (lock == 1) {
connected=isConnectedToNet();
if(connected) {
lock = 0;
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
md.release();
md = MediaPlayer.create(LoginActivity.this, R.raw.tick);
md.start();
/***Send username and password to server.Take back user's parameters ***/
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
int age = jsonResponse.getInt("age");
int score = jsonResponse.getInt("score");
int level = jsonResponse.getInt("level");
int online = jsonResponse.getInt("online");
Intent intent = new Intent(LoginActivity.this, MainMenuActivity.class);
intent.putExtra("username", username);
intent.putExtra("score", score);
intent.putExtra("level", level);
intent.putExtra("online", online);
LoginActivity.this.startActivity(intent);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this, R.style.myBackgroundStyle);
builder.setMessage("Λάθος όνομα χρήστη ή κωδικός")
.setNegativeButton("Ξαναπροσπάθησε", null)
.create()
.show();
/***Set lock back to value '1' .***/
Runnable runnable = new Runnable() {
#Override
public void run() {
lock = 1;
}
};
mHandler.postDelayed(runnable, 1000);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener error=new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
recursive();
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener,error);
//RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//queue.add(loginRequest);
Mysingleton.getmInstance(getApplicationContext()).addToRequestque(loginRequest);
}
else {
Snackbar snackbar = Snackbar.make(findViewById(R.id.bSignIn), "Δεν υπάρχει σύνδεση στο διαδίκτυο", Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setGravity(Gravity.CENTER);
sbView.setBackgroundResource(R.drawable.snackbar1);
textView.setTextColor(Color.BLACK);
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.image3,0);
snackbar.show();
lock=1;
}
}
}
});
}
How is it possible to do that?
Save your username and password in shared preferences
SharedPreferences.Editor editor = getSharedPreferences("LOGIN_DETAILS", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("password", "123456");
editor.commit();
Receive values whenever you need
SharedPreferences prefs = getSharedPreferences("LOGIN_DETAILS", MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
String password = prefs.getString("password","0"); //0 is the default value.

Nothing Being Passed via $_Post to Php from login code?

I've been working on a log-in/register for an android app and have the register up and running but the log-in doesnt seem to be passing anything over to the php script via post like the register was? , I'm pretty sure the php script is fully functional as I've tested it with Postman, If anyone could point me in the right direction it would be much appreciated, Cheers
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL="http://192.168.0.17/WebD/HASSAPP/login.php";
private Map<String, String> params;
public LoginRequest(String username,String password , Response.Listener<String> listener) {
super(Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
}
#Override
public Map<String,String> getParams() {
return params;
}
}
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//Edit to change title text
setSupportActionBar(toolbar);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String businessname = jsonResponse.getString("businessname");
String username = jsonResponse.getString("username");
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("businessname", businessname);
intent.putExtra("username", username);
Login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginrequest = new LoginRequest(username,password,responseListener);
RequestQueue queue = Volley.newRequestQueue(Login.this);
queue.add(loginrequest);
}
});
}
I cannot understand how me sending via Post on my register is working fine but On Log-in it's non responsive , Log-in button does nothing , not even send me to mainactivity like the intent's purpose,
Kind Regards,
Andrew
This overriden method should be protected. You have it as public.
#Override
protected Map<String,String> getParams() {
return params;
}
Also, for debugging purposes, you might want to override the error listener as well.

JSONObjectRequest how to populate spinner using volley

i am trying to populate a spinner from a URl but i cant get the elements on to spinner using the GET method...my POST method works well to do the registration...But cant GET data to spinner...this is my code
public class SuppRegActivity extends AppCompatActivity implements RegistrationView,View.OnClickListener {
EditText company_name,code,Add1,Add2,Add3,Add4,Tel_no,mob_no,email,contact_person,tin_no,password;
Spinner state;
Button save;
ArrayList<String> mystates;
ArrayList<JSONObject> err;
String Get_company_name,Get_code,Get_Add1,Get_Add2,Get_Add3,Get_Add4,Get_Telno,
Get_mobno,Get_email,Get_contactp,Get_tinno,Get_password,Get_state;
RegistrationPresenter registrationPresenter;
ProgressDialog progressDialog;
View v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_supp_reg);
company_name = (EditText) findViewById(R.id.suppname);
code = (EditText) findViewById(R.id.suppcode);
Add1 = (EditText) findViewById(R.id.Add1);
Add2 = (EditText) findViewById(R.id.Add2);
Add3 = (EditText) findViewById(R.id.Add3);
Add4 = (EditText) findViewById(R.id.Add4);
Tel_no = (EditText) findViewById(R.id.suppPhone);
mob_no = (EditText) findViewById(R.id.SuppMob);
email = (EditText) findViewById(R.id.suppEmail);
contact_person= (EditText) findViewById(R.id.SuppPerson);
tin_no = (EditText) findViewById(R.id.SuppTin);
password = (EditText) findViewById(R.id.suppPass);
state = (Spinner) findViewById(R.id.suppstate);
save = (Button) findViewById(R.id.Saveregister);
save.setOnClickListener(this);
//arr = new ArrayList<JSONObject>();
registrationPresenter = new RegistrationPresenterImpl(this, SuppRegActivity.this);
}
#Override
public void onClick(View view) {
Get_company_name = company_name.getText().toString();
Get_Add1 = Add1.getText().toString();
Get_Add2 = Add2.getText().toString();
Get_Add3 = Add3.getText().toString();
Get_Add4 = Add4.getText().toString();
Get_state = state.getSelectedItem().toString();
Get_Telno = Tel_no.getText().toString();
Get_mobno = mob_no.getText().toString();
Get_email = email.getText().toString();
Get_contactp = contact_person.getText().toString();
Get_tinno = tin_no.getText().toString();
Get_code = code.getText().toString();
Get_password = password.getText().toString();
if(!Get_company_name.equals("")){
if(!Get_Add1.equals("")){
if(!Get_Add2.equals("")){
if(!Get_Add3.equals("")){
if(!Get_Add4.equals("")){
if(!Get_state.equals("")){
if(!Get_Telno.equals("")){
if(Get_Telno.length() ==10 ){
if(!Get_mobno.equals("")){
if(Get_mobno.length() == 10){
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(Get_email.matches(emailPattern)){
if(!Get_contactp.equals("")){
if(!Get_tinno.equals("")){
if(!Get_code.equals("")){
if(!password.equals("")){
doRegisteration(Get_company_name,Get_code,Get_Add1,Get_Add2,Get_Add3,Get_Add4,Get_state,Get_Telno,Get_mobno,Get_email,Get_contactp,
Get_tinno,Get_password);
}else{
showFailedAlertBox("Password in Required");
}
}else{
showFailedAlertBox("user name is required");
}
}else{
showFailedAlertBox("enter Tin No.");
}
}else{
showFailedAlertBox("enter contact person");
}
}else{
showFailedAlertBox("invalid email");
}
}else{
showFailedAlertBox("enter 10 digit phone no");
}
}else{
showFailedAlertBox("enter mobile no");
}
}else{
showFailedAlertBox("enter 10 digit phone no.");
}
}else{
showFailedAlertBox("enter mobile no");
}
}else{
showFailedAlertBox("State not selected");
}
}else{
showFailedAlertBox("Address line 4 required");
}
}else{
showFailedAlertBox("Address line 3 required");
}
}else{
showFailedAlertBox("Address line 2 required");
}
}else{
showFailedAlertBox("Address line 1 required");
}
}else{
showFailedAlertBox("Company name is required");
}
}
private void showSuccessAlertBox(final String v) {
new AlertDialog.Builder(this).setMessage(v)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (v.equals("Registration Done")) {
/* // String uNameForIntent = company_name.getText().toString().trim();
Intent intent = new Intent(SuppRegActivity.this, MainActivity.class);
// intent.putExtra("uname", uNameForIntent);
startActivity(intent);*/
}
else{
return;
}
}
}).show();
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void doRegisteration(String companyname, String code, String Add1, String Add2, String Add3, String Add4, String State, String tel_no,
String mobileno, String email, String contactp, String tinno, String password){
/*JSONObject stat = new JSONObject();
try{
JSONObject a = stat.getJSONObject("getAllState");
for(int i=0;i<a.length();i++) {
JSONObject c=(JSONObject) a.get(i);
}
} catch (JSONException e) {
e.printStackTrace();
}*/
JSONObject register= new JSONObject();
try {
register.put("FullName",Get_company_name);
register.put("Alias",Get_code);
register.put("Add1", Get_Add1);
register.put("Add2", Get_Add2);
register.put("Add3", Get_Add3);
register.put("Add4", Get_Add4);
register.put("State",Get_state);
register.put("TelNo",Get_Telno);
register.put("mobile", Get_mobno);
register.put("email", Get_email);
register.put("TinNo",Get_tinno);
register.put("ContactPerson", Get_contactp);
register.put("Password", Get_password);
JSONObject s = register.getJSONObject("http://.............................../getAllState");
err = new ArrayList<JSONObject>();
err.add(s);
ArrayAdapter<JSONObject> adapter = new ArrayAdapter<JSONObject>(this,android.R.layout.simple_spinner_item,err);
state.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String REGISTER_URL =" http://........................../AddAccount";
//String STATE_URL = "http://.........................../getAllState";
showProgress();
/*JsonObjectRequest statelist = new JsonObjectRequest(Request.Method.GET, STATE_URL, stat,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
state.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,arr));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});*/
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, REGISTER_URL,register,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject j = null;
String result = null;
try {
result = response.getString("Result");
} catch (JSONException e) {
e.printStackTrace();
}
if (result.equals("Saved")) {
showSuccessAlertBox("Registration Done");
//volleyForProfile(sessionManager.getUserName());
}
else
showFailedAlertBox("Failed Process!!!Try Again");
hidePregress();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePregress();
}
}
);
request.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleyApplication.getInstance().getRequestQueue().add(request);
}
private void showFailedAlertBox(String v) {
new AlertDialog.Builder(this).setMessage(v)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
#Override
public void showProgress() {
progressDialog = ProgressDialog.show(SuppRegActivity.this, "Please Wait",
"Processing...", true);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
#Override
public void hidePregress() {
progressDialog.dismiss();
}
#Override
public void setErrorOnEditText() {
/*Snackbar.make(v, msg, Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
showSuccessAlertBox(msg);*/
}
#Override
public void savedMsg(String msg) {
}
}
where REGISTER_URL uses the post method....and STATE_URL uses the GET Method...
First instead of accepting response as JSON object use instance of a custom POJO class of your own depending on your requirements. And secondly you can create a custom adapter class for populating your spinner.
If you have a small requirement like mentioned above I'd suggest you should use Retrofit instead of Volley which is lightweight and fast.

Categories

Resources