I am using a save button in my application. When I click on save button, I want it to validate each field and display an error message like "Please enter this field", "Please enter in correct format in this field" or "Please select this".
I have 8 EditText boxes and 2 spinners and on TextView having ListView. In Android, how to use field validation on every field and after validating each field it save data successfully.
My java code is:
public class non_ticket_task extends Activity implements OnItemSelectedListener{
public static String complain_date;
public static String complain_time;
public static String job_performed;
// public static String time;
public static String next_due_on;
static TelephonyManager tm;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
TextView cus_name_txt;
EditText complain_date_txtbx;
EditText complain_time_txtbx;
EditText job_performed_txtbx;
EditText date_txtbx;
EditText lat_txtbx;
EditText lon_txtbx;
EditText next_due_on_txtbx;
Button btnadd;
// url to create new product
private static String url_create_task = "http://192.168.2.1/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.non_ticket_task);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// Buttons
btnadd = (Button) findViewById(R.id.addbtn);
// button click event
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new task in background thread
new CreateNewTask().execute();
}
});
cus_name_txt = (TextView)findViewById(R.id.textView1);
cus_name_txt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Onclick_click1(cus_name_txt);
}
});
complain_date_txtbx = (EditText) findViewById(R.id.complain_date_txt);
complain_date_txtbx.setText(non_ticket_task.complain_date);
complain_time_txtbx = (EditText) findViewById(R.id.complain_time_txt);
complain_time_txtbx.setText(non_ticket_task.complain_time);
job_performed_txtbx = (EditText) findViewById(R.id.job_performed_txt);
job_performed_txtbx.setText(non_ticket_task.job_performed);
date_txtbx = (EditText) findViewById(R.id.date_txt);
date_txtbx.setText(" "
+ String.valueOf(java.text.DateFormat.getDateTimeInstance()
.format(Calendar.getInstance().getTime())));
MyLocation loc = new MyLocation(this.getApplicationContext());
lon_txtbx = (EditText) findViewById(R.id.lon_txt);
lon_txtbx.setText(String.valueOf(loc.lon));
lat_txtbx = (EditText) findViewById(R.id.lat_txt);
lat_txtbx.setText(String.valueOf(loc.lat));
next_due_on_txtbx = (EditText) findViewById(R.id.next_due_on_txt);
next_due_on_txtbx.setText(non_ticket_task.next_due_on);
Spinner status = (Spinner) findViewById(R.id.status_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Status_array, android.R.layout.simple_dropdown_item_1line);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
status.setAdapter(adapter);
Spinner severity = (Spinner) findViewById(R.id.severity_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
R.array.Severity_array, android.R.layout.simple_dropdown_item_1line);
// Specify the layout to use when the list of choices appears
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
severity.setAdapter(adapter1);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void Onclick_click1(final TextView cus_name_txt)
{
final TextView txtbx = (TextView) cus_name_txt;
if(cus_name_txt.getId()==R.id.textView1)
{
final CharSequence[] items = {"Ali Asghar","Ali Shah","Tamseel","Bilal","Daniyal","Muzamil","Faraz","Uzair","Mohsin","Mehran","Babar","Ameen","Zeeshan","Maqsood","Hasan","Taqi","Talib","Asif","Mudasir"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Customers Name");
//builder.setI
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(getApplicationContext(), con.get(item).getCountrName(), Toast.LENGTH_SHORT).show();
txtbx.setText(items[item]);
System.out.println("Item is: "+items[item]);
/*CONTRY_ID = con.get(item).getCountryId();
stateET.requestFocus();*/
}
});
builder.show();
}
}
/**
* Background Async Task to Create new product
* */
class CreateNewTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(non_ticket_task.this);
pDialog.setMessage("Saving Details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating task
* */
protected String doInBackground(String... args) {
String cus_name = cus_name_txt.getText().toString();
String complain_date = complain_date_txtbx.getText().toString();
String complain_time = complain_time_txtbx.getText().toString();
String job_performed = job_performed_txtbx.getText().toString();
String date = date_txtbx.getText().toString();
String next_due_on = next_due_on_txtbx.getText().toString();
String lat = lat_txtbx.getText().toString();
String lon = lon_txtbx.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cus_name", cus_name));
params.add(new BasicNameValuePair("complain_date", complain_date));
params.add(new BasicNameValuePair("complain_time", complain_time));
params.add(new BasicNameValuePair("job_performed", job_performed));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("next_due_on", next_due_on));
params.add(new BasicNameValuePair("lat", lat));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_task,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), My_Task.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Frankly speaking the validation process largely depends upon what you want to validate and how. For example if you want to validate the text of an edittext just after leaving the focus or only after clicking the submit button. TextWatchers can serve the purpose for a fast and user friendly validation. However if you want to validate on click of a Button, You can have a function like
boolean void validateInput(){
boolean retStatus=false;
if((textView1.getText().length()==0 || textView1.getText().equals("") && (any other condition )){
retStatus=true;
textView1.setError("You have entered wrong value in textView 1");
}
//similarly for other controls
------
-----
--
return retStatus;
}
If you want to use immediate error detection the error checking (and correction) will be fast instead methods like above can show "all at once" errors. You can decide whichever suits to your users.
For reducing user input errors use text type for edittexts i.e. use numeric for editText for phone number, alphabets for Names or type emailid for emails etc. Use hints to indicate users what they are supposed to do in that EditText i.e. enter your email id here.
Happy Coding!!
Hi if I understand you very well you just want to make sure you give feedback to users to type something in the EditText. If that is what you want, then you only need to check the lenght of the EditText.getText like so:
if (cus_name_txt.getText().Lenght()==0){
//Your message here
}
Hope this helps.
In onPreExecute you do the validations. If a field is empty(or wrong) you set to that field an error message. If there are one or more invalid fields, you cancel the AsyncTask and show the error. After the user fixes the errors, it can press Save again.
You should take the string from the fields in onPreExecute, not in doInBackground, because you cannot make modifications in the Ui from that method.
You can make a function validatefields() like this and call this function in like this
if(validate()){
new CreateNewTask().execute()
}
else{
showErrorMsg(msg);
}
where validate function will be like this
private boolean validate(){
boolean retStatus=false;
if((textView1.getText().length()==0 || textView1.getText().equals("") ){
retStatus=false;
msg = "Please fill TextView 1";
}
else if ( ---check other 9 condition in the same way--)
}
if ( !msg.equals("")){
return false;
}
else {
return true;
}
}
Related
Currently I have trouble based on my question above. I Have two radio button in one radio group. The first radio button is "Approved" and the second radio button is "Rejected". Example, if I clicked the radio button "Approved", the value from that checked radio button will save to MySQL. Then, if I want to display back the value of Radio button, how will the radio button "Approved" is display as Checked? (don't want to display back as TextView).
Below is my code on how I get all the value from edit text to text view.
This code is retrieve from database and display as textView.
etName = findViewById(R.id.etName);
etBadgeID = findViewById(R.id.etBadgeID);
etDepartment = findViewById(R.id.etDepartment);
etFactory = findViewById(R.id.etFactory);
etPosition = findViewById(R.id.etPosition);
etReviewer = findViewById(R.id.etReviewer);
etTitle = findViewById(R.id.etTitle);
etMonth = findViewById(R.id.etMonth);
etYear = findViewById(R.id.etYear);
etSuggestwill = findViewById(R.id.etSuggestwill);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
rgStatus = findViewById(R.id.rgStatus);
etComment = findViewById(R.id.etComment);
Intent intent = getIntent();
User user = (User) intent.getSerializableExtra("user");
etName.setText(user.getName());
etBadgeID.setText(user.getBadgeid());
etDepartment.setText(user.getDepartment());
etFactory.setText(user.getFactory());
etPosition.setText(user.getPosition());
etReviewer.setText(user.getReviewer());
etTitle.setText(user.getTitle());
etMonth.setText(user.getMonth());
etYear.setText(user.getYear());
etSuggestwill.setText(user.getSuggestionwill());
etPresent.setText(user.getPresent());
etDetails.setText(user.getDetails());
etBenefit.setText(user.getBenefit());
imgAttach.setImageBitmap(base64ToBitmap(user.getPhoto()));
etComment.setText(user.getComment());
This is how I store value radio button at the database (at Submit Button)
int selectedId = rgStatus.getCheckedRadioButtonId();
radioButton = findViewById(selectedId);
final String status = radioButton.getText().toString();
update(status);
Method for update(status)
private void update(final String status){
class updateClass extends AsyncTask<String,Void,String> {
private ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading =
ProgressDialog.show(NeedApproval.this,"Updating.....",null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
}
#Override
protected String doInBackground(String... params) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> data = new HashMap<>();
data.put("status",params[0]);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_UPDATE, data);
}
}
updateClass ulc = new updateClass();
ulc.execute(status);
}
I've got an inputDialog, which allows for some text inputs. On clicking save, the inputDialog checks if the entered text is already available (to prevent double entries). If this is the case, a new AlertDialog is created, simply stating "The value you entered already exists", with just an "Ok" button to dismiss this AlertDialog. This all works.
I would like to have the inputDialog pop back up again, after dismissing the AlertDialog, with the values that were entered by the user before still in the editText fields.
I'm not expecting any problems on getting those values back in the editText fields (Store them in a variable on clicking save, if the double entry error occurs, set those variables on the editText's. If I'm doing this in a stupid way, please let me know).
I am however having trouble with getting the first (inputDialog) dialog to come back. The code you see below is the code for my inputDialog fragment (The code is simplified, so if something seems to be missing, it probably is. Let me know, so I can add it back in.)
So, to repeat myself: How can I return to the previous dialog after dismissing the second one?
StuffManagerInputDialogFragment.java:
public class StuffManagerInputDialogFragment extends DialogFragment {
EditText nameInputField;
EditText tagInputField;
DBHandler dbHandler;
StuffManagerFragment f = new StuffManagerFragment();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v_iew = inflater.inflate(R.layout.fragment_inputdialog, null);
nameInputField = (EditText) v_iew.findViewById(R.id.inputdialogname);
tagInputField = (EditText) v_iew.findViewById(R.id.inputdialogtag);
dbHandler = new DBHandler(getActivity(), null, null, 1);
final MainActivity ma = (MainActivity) getActivity();
final AlertDialog.Builder newLinkDialog = new AlertDialog.Builder(getActivity());
newLinkDialog.setView(v_iew)
.setTitle("New Link")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String nameInputFieldText = nameInputField.getText().toString();
String tagInputFieldText = tagInputField.getText().toString();
ArrayList<String> nameArray = dbHandler.nameArrayMethod();
ArrayList<String> tagArray = dbHandler.tagArrayMethod();
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
if (nameArray.contains(nameInputFieldText) || tagArray.contains(tagInputFieldText)) {
if (nameArray.contains(nameInputFieldText) && tagArray.contains(tagInputFieldText)) {
AlertDialog.Builder errorBoth = new AlertDialog.Builder(getActivity())
.setTitle("Error")
.setMessage("The name and tag you entered are already in use.")
.setIcon(R.drawable.ic_error_black)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Return to previous dialog here
}
});
errorBoth.show();
}
} else {
dbHandler.addLink(nameInputFieldText, tagInputFieldText);
nameArray = dbHandler.nameArrayMethod();
int nameArraySize = (nameArray.size() - 1);
MenuItem item = menu.add(R.id.group1, nameArraySize, 1, nameArray.get(nameArraySize));
Toast.makeText(getContext(), "'" + nameInputFieldText + " - " + tagInputFieldText + "' link saved.", Toast.LENGTH_SHORT).show();
ma.addSMVFFragments();
f.hideDeleteAllButton = false;
getActivity().invalidateOptionsMenu();
}
}
})
.setNegativeButton("Cancel", null);
return newLinkDialog.create();
}
}
A better solution is to have a dialog fragment for your input layout, and that dialog fragment would display an AlertDialog on OK if the text validation fails. The input dialog fragment would not dismiss in this case, it will remain in the background so when you dismiss the alert dialog to tell the user the input is invalid, you return to the input dialog as it was.
To prevent the dialog fragment from dismissing on OK you would override onStart and get a reference to the OK button and set the listener there, like this:
#Override
public void onStart() {
super.onStart();
AlertDialog alertDialog = (AlertDialog) getDialog();
if (alertDialog != null) {
mOKButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
mOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (field OK) {
// save data
dismiss();
} else {
// show error dialog
}
}
});
}
}
Anyone, Please help, how to remove this warning in Eclipse..
I completely newbie in android developing and I want to know how to get remove this warning, indicated in this photo. It said "The value of the field LoginActivity.KEY_ERROR_MSG and KEY_ERROR is not used". Anyone?
Here's the code:
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
I won't buy an Apple, if I'm not hungry :)
That means you are declared a filed and not using it anywhere. I just remove that, if I'm not using it anymore. Or at least comment it, for future uses.
put #SuppressWarnings("unused") before the variable where you are getting warning .
This warning message occurs when you declare variables which are not used within their respective scope.
This is not an error but it would be better if you remove unused variables.
Should you want to remove this warning message but would like to retain the declaration, place the following tag right on top of the variable with the warning (in case of class scope declaration) or on top of the method (method scope declaration) where it was declared:
#SuppressWarnings("unused")
I am new to Android development. I am trying to call a method of one of my classes when a button on my main activity is pressed.
On my Main Activity I have this button:
public void buttonTest(){
Button b = (Button) findViewById(R.id.test);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String s = "changeText:myText";
Intent in = new Intent(PlusActivity.this, Test.class);
in.putExtra("method",s);
startActivity(in);
}
});
}
And here is is the class (without imports) which that intent above is calling to.
public class Test extends Activity {
static String text = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView mTextView = (TextView) findViewById(R.id.textView);
mTextView.setText(text);
}
public void changeText(String s){
this.text = s;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String[] array = intent.getStringExtra("method").split(":");
if(array[0].equals("changeText")){
changeText(array[1]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
Basically I want to know if it is possible to change the value of that String text, before onCreate(). Basically each button will have a correspondent text, and I want to be able to modify that text based on which button.
If it is, what should I do/change?
Thanks in advance.
The right way to do it is to send the string you want it to be as an extra in the intent, and to read the extra from the intent and assign it to that variable in the onCreate function.
Use SharedPreference. Save in OnCLick of first class and retrieve in OnCreate of second class.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes
String text;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
text= null;
} else {
text= extras.getString("your default string message");
}
} else {
String s = "your default string message";
text= (String) savedInstanceState.getSerializable(s);
}
I have written a log in function for my android app, I am wanting to make it work on API 17, right now it give a network on main thread exception, which I understand you cant do network operations on the main thread, I have played around with trying to put threads in but it doesn't seem to go. So i am trying a asynctask now
any help suggestions would be great
package khs.studentsupport;
import java.util.HashMap;
import khs.supportapp.library.DatabaseHandler;
import khs.supportapp.library.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class New_Login extends Activity{
// Progress Dialog
private ProgressDialog pDialog;
public String storedEmail="";
public String stroedPW = "";
boolean GCMFlag=false;
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public void SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
// Internet detector
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
//private static String KEY_ERROR = "error";
//private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_STUDENT_ID = "studentUser";
private static String KEY_CREATED_AT = "created_at";
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
//ID of student
user.put(KEY_STUDENT_ID, pref.getString(KEY_STUDENT_ID, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
}
// Response from Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAlldetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(New_Login.this);
pDialog.setMessage("Logging you in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* getting user details from url
* */
protected String doInBackground(String... args) {
cd = new ConnectionDetector(getApplicationContext());
String storedEmail = Appconfig.stored_user_name.toString();
String stroedPW = Appconfig.stored_password.toString();
// Check if Internet present
if (!cd.isConnectingToInternet())
{
if((inputEmail.toString()==storedEmail)&&(inputPassword.toString()==stroedPW))
{
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
}
}
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
//Auto fill for login only if the user has logged in before
if((Appconfig.stored_user_name.length()>0)&&(Appconfig.stored_password.length()>0))
{
inputEmail.setText(Appconfig.stored_user_name.toString());
inputPassword.setText(Appconfig.stored_password.toString());
}
// Importing all assets like buttons, text fields
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new LoadAlldetails().execute();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
//Check to see if user has put in details
if ((email.matches("")||(password.matches(""))))
{
loginErrorMsg.setText("Please enter your details ");
}
else
{ //Checks to see if first time in the app
// launces gcm activity
if (Appconfig.GCMactivity == false) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(),RegisterForGCMActivity.class);
startActivity(intent);
//set to true so GCm register wont show again
Appconfig.GCMactivity=true;
}
else{
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
Appconfig.stored_user_name=json_user.getString(KEY_EMAIL);
Appconfig.stored_password = password;
if(Appconfig.email_is_set==false)
{
Appconfig.student_ID = json_user.getString(KEY_STUDENT_ID);
}
Appconfig.email_is_set=true;
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}}});
GCMFlag = true;
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
return null;
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting user details
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
I see many so far so I will let you know about these but know that there may be more.
First, you call startActivity from a background Thread so you need to add a Context to it. Since its an inner class of Activity you could use
New_Login.this.startActivity(dashboard);
However, you should return data to onPostExecute() and just start the Activity from there.
Another thing I see is that you are trying to update Views from a background Thread which is a no no. You should not try to update them in doInBackground().
You are trying to compare Strings incorrectly
if((inputEmail.toString()==storedEmail)&&(inputPassword.toString()==stroedPW))
it should be
if((inputEmail.toString().equals(storedEmail))&&(inputPassword.toString().equals(stroedPW)))
It looks like you are declaring your Views in your AsyncTask but this should be done in your Activity(most likely in onCreate() or onResume().
Don't use getApplicationContext() unless absolutely necessary. Inside of an onClick() you can use v.getContext() and inside of your Activity but outside of a listener you can use ActivitiyName.this (there are more options there but I will keep that simple for now).
My suggestion, strip out your AsyncTask and get your Activity set up correctly then implement your AsyncTask. And be sure to go through the documentation well.
Activity Docs
AsyncTask Docs