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)
Related
I have a android consuming a django REST API backend which includes token based authentication.
The problem is that whenever a user provides a wrong email or password, i expect a 403 error from the code below but the volley library does not get the response code.
This is the backed service in django rest.
def api_authenticate_user(request):
try:
email = request.data['email']
password = request.data['password']
user = authenticate(email=email, password=password)
if user is not None:
try:
payload = jwt_payload_handler(user)
token = jwt.encode(payload, settings.SECRET_KEY)
user_logged_in.send(sender=user.__class__, request=request, user=user)
user = User.objects.get(email=email)
user_details = {'token': token, 'names': user.get_name(), 'id': user.id}
return JsonResponse(user_details, status=status.HTTP_200_OK)
except Exception as e:
raise e
else:
return JsonResponse({'error': 'Invalid email address or password', 'status': status.HTTP_403_FORBIDDEN})
except KeyError:
return JsonResponse({'error': 'Provide email and password', 'status': status.HTTP_403_FORBIDDEN})
In my android app, this is how am trying to get the response code so that i can alert the user to enter the right credentials.
private void UserLoginTask(final String email, final String password) {
StringRequest request = new StringRequest(Request.Method.POST, loginUrl , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject userObj = new JSONObject(response);
userSession.initializeSession(userObj.getString("names"), email, userObj.getString("token"));
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
errorText.setText("Could not process your request. Try again");
errorText.setVisibility(View.VISIBLE);
showProgress(false);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.networkResponse);
if(error.networkResponse.statusCode == 403){
errorText.setText("Invalid email address or password");
}else{
errorText.setText("Could not process your request. Try again");
}
errorText.setVisibility(View.VISIBLE);
showProgress(false);
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(Login.this);
queue.add(request);
}
When i try to log or get the error status as shown in the volley error listener class, I get this error showing that the response network status is null. How can i get the 403 or any other status code.
2019-04-15 22:24:46.461 31397-31397/com.example.phanue.antenatal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.phanue.antenatal, PID: 31397
java.lang.NullPointerException: Attempt to read from field 'int com.android.volley.NetworkResponse.statusCode' on a null object reference
at com.example.phanue.antenatal.LoginData.Login$4.onErrorResponse(Login.java:153)
at com.android.volley.Request.deliverError(Request.java:564)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6942)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Check null pointer to avoid NullPointerException
#Override
public void onErrorResponse(VolleyError error) {
if (error != null && error.networkResponse != null && error.networkResponse.statusCode == 403) {
errorText.setText("Invalid email address or password");
}
else{errorText.setText("Could not process your request. Try again");
}
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
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.
Hey developers i am tried send the data through intent
i am sending data A activity to B activity data is send A Activity properly but B Activity is not receive but some data is receive but some data not receive
Code is A Activity
private void requestForSMS(final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
config.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);
final String user = responseObj.getString("uid");
String message = responseObj.getString("msg");
Intent intent1 = new Intent(getApplicationContext(),HttpService.class);
intent1.putExtra("uid", user); // <---Sending data here this data not recive B Activity ------>
Log.d("user id going","====>"+user);
if(!user.equalsIgnoreCase("")){
pref.setIsWaitingForSms(true);
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"ErrorToast: " + 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, "ErrorResponce: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxxxxx");
params.put("mobile", mobile);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
// Adding request to request queue
newapp.getInstance().addToRequestQueue(strReq);
}
private void verifyOtp() {
String otp = inputOtp.getText().toString().trim();
if (!otp.isEmpty()) {
Intent grapprIntent = new Intent(getApplicationContext(), HttpService.class);
// <---- sending data here also B Activity---->
grapprIntent.putExtra("key","xxxxxxxxxxxx");
grapprIntent.putExtra("mobileverify", otp);
startService(grapprIntent);
} else {
Toast.makeText(getApplicationContext(), "Please enter the OTP", Toast.LENGTH_SHORT).show();
}
}
private static boolean isValidPhoneNumber(String mobile) {
String regEx = "^[0-9]{10}$";
return mobile.matches(regEx);
}
B Activity
public class HttpService extends IntentService {
private static String TAG = HttpService.class.getSimpleName();
public HttpService() {
super(HttpService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String otp = intent.getStringExtra("mobileverify");
final String user1 = intent.getStringExtra("uid"); //<---- this is not recive value ---->
verifyOtp(otp,user1);
}
}
/**
* Posting the OTP to server and activating the user
*
* #param otp otp received in the SMS
*/
private void verifyOtp(final String otp, final String user1){
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_VERIFY_OTP, 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
String message = responseObj.getString("msg");
if (message!="") {
// parsing the user profile information
JSONObject profileObj = responseObj.getJSONObject(response);
String mobile = profileObj.getString("mobile");
PrefManager pref = new PrefManager(getApplicationContext());
pref.createLogin(mobile);
Intent intent = new Intent(HttpService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(getApplicationContext(), "HTTPIF"+message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "HTTPELSE"+message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "HTTPError: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxx");
params.put("mobileverify", otp);
params.put("uid",user1); // here its given error
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
Please Help me Thanks
Your grapprIntentdoesn't contain a value for "uid" key because you don't put it. You use some intent1 which is not used anywhere more. Instead you need to put "uid" into grapprIntent:
grapprIntent.putExtra("uid", user);
Maybe grapprIntent should be global variable for the class or find a way to pass it between methods.
Create A Global variable in your Application class and Use set and get Methods
like this
Application.class
private String user;
public String setuser(String usermy) {
this.user = usermy;
return null;
}
public String getuser()
{
return user;
}
where you want to send value set value like as your code
SMSActivity
MyApplication myUser = (MyApplication)getApplicationContext();
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
String user = responseObj.getString("uid");
String user1 = myUser.setuser(user);
And Get Value in your HttpService.class
Like this
MyApplication uidinfo = (MyApplication)getApplicationContext();
final String user = uidinfo.getuser();
and mention manifest.xml inside Application tag
<application
android:name=".MyApplication"
/>
happy coding