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
Related
I'm new to android development. I'm trying to send some data to server using volley. But it is not sending parameters. Please help. The server is saying that the parameter is not set. I checked with the isset in php. When I tried sending data from a html form, it's working. But the volley is not sending the parameters.
public class MainActivity extends AppCompatActivity {
EditText uname;
EditText uotp;
RequestQueue myqueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText) findViewById(R.id.uname);
uotp = (EditText) findViewById(R.id.uotp);
myqueue = Volley.newRequestQueue(this);
}
public void sendotp(View v)
{
String unameval = uname.getText().toString();
if(unameval.matches(""))
{
Toast.makeText(getApplicationContext(), "Enter Phone Number", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, String> params = new HashMap<>();
params.put("phone", unameval);
String myUrl = "http://privateurlhere";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, myUrl, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String dispname = response.getString("stat");
Toast.makeText(getApplicationContext(), dispname, Toast.LENGTH_SHORT).show();
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Resp err" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
myqueue.add(request);
}
}
}
facing problem in posting data to mysql database using rest api which is done in magento 2 from my android app.
RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "https://xyz/restapi/registration";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputCnfPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputCnfPassword = (EditText) findViewById(R.id.signup_input_passwords);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
signupInputCnfPassword.getText().toString(),
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password, final String cnfpassword, final String dob) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
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("cust_username", name);
params.put("cust_firstname", email);
params.put("cust_pass", password);
params.put("cust_confirmpass", cnfpassword);
params.put("cust_phoneno", dob);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I am using Volley library for request.
I am getting this error
BasicNetwork.performRequest: Unexpected response code 503 for
https://xyz/restapi/registration.
My question is am I missing any thing or will there be constrain that should be checked in mysql to post the data.
I have written a code using a volley library (GET) and I have to fetch the data from the rest API in Django.
Actually the problem is i am getting a user id while i login , i just saved that id through shared preferences and i have to pass the id in the URL to get wallet details but i am getting error
BasicNetwork.performRequest: Unexpected response code 403
public class Wallet extends AppCompatActivity {
TextView all_tv1;
Button credit_bt, debit_bt;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_wallet);
pref=getApplication().getSharedPreferences("Options", MODE_PRIVATE);
Integer Key_UserID=pref.getInt("UserId_Value", 0);
// String a = Key_UserID.toString();
/Json Request/
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/+Key_UserID";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getApplicationContext(),"stop",LENGTH_SHORT).show();
// String data = "";
try {
for(int i=0; i< response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
String tnx_id = obj.getString("tnx_id");
String transition_type = obj.getString("transition_type");
// String email = obj.getString("email");
// System.out.print("\nggtrgtg"+user+"\ngfg"+amount);
Toast.makeText(getApplicationContext(),tnx_id + transition_type ,LENGTH_SHORT).show();
// data = "" + id + "" + name + "" + email + "";
//txtDisplay.setText(txtDisplay.getText()+"\n" + id + "" + name + "\n" + email + "");
// Adds the data string to the TextView "results"
}
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),"Faled Misreably" ,LENGTH_SHORT).show();
}
});
//add request to queue
requestQueue.add(jsonArrayRequest);
setTitle("Wallet Window");
Toolbar toolbar1 = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar1);
all_tv1 = (TextView)findViewById(R.id.all_tv);
all_tv1.setMovementMethod(new ScrollingMovementMethod());
credit_bt = (Button)findViewById(R.id.credit_details1__bt);
debit_bt = (Button) findViewById(R.id.debit_details1__bt);
credit_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Credit Tab", LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Wallet_Credit.class);
startActivity(i);
finish();
}
});
debit_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Debit Tab", LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Wallet_Debit.class);
startActivity(i);
finish();
}
});
}
}
Your uri string is not set properly (notice the closing "). Instead of
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/+Key_UserID";
It should be
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/"+Key_UserID;
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/
**