i am getting this error on and on. followings are related code pieces:
int digi=0;
public Pointcalculator pointCalculator = new Pointcalculator();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
digi = pointCalculator.digicalculator();
Toast.makeText(getApplicationContext(), Integer.toString(digi), Toast.LENGTH_LONG).show();
}
this is another piece :
public int digicalculator()
{
//int digipoints=0;
// Log.d("ggggggggg","digicallll");
fetchPoints("hh");
digipoints = digipoints + 30;
return digipoints;
}
private void fetchPoints(String email)
{
// Tag used to cancel the request
String tag_string_req = "fetch_points";
Log.d("ggggggggg","digicallll");
Toast.makeText(getApplicationContext(),"in fetch", Toast.LENGTH_LONG).show();
pD.setMessage("Fetching Points ...");
showDialog(10);
/* StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_FETCH_USER_POINTS, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d(TAG, "FETCH RESPONSE: " + response.toString());
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
//hideDialog(10);
try {
JSONObject jObj = new JSONObject(response);
// boolean error = jObj.getBoolean("error");
// if (!error)
// {
// Now store the user in sqlite
String totalpts = (jObj.getString("totalpoints"));
String digipts = (jObj.getString("digipoints"));
Toast.makeText(getBaseContext(), "totalpoints : "+totalpts, Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "digipoints : "+digipts, Toast.LENGTH_SHORT).show();
try
{
totalpoints = Integer.parseInt(totalpts);
digipoints = Integer.parseInt(digipts);
}
catch(NumberFormatException nfe)
{
System.out.println("Could not parse " + nfe);
}
// Inserting row in users table
// db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "Points successfully retrieved!", Toast.LENGTH_LONG).show();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.e(TAG, "Points retriving Error: " + error.toString());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
//hideDialog();
}
}) {
#Override
protected Map<String, String> getParams()
{
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("email", "hh");
return params;
}
};*/
// Adding request to request queue
// AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
i cannot understand what is causing this error. as you can see I commented all the fetching information part in the method. and i cannot call neither pdialoge () nor Toast function.
and this is logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.example.neshat.test.Pointcalculator.fetchPoints(Pointcalculator.java:64)
at com.example.neshat.test.Pointcalculator.digicalculator(Pointcalculator.java:52)
at com.example.neshat.test.MainActivity.onCreate(MainActivity.java:18)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The first parameter for a Toast is a Context, I think you should pass it asthis or YourActivity.this if it is in yout MainActivity it would be like MainActivity.this, give it a try.
Related
i am posting data to the server and while debugging i get the following error at this line. and unable to call the server.
network calls. i am using sql server version 2014, and the url to web services is localhost:8081/api/login/signup.
StringRequest strReq = new StringRequest(Request.Method.POST, Constants.SIGN_UP,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Snackbar.make(mainlayout, response.toString(), Snackbar.LENGTH_LONG).show();
Log.e("Responce from server", response);
avi.hide();
if(!response.contains("User")) {
spEdit.putString(getString(R.string.uaccount), response);
spEdit.commit();
Intent intent = new Intent(SignUp.this, Products.class);
intent.putExtra(getString(R.string.uemail), Email_Address);
intent.putExtra(getString(R.string.uphone), Phone_Number);
intent.putExtra(getString(R.string.upass), Password);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
avi.hide();
Log.e("Volley Error", error.toString());
if(error.toString().contains("NoConnectionError")) {
Snackbar.make(mainlayout, "Internet Not Available!", Snackbar.LENGTH_LONG).show();
}else{
Snackbar.make(mainlayout, "Webservice not responding!", Snackbar.LENGTH_LONG).show();
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<String, String>();
String name[] = Name.split(" ");
String first = "", last = "";
boolean firstb = true;
for (int i = 0; i < name.length; i++) {
if (firstb) {
first += name[i];
firstb = false;
} else {
if (i == name.length - 1) {
last = name[i];
} else {
first += " ";
first += name[i];
}
}
}
data.put("FirstName", first);
data.put("LastName", last);
data.put("LoginName", Login_Name);
data.put("PrimaryEmail", Email_Address);
data.put("PrimaryPasscode", Encrypted_Password);
data.put("PhoneNumber", Phone_Number);
data.put("MobileVerificationCode", smsCode);
data.put("AccountType", UserType);
return data;
}
};
AppController.getInstance().addToRequestQueue(strReq, REQ_TAG);
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: market.enxo.com.marketstore, PID: 3202
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.<init>(Request.java:136)
at com.android.volley.toolbox.StringRequest.<init>(StringRequest.java:43)
at market.enxo.com.marketstore.SignUp$8.<init>(SignUp.java:361)
at market.enxo.com.marketstore.SignUp.signUpWS(SignUp.java:332)
at market.enxo.com.marketstore.SignUp$4.onClick(SignUp.java:297)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I am Creating an application which perform an OTP verification method..
I implemented the code as described in this link http://www.androidhive.info/2015/08/android-adding-sms-verification-like-whatsapp-part-2/
But when i click the NEXT button in app app is force closing
The function i get error is :
private void requestForSMS(final String name, final String email, final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
boolean error = responseObj.getBoolean("error");
String message = responseObj.getString("message");
// checking for error, if not error SMS is initiated
// device should receive it shortly
if (!error) {
// boolean flag saying device is waiting for sms
pref.setIsWaitingForSms(true);
// moving the screen to next pager item i.e otp screen
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Error: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
//Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.e(TAG, "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
/**
* Passing user parameters to our server
* #return
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("mobile", mobile);
//Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Log is :
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.my.application.activity.SmsActivity.requestForSMS(SmsActivity.java:245)
at com.my.application.activity.SmsActivity.validateForm(SmsActivity.java:157)
at com.my.application.activity.SmsActivity.onClick(SmsActivity.java:117)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17446)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Volley library is used..
Any help??
public void confirmOTP() throws JSONException {
LayoutInflater lf = LayoutInflater.from(SignUp.this);
View view = lf.inflate(R.layout.confirm_dialog, null);
confirmButton = (Button) view.findViewById(R.id.buttonConfirm);
inputOTP = (EditText) view.findViewById(R.id.editTextOtp);
AlertDialog.Builder dialog = new AlertDialog.Builder(SignUp.this);
dialog.setView(view);
final AlertDialog alertDialog = dialog.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
final ProgressDialog load = ProgressDialog.show(SignUp.this, "Authenticating", "Please Wait ...", false, false);
load.setCanceledOnTouchOutside(false);
final String otp = inputOTP.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfingDetalsActivity.CONFIRM_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Confirm Response Check>",response.toString());
String mesage;
try {
JSONObject jsonObject=new JSONObject(response);
mesage=jsonObject.getString("msg");
if(mesage.equals("success")){
Toast.makeText(SignUp.this, "Registerd sucessfully", Toast.LENGTH_LONG).show();
load.dismiss();
Intent in = new Intent(SignUp.this, SignupSucess.class);
startActivity(in);
} else {
load.dismiss();
Toast.makeText(SignUp.this, "Wrong OTP Please try again", Toast.LENGTH_SHORT).show();
confirmOTP();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
load.dismiss();
Toast.makeText(SignUp.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map params = new HashMap();
//Adding the parameters otp and username
params.put(ConfingDetalsActivity.KEY_OTP, otp);
if (businessFrag) {
} else {
params.put(ConfingDetalsActivity.CONSUMER_EMAIL, constant.EMAIl);
}
return params;
}
};
requestQueue.add(stringRequest);
}
});
}
public void register() {
Log.d("RegisterCalled>>>>>>>>>", "register");
final ProgressDialog load = ProgressDialog.show(SignUp.this, "Loading", "Pleas wait...", false, false);
load.setCanceledOnTouchOutside(false);
StringRequest request = new StringRequest(Request.Method.POST, ConfingDetalsActivity.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Check>>>",response.toString());
load.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String message=jsonObject.getString("msg");
if (message.equals("success")) {
confirmOTP();
} else {
Toast.makeText(SignUp.this, "User Name or phone already register", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
load.dismiss();
Toast.makeText(SignUp.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parms = new HashMap<String,String>();
if (businessFrag) {
parms.put(ConfingDetalsActivity.BUSINESS_ZIP_CODE, constant.B_ZIP_CODE);
parms.put(ConfingDetalsActivity.BUSINESS_INDUSTRY, constant.B_INDUSTRY);
parms.put(ConfingDetalsActivity.BUSINESS_PHONE, constant.B_MOBILE);
parms.put(ConfingDetalsActivity.BUSINESS_EMAIL, constant.B_EMAIl);
parms.put(ConfingDetalsActivity.BUSINESS_PASSWORD, constant.B_PASSSOWRD);
parms.put(ConfingDetalsActivity.SIGNUP_TYPE,"1");
} else {
parms.put(ConfingDetalsActivity.CONSUMER_FNAME, constant.F_NAME);
parms.put(ConfingDetalsActivity.CONSUMER_LNAME, constant.L_NAME);
parms.put(ConfingDetalsActivity.CONSUMER_PHONE, constant.MOBILE);
constant.EMAIl);
parms.put(ConfingDetalsActivity.CONSUMER_PASSWORD, constant.PASSSOWRD);
parms.put(ConfingDetalsActivity.SIGNUP_TYPE,"0");
}
return parms;
}
};
requestQueue.add(request);
}
I have 3 functions that are uploading images and setting the name of an image on a server. The thing is, I can't get all functions to work at a time. Only one function works and the other throws a NullPointerException that aren't pointing to anything specific but just the first line in the function.
private void uploadMainImage()
{
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest ppRequest = new StringRequest(Request.Method.POST,URL_IMAGE_MAIN , new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println("Response[Job Image Main]: " + response.toString());
uploadThumbImage();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
System.out.println("Job Image profile Error: " + error.getMessage());
progressDialog.hide();
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("ImageName",jobID + "-1.jpg");
params.put("base64", pp_finalImage);
return params;
}
};
queue.add(ppRequest);
}
private void uploadThumbImage()
{
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest ppRequest = new StringRequest(Request.Method.POST,URL_IMAGE_THUMB , new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println("Response[Job Image Thumb]: " + response.toString());
//updateImageName();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
System.out.println("Job Thumb Image profile Error: " + error.getMessage());
progressDialog.hide();
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("ImageName",jobID + "-1.jpg");
params.put("base64", thumb_finalImage);
return params;
}
};
queue.add(ppRequest);
}
private void updateImageName()
{
SharedPreferences prefs = getActivity().getSharedPreferences("USER_DETAILS", Context.MODE_PRIVATE);
String userID = prefs.getString("USER_ID", "NO_SESSION");
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
Map<String, String> params = new HashMap<String, String>();
params.put("postpicture ", jobID + "-1.jpg");
params.put("userid", "1");
params.put("postjobid ", jobID);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,URL + "updateJobPostImage" ,new JSONObject(params), new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(LOG_TAG,"Response[Image Name Update Job]: " + response.toString());
try
{
String status = response.getString("result");
if(status.equals("Success"))
{
progressDialog.hide();
progressDialog.dismiss();
}
else
{
Log.d(LOG_TAG," Image Name Update Failed, Aborting.");
progressDialog.hide();
progressDialog.dismiss();
}
}
catch (JSONException e)
{
Log.d(LOG_TAG,e.getMessage());
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
progressDialog.hide();
progressDialog.dismiss();
Log.d(LOG_TAG, "Image Name Update Error: " + error.getMessage());
}
});
queue.add(request);
}
This is the log
04-30 00:41:29.074 14041-14041/com.antisaby.trackit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antisaby.trackit, PID: 14041
java.lang.NullPointerException
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at fragments.homefragments.AddServiceFragment.uploadThumbImage(AddServiceFragment.java:397)
at fragments.homefragments.AddServiceFragment.access$1100(AddServiceFragment.java:50)
at fragments.homefragments.AddServiceFragment$8.onResponse(AddServiceFragment.java:368)
at fragments.homefragments.AddServiceFragment$8.onResponse(AddServiceFragment.java:363)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5322)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
The uploadMainImage function executes first. If the response is good, it calls uploadThumbImage. If the result of uploadThumbImage is good, it calls updateImageName. If i don't comment out any function, the exception occurs in the uploadThumbImage function. If i comment out the first function, exception occurs in the last function. If I try to catch the exception, the message comes out to be null.
A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
Source
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I know this is a really common topic but I'm getting this error and don't know why. The code is working absolutely fine in Eclipse but crashing on Button click in Studio. The only difference I can think of is Request.Method instead of Method as in Eclipse. Earlier I thought its because, the values from edittext are not getting. But its showing in Toast.
Error
01-13 11:13:34.242 14427-14427/com.sam.sports E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sam.sports, PID: 14427
java.lang.NullPointerException
at com.sam.sports.LoginPage.checkLogin(LoginPage.java:180)
at com.sam.sports.LoginPage.access$200(LoginPage.java:28)
at com.sam.sports.LoginPage$1.onClick(LoginPage.java:80)
at android.view.View.performClick(View.java:4562)
at android.view.View$PerformClick.run(View.java:18918)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)
01-13 11:13:38.996 14427-14427/com.sam.sports I/Process: Sending signal. PID: 14427 SIG: 9
public class LoginPage extends AppCompatActivity {
private static final String TAG = RegisterPage.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
String name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
inputEmail = (EditText) findViewById(R.id.email_login);
inputPassword = (EditText) findViewById(R.id.password_login);
btnLogin = (Button) findViewById(R.id.login_btn);
btnLinkToRegister = (Button) findViewById(R.id.btnLinktoRegd);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginPage.this, HomePage.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
//Toast.makeText(getApplicationContext(), email + "\n" + password, Toast.LENGTH_LONG ).show();
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(LoginPage.this, RegisterPage.class));
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
String status = jObj.getString("status");
// Now check status value
if (status.equals("0")) {
Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();
}else if(status.equals("1")){
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
JSONObject userData = jObj.getJSONObject("userData");
String uid = userData.getString("id");
String name = userData.getString("name");
String email = userData.getString("email");
String created_at = userData.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
startActivity(new Intent(LoginPage.this, HomePage.class));
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Although this is not a solution to your problem(for solution look below), refactoring the checkLogin Method will definetly help alot in finding the cause of the error. Due to the fact that the checkLogin method was way to long I've move some of the code into other methods.
Copy it, run it and let us know which line throws the error.
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
checkStatus();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void checkStatus() {
try {
JSONObject jObj = new JSONObject(response);
String status = jObj.getString("status");
// Now check status value
if (status.equals("0")) {
processStatusZero();
}else if(status.equals("1")){
processStatusOne(jObj);
} else {
processStatusError(jObj);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void processStatusZero() {
Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();
}
private void processStatusOne(JSONObject jObj) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
JSONObject userData = jObj.getJSONObject("userData");
String uid = userData.getString("id");
String name = userData.getString("name");
String email = userData.getString("email");
String created_at = userData.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
startActivity(new Intent(LoginPage.this, HomePage.class));
finish();
}
private void processStatusError(JSONObject jObj) {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
Now for the actual solution: you need to add AppControler to the Android Manifest. You do this by adding the following lines in your manifest file:
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
This way AppController.getInstance() will stop returning null.
Im using a tutorial from http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
when i click the Login or Register button the app crashes instantly with a null ponter exception. LogCat is pointing me to 3 lines in the code(Login.java). Any ideas on how to fix this?
loginCheck(email, password);
private void loginCheck(final String email, final String password) {
and
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
LogCat
E/AndroidRuntime(6911): java.lang.NullPointerException
E/AndroidRuntime(6911): at com.smwale.zicaresults1.Login.loginCheck(Login.java:176)
E/AndroidRuntime(6911): at com.smwale.zicaresults1.Login.access$2(Login.java:108)
E/AndroidRuntime(6911): at com.smwale.zicaresults1.Login$1.onClick(Login.java:85)
E/AndroidRuntime(6911): at android.view.View.performClick(View.java:3511)
E/AndroidRuntime(6911): at android.view.View$PerformClick.run(View.java:14105)
E/AndroidRuntime(6911): at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime(6911): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(6911): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(6911): at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime(6911): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(6911): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(6911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime(6911): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime(6911): at dalvik.system.NativeStart.main(Native Method)
Login,java
public class Login extends Activity{
// LogCat tag
private static final String TAG = Register.class.getSimpleName();
private Button buttonLogin;
private Button btnLinkToRegister;
private EditText emailInput;
private EditText passwordInput;
private ProgressDialog pDialog;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_login);
emailInput = (EditText)findViewById(R.id.etLoginEmail);
passwordInput = (EditText)findViewById(R.id.etLoginPass);
buttonLogin = (Button)findViewById(R.id.buttonLogin);
btnLinkToRegister = (Button)findViewById(R.id.buttonToReg);
//p dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
//sessionMan
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Login.this, HomeActivity.class);
startActivity(intent);
finish();
}
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailInput.getText().toString();
String password = passwordInput.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
loginCheck(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Register.class);
startActivity(i);
finish();
}
});
}
private void loginCheck(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(Login.this,
HomeActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
private void actionBarSetup() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = getActionBar();
ab.setTitle("My Results");
ab.setSubtitle("Login screen");
}
}}
Joshua
I faced the same problem.Found that "AppController.getInstance()" is returning NULL.
May be you missed
android:name="info.androidhive.loginandregistration.app.AppController" in the manifest file