Android AsyncTask not functioning - java

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

Related

getResources on a null object in an android project

I have a method in a library I am creating for a series of apps I am doing. This method will display an input dialog for the user to input a string entry. I am writing this project for android using android studio, and I am writing it in Java.
Here is the Logcat:
2020-11-17 00:44:23.819 6758-6758/com.phoenixhosman.launcher E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.phoenixhosman.launcher, PID: 6758
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:91)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at android.content.Context.getString(Context.java:594)
at com.phoenixhosman.phoenixlib.ActivityPhoenixLib.InputDialog(ActivityPhoenixLib.java:97)
at com.phoenixhosman.launcher.ActivityHome.onClick(ActivityHome.java:151)
at android.view.View.performClick(View.java:6603)
at android.view.View.performClickInternal(View.java:6576)
at android.view.View.access$3100(View.java:780)
at android.view.View$PerformClick.run(View.java:26090)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6714)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:911)
Here in my ActivityHome.java file:
/*
The Phoenix Hospitality Management System
Launcher App Source Code
Main Activity Code File
Copyright (c) 2020 By Troy Marker Enterprises
All Rights Under Copyright Reserved
The code in this file was created for use with the Phoenix Hospitality Management System (PHMS).
Use of this code outside the PHMS is strictly prohibited.
*/
package com.phoenixhosman.launcher;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.phoenixhosman.phoenixapi.*;
import com.phoenixhosman.phoenixlib.ProviderUser;
import com.phoenixhosman.phoenixlib.ActivityPhoenixLib;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.atomic.AtomicInteger;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.phoenixhosman.phoenixapi.ManagerSecurityApi.*;
/**
* This activity display links to the other apps in the Phoenix Hospitality
* system, and use authentication to only show those that the user has
* permission to use.
* #author Troy L. Marker
* #version 1.0.0
* #since 0.5.0
*/
public class ActivityHome extends Activity implements View.OnClickListener
{
private String strCoName;
private String strApiUrl;
private String strLockPass;
private EditText etUsername;
private EditText etPassword;
final private static int REQUEST_CODE_1 = 1;
final ActivityPhoenixLib Phoenix = new ActivityPhoenixLib();
/**
* This method will create the activity, read content to display, and show the main activity screen
* Used when the activity is (re)created.
* #param savedInstanceState current saved instance state
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
setContentView(R.layout.activity_home);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
TextView tvWarning = findViewById(R.id.tvWarning);
Button btnLogon = findViewById(R.id.btnLogon);
Button btnLockPass = findViewById(R.id.btnLockPass);
btnLogon.setOnClickListener(this);
btnLockPass.setOnClickListener(this);
#SuppressLint("Recycle") Cursor cursor = getContentResolver().query(Uri.parse("content://com.phoenixhosman.installer.ProviderSettings/settings"), null, null, null, null, null);
assert cursor != null;
if(cursor.moveToFirst()) {
while(!cursor.isAfterLast()) {
strCoName = cursor.getString(cursor.getColumnIndex("coname"));
strApiUrl = cursor.getString(cursor.getColumnIndex("apiurl"));
strLockPass = cursor.getString(cursor.getColumnIndex("lockpass"));
cursor.moveToNext();
}
new ManagerSecurityApi(strApiUrl);
tvWarning.setText(getString(R.string.warning, rtrim(strCoName)));
} else {
Phoenix.Error(getApplicationContext(),getString(R.string.required), false);
}
}
/**
* Override of the onBackPress method from the parent class
* This disables the back button on the device.
*/
#Override
public void onBackPressed() {
Phoenix.Error(ActivityHome.this, getString(R.string.disabled, getString(R.string.back)),false);
}
/**
* This method overrides the parents click listner.
* #param v the view clicked.
*/
#Override
public void onClick(View v) {
Button button = (Button)v;
String buttonText = button.getText().toString();
if (buttonText.equals(getString(R.string.login))) {
if (etUsername.getText().toString().isEmpty() || etPassword.getText().toString().isEmpty()) {
Phoenix.Error(ActivityHome.this, getString(R.string.both_required,getString(R.string.username_password)), false);
} else {
Call<String> call = getInstance().getApi().login(etUsername.getText().toString(), etPassword.getText().toString());
call.enqueue(new Callback<String>() {
#Override
public void onResponse(#NonNull Call<String> call, #NonNull Response<String> response) {
String body = response.body();
try {
assert body != null;
JSONObject obj = new JSONObject(body);
if (obj.optBoolean("success")) {
etUsername.setText("");
etPassword.setText("");
etUsername.requestFocus();
getContentResolver().delete(ProviderUser.CONTENT_URI, null, null);
ContentValues values = new ContentValues();
values.put(ProviderUser.name, obj.optString("username"));
values.put(ProviderUser.grade, obj.optInt("grade"));
values.put(ProviderUser.gradename, obj.optString("gradename"));
values.put(ProviderUser.department, obj.optInt("department"));
values.put(ProviderUser.departmentname, obj.optString("departmentname"));
getContentResolver().insert(ProviderUser.CONTENT_URI, values);
Phoenix.Success(ActivityHome.this, obj.optString("message"), 5);
showApps(obj.optString("username"), obj.optInt("grade"), obj.optString("gradename"), obj.optInt("department"), obj.optString("departmentname"));
} else {
Phoenix.Error(getApplicationContext(), getString(R.string.user_not), false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(#NonNull Call<String> call, #NonNull Throwable t) {
}
});
}
} else if (buttonText.equals(getString(R.string.admin_access))) {
String LockPass = Phoenix.InputDialog(ActivityHome.this.getApplicationContext(), getString(R.string.input_prompt, getString(R.string.enter_lock_pass)));
if (LockPass.equals(strLockPass)) {
this.getPackageManager().clearPackagePreferredActivities(this.getPackageName());
finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
} else {
throw new IllegalStateException(getString(R.string.unexpected) + v.getId());
}
}
/**
* This method will call the App Display Activity
*/
private void showApps(String username, Integer grade, String gradename, Integer department, String departmentname){
Intent intent = new Intent(ActivityHome.this.getApplicationContext(), ActivityApp.class);
intent.putExtra("username", username);
intent.putExtra("grade", String.valueOf(grade));
intent.putExtra("gradename", gradename);
intent.putExtra("department", String.valueOf(department));
intent.putExtra("departmentname", departmentname);
startActivityForResult(intent, REQUEST_CODE_1);
}
/**
* Function to trim whitespace from the end of a string.
* #param s the string to trim
* #return the trimmed string
*/
#NonNull
public static String rtrim(String s) {
AtomicInteger i;
i = new AtomicInteger(s.length() - 1);
while (i.get() >= 0 && Character.isWhitespace(s.charAt(i.get()))) {
i.getAndDecrement();
}
return s.substring(0, i.get() +1);
}
}
And finially, here is my ActivityPhoenixLib.java file:
package com.phoenixhosman.phoenixlib;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import static android.view.View.inflate;
public class ActivityPhoenixLib extends Activity {
/**
* While not needed, this constructor makes calls to the member method of the class
* to clear errors in the editor.
*/
public ActivityPhoenixLib() {
Error(this, "", false);
Success(this,"",0);
String dummy = InputDialog(this, "");
if (dummy.equals("test")) {
}
}
/**
* This method displays a dialog box with an error message and a close button.
* #param strError the error message to display
*/
public void Error(Context context, #NonNull String strError, Boolean exit) {
if (strError.equals("")) {
return;
}
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
View view = inflate(context, R.layout.dialog_error, null);
Button btnExit = view.findViewById(R.id.btnExitButton);
Button btnError = view.findViewById(R.id.btnErrorMessage);
btnError.setText(strError);
mBuilder.setView(view);
AlertDialog dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
btnExit.setOnClickListener(v -> {
dialog.dismiss();
if (exit) System.exit(0);
});
}
/**
* This method displays a dialog box with a message and a close button.
* It also has an auto close function to auto close after a specified number of seconds.
* #param strMessage the message to display
*/
public void Success(Context context, #NonNull String strMessage, Integer autoclose) {
if (strMessage.equals("")) {
return;
}
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
View view = inflate(context, R.layout.dialog_success, null);
Button btnExit = view.findViewById(R.id.btnButton);
Button btnError = view.findViewById(R.id.btnMessage);
btnError.setText(strMessage);
mBuilder.setView(view);
AlertDialog dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
btnExit.setOnClickListener(v -> dialog.dismiss());
new Handler().postDelayed(dialog::dismiss, autoclose * 1000);
}
/**
* This method show an input box to get string input from the user.
* #param strPrompt - the dialog prompt
*/
public String InputDialog(Context context, String strPrompt) {
if (strPrompt.equals("")) {
return "";
}
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
final String[] retval = new String[1];
View view = inflate(context, R.layout.dialog_input, null);
TextView txtPrompt = view.findViewById(R.id.txtPrompt);
EditText edtLockPass = view.findViewById(R.id.edtLockPass);
Button btnEnter = view.findViewById(R.id.btnEnter);
--> Line 97 <-- txtPrompt.setText(getString(R.string.input_prompt, strPrompt));
mBuilder.setView(view);
AlertDialog dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
btnEnter.setOnClickListener(v -> {
if (edtLockPass.getText().toString().equals("")) {
retval[0] = "";
} else {
retval[0] = edtLockPass.getText().toString();
}
});
dialog.dismiss();
return retval[0];
}
}
I have tried several different things. I am going on the assumption that the context is not being passed to the InputDialog function, and I have tried different way of pass the context to the function: this. ActivityHome.this, getApplicationContext, and none of them seemed to work. Is there something I have nbot considered? Any help would be appreciated. Thanks.
Edit-In responce to one of the comments about my getString usage, on the page linked here my usage is documented, the second string is is the argument object for the formatting string.
Edit 2: I also tried to use a single parameter getSting on the line in question, and got the smae error.

Attempt to invoke virtual method 'void com.example.app.createLoginSession(java.lang.String)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to pass through a username (EMAIL) into the createLoginSession within my SharedPreferencesManagement class. When I try to execute this on the login i'm getting an error which states that "createLoginSession(java.lang.String) on a null object reference".
public class SessionManagement {
// 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";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public SessionManagement(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, ActivityLogin.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, ActivityLogin.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
The code for the Activity Login is as follows:
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.View;
import com.example.myapplication.R;
import com.example.myapplication.InputValidation;
import com.example.myapplication.DatabaseHelper;
public class ActivityLogin extends AppCompatActivity implements
View.OnClickListener {
private final AppCompatActivity activity = ActivityLogin.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton appCompatButtonLogin;
private AppCompatTextView textViewLinkRegister;
private InputValidation inputValidation;
private DatabaseHelper databaseHelper;
public String email;
//Session Manager Class
SessionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
textInputLayoutEmail = (TextInputLayout)
findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout)
findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail = (TextInputEditText)
findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText)
findViewById(R.id.textInputEditTextPassword);
appCompatButtonLogin = (AppCompatButton)
findViewById(R.id.appCompatButtonLogin);
textViewLinkRegister = (AppCompatTextView)
findViewById(R.id.textViewLinkRegister);
;
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
appCompatButtonLogin.setOnClickListener(this);
textViewLinkRegister.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
inputValidation = new InputValidation(activity);
}
/**
* This implemented method is to listen the click on view
*
* #param v
*/
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonLogin:
verifyFromSQLite();
break;
case R.id.textViewLinkRegister:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(intentRegister);
break;
}
}
/**
* This method is to validate the input text fields and verify login
credentials from SQLite
*/
private void verifyFromSQLite() {
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail,
textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail,
textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword,
textInputLayoutPassword, getString(R.string.error_message_email))) {
return;
}
if
(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())) {
email = textInputEditTextEmail.getText().toString().trim();
Intent accountsIntent = new Intent(activity, MainMenuActivity.class);
accountsIntent.putExtra("EMAIL",
textInputEditTextEmail.getText().toString().trim());
session.createLoginSession(email);
emptyInputEditText();
startActivity(accountsIntent);
} else {
// Snack Bar to show success message that record is wrong
Snackbar.make(nestedScrollView,
getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
/**
* This method is to empty all input edit text
*/
private void emptyInputEditText() {
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
}
The error is on the line "session.createLoginSession("EMAIL");" as this is being passed in as a null value.
the problem is that you don't instantiate your SessionManagement object anywhere in your Activity. Implement this statement in your initObjects method session = SessionManagement(this);

How to get rid of this warning? The value of the field is not used

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")

validations on button

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;
}
}

How to notify application user whenever i add something to remote database?

I have developed my first android application.
What that application does: I update mysql database with new results on the website and the android application fetches the same data from mysql. I am using JSON.
What i want it to do: I want it to notify user that the results have been updated. It can bee a timely notification or the normal one. It does not matter. I just want the user to know about it as soon as i update database.
Code for your reference:
1) Java code that displays results inside the application.
package in.thespl.spl.notifications;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllResultsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://mydomain.in/fetchresult.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "result";
private static final String TAG_PID = "rid";
private static final String TAG_NAME = "rname";
private static final String TAG_INFO = "rinfo";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.rid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
AllResultsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product 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 LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllResultsActivity.this);
pDialog.setMessage("Loading results. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String info = c.getString(TAG_INFO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_INFO, info);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// AllResultsActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllResultsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_INFO },
new int[] { R.id.rid, R.id.rname, R.id.rinfo});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Any idea how to add a notification feature in this?
You have multiple ways to do that.
First way is to poll the server to ask for update.
This solution isn't really efficient and lot of params are had to choose:
Time to update-> will affect battery and reactivity.
Second way is to use Google Cloud Messaging. It provides a solution to push data from server to user. It's really simple to implement. (took me some hours).
Android documentation.
http://developer.android.com/guide/google/gcm/index.html
This second way optimizes battery and you could receive push even if your app is off.
Choose the way it's better for your needs.
Hope it helps you.

Categories

Resources