I need help for showing toast and progress dialog inside volley request, and I use a custom adapter file when click on the card will send data with volley, please give better flow or fixing this code.
this is my onBindViewHolder inside adapter file
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final DataPicking task = taskList.get(position);
holder.numberid.setText(task.getNomorid());
holder.nama.setText(task.getNamakonsumen());
holder.rate.setText(task.getRate());
holder.tanggal.setText(task.getTanggal());
holder.salesman.setText(task.getSalesman());
holder.cardList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setTitle("Proses Picking")
.setMessage("Apakah kamu yakin ingin memproses picking data ini?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String nomorid = taskList.get(position).getNomorid();
PickingActivity picking = new PickingActivity();
picking.kirimData(nomorid);
}})
.setNegativeButton(android.R.string.no, null).show();
}
});
}
and this is kirimData function for send data with volley
public void kirimData(final String nomorid){
// Log.e("ini kirimdata ",nomorid);
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Loading ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Constants.URL_SET_PICKING, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Picking Response: " + response.toString());
//hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Log.e(TAG, "obj: " + jObj.toString());
String error = jObj.getString("status");
Log.e(TAG, "obj: " + error);
// Check for error node in json
if (error.equals("1")) {
// user successfully logged in
// Create login session
mAdapter.notifyDataSetChanged();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getBaseContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/*Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();*/
Log.e(TAG, "Proses Picking Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Proses Picking Failed", 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("nomorid", nomorid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
and this is the error log
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.sip.gotrack.PickingActivity.kirimData(PickingActivity.java:167)
at com.sip.gotrack.PickingAdapter$1$1.onClick(PickingAdapter.java:69)
please help me for this error
Where is your pDialog being initialized?
Inside kirimData, initialize pDialog like this in the beginning.
pDialog = new ProgressDialog(context);
It seems pDialog is not initialized before this method is called.
Related
I am successfully deleting an Item from the recyclerView. The Items gets deleted successfully, but the recyclerView is not refreshed after the delete operation.
This is my Adapter code :
holder.removeProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences myPrefs = context.getSharedPreferences("loginToken", Context.MODE_PRIVATE);
getToken = myPrefs.getString("token", null);
new AlertDialog.Builder(context)
.setTitle("Remove from Cart")
.setMessage("Are you sure you want to remove this Item from cart ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteDialog = ProgressDialog.show(context, "",
"Please Wait...", true);
final RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST,
REMOVE_CART_URL + "?token=" + getToken + "&product_id=" + cartModel.getProductid()
, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("success");
if (message.equals("true")) {
Toast.makeText(context, "Item Deleted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Delete error", e.getLocalizedMessage());
}
deleteDialog.dismiss();
notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
deleteDialog.dismiss();
}
});
requestQueue.add(request);
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_delete)
.show();
}
});
The Item after deletion stays there until I close the App and reopen. How do I fix this , so I dont have to reopen app everytime.
Instead of notifyDataSetChanged() write this code:
if (yourAdapterList.size() > 0) {
ourAdapterList.remove(position);
notifyItemRemoved(position);
}
I am working on my app, till morning it was working fine. I used volley in my app. suddenly it stopped working . I am not able to send request to server and get response. It goes to onErrorResponse method. Following is my snippet code
private void makeJsonArrayRequestCountry() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( myorderlist_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
placeorderlists=new ArrayList<MyOrderModel>();;
if(response.length() > 0)
{
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyOrderModel movie = new MyOrderModel();
movie.setOrder_Id(obj.getString("orderID"));
movie.setOrder_Name(obj.getString("packDesc"));
movie.setOrder_Imgpath(obj.getString("packImagePath"));
movie.setOrder_Img(obj.getString("packImageName"));
movie.setOrder_date(obj.getString("orderDate"));
movie.setOrder_Status(obj.getString("orderStatus"));
movie.setCancel_Status(obj.getString("isCancelled"));
placeorderlists.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
textcounter.setText("Total Order : "+placeorderlists.size());
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MyOrderListActivity.this);
builder.setMessage("You Have No Order");
String positiveText = getString(android.R.string.ok);
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// positive button logic
Intent intentc=new Intent(MyOrderListActivity.this,OrderActivity.class);
startActivity(intentc);
}
});
String negativeText = getString(android.R.string.cancel);
builder.setNegativeButton(negativeText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}
// Parsing json
rcAdapter = new RecyclerViewAdapterMyorderlist(MyOrderListActivity.this, placeorderlists);
rView.setAdapter(rcAdapter);
// notifying list adapter about data changes
// so that it renders the list view with updated data
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
in my logcat it shows blank message and getting blank toast
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Once check with below code snippet for error.
#Override
public void onErrorResponse(VolleyError error) {
String body;
//get status code here
String statusCode = String.valueOf(error.networkResponse.statusCode));
//get response body and parse with appropriate encoding
if(error.networkResponse.data!=null) {
try {
body = new String(error.networkResponse.data,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//do stuff with the body...
}
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 am fetching json data through Volley. The problem I am having
is that Volley's onResponse is never called, and hence the data are not parsed and displayed.
Sample JSON data
{
"title": "This is a sample text title title",
"cat": {
"origin" : "United states",
"target" : "Asia",
},
"content": "Lorem ipsum ipsum trxt hag jlak jshss jsyts pjqgq uuqtyq usiuqjo uwywh",
}
NewsActivity
public class NewsDetails extends AppCompatActivity {
private final String TAG = "NewsDetails";
private ProgressDialog mProgresscircle;
TextView newsTitle, newsOrigin, newsContent;
//private int news_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsOrigin = (TextView) findViewById(R.id.dnews_origin);
newsContent = (TextView) findViewById(R.id.dnews_content);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to load newss
loadNews();
} else {
final Context context;
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_titl);
alertDialog.setCancelable(false);
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage(R.string.failed_news);
alertDialog.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialog.show();
} else {
loadNews();
}
}
});
alertDialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
}
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DetailConfig.GET_DURL + news_id,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called NewsDetails");
//Dismissing progressbar;
if (mProgresscircle != null) {
mProgresscircle.dismiss();
}
//Calling method to parse json array
parseNews(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
//This method will parse json data of news
private void parseNews(JSONArray jsonArray) {
Log.d(TAG, "Parsing news array");
for (int i = 0; i<jsonArray.length(); i++) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
newsTitle.setText(title);
JSONObject pOrigin = jsonObject.getJSONObject("cat");
String origin = pOrigin.getString("origin");
newsOrigin.setText(origin);
String content = jsonObject.getString(DetailConfig.TAG_DPOST_CONTENT);
newsContent.setText(content);
} catch (JSONException w) {
w.printStackTrace();
}
}
}
}
The things I know
In logcat, loadNews method is called.
I'm logging Volley, and from logcat volley is not complaining in anyway
I can't see "onResponse called NewsDetails" in logcat, meaning that for some reason not known to me, it's not called
So, my question is why is onResponse not called and how should I fix it?
You should use JsonObjectRequest instead of JsonArrayRequest because you are getting jsonobject in the response.
For getting more knowledge you may go through Volley tutorial
/* you are getting json in response but your response listener method is get Json Array replace your code with below code and also add an debug point in your error listener method */
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
// or replace this code into your into your loadNews method
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
**
You can also refer below link for complete tutorial http://www.hackpundit.com/android-turorial-json-parse-volley/
**
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