I want to get value inside my String JsonObject - android

try {
JSONObject jobj = new JSONObject(response);
String status = jobj.getString("status");
String error = jobj.getString("result");
if(status == "1"){
builder.setTitle("Server Message");
builder.setMessage("Please validate your ID in registered email.");
}else if(status == "0")
{
builder.setTitle("Server Message");
builder.setMessage(error);
}else{
builder.setTitle("Server Message");
builder.setMessage(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent mainIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(mainIntent);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
my response is {"status":"1","result":"true")
But I can't do if else to the "status" mean I can't get value of "1" inside the status.

Two mistakes
Getting integer and boolean as string
Comparing string with ==
Do this
int status = jobj.getInt("status");
Boolean error = jobj.getBoolean("result");
if(status == 1){
builder.setTitle("Server Message");
builder.setMessage("Please validate your ID in registered email.");
}else if(status == 0)
{
...
...

"==" is reference compare.
So, replace "==" to equals()
status.equals("1")

I hope this will work for you.
By using String
String status = jobj.getString("status");
String error = jobj.getString("result");
if(status.equalsIgnoreCase("1")){
builder.setTitle("Server Message");
builder.setMessage("Please validate your ID in registered email.");
}else if(status.equalsIgnoreCase("0")){
// your other code.
}

Related

JSONException: No value for id after completing paypal payment

After a user has payed via PayPal on my android app I want the PaymentId to be displayed, with the state and the amount they have just payed. When i'm trying to get the id from the JSONObject it keeps saying "No value for id" when the id in the logcat has a value.
ID Has A Value As Shown
When I get to the line textViewId.setText(jsonObject.getString("id")); it jumps to the catch and displayed the error "No value for id". Even though in the logcat there is a value.
Below is my code.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PAYPAL_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirmation != null)
{
try
{
String paymentDetails = confirmation.toJSONObject().toString(4);
JSONObject jsonObject = new JSONObject(paymentDetails);
// String id = jsonObject.getString("id");
// String status = jsonObject.getString("state");
// startActivity(new Intent(getActivity(), PaymentDetails.class)
// .putExtra("PaymentDetails", paymentDetails)
// .putExtra("PaymentAmount", totalAmount + commisionAmount));
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
View mView = getLayoutInflater().inflate(R.layout.popup_payment_successful, null);
alertDialog.setTitle("Payment Successful");
alertDialog.setView(mView);
final AlertDialog dialog = alertDialog.create();
dialog.show();
TextView textViewId = mView.findViewById(R.id.textId);
TextView textViewAmount = mView.findViewById(R.id.textAmount);
TextView textViewStatus = mView.findViewById(R.id.textStatus);
jsonObject.has("id");
textViewId.setText(jsonObject.getString("id"));
textViewAmount.setText((int) (totalAmount + commisionAmount));
textViewStatus.setText(jsonObject.getString("state"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getActivity(), "Cancel", Toast.LENGTH_SHORT).show();
}
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
{
Toast.makeText(getActivity(), "Invalid", Toast.LENGTH_SHORT).show();
}
}
Apparently your id is inside response jsonobject so do
JSONObject jsonObject = new JSONObject(paymentDetails);
JSONObject jsonObject1 = jsonObject.optJSONObject("response");// return null or found object
if(jsonObject1 != null){
String id = jsonObject1.optString("id",""); //return value or empty string
String status = jsonObject1.optString("state","");
}

Extract json string i.e authentication Token from Json response for next activity.

*on postExecute()
#Override
protected void onPostExecute(String s) {
if (s != null) {
s.replaceAll("\\s+","");
Log.e("Fetch_frame_response", s);
userToken = s.substring(24,451);
Log.e("userToken", userToken);
Intent abc = new Intent(MainActivity.this, Orderlist.class);
startActivity(abc);
finish();
} else {
Intent abc = new Intent(MainActivity.this, MainActivity.class);
startActivity(abc);
Toast.makeText(MainActivity.this, "Invalid credentials", Toast.LENGTH_LONG).show();
}
}
}
}
*logcat Response which is not fetching me the value i want to stored as a variable userToken
07-29 10:30:57.556 7341-7341/com.example.rinzinchoephel.driverdemo2 E/userToken: 2791d970-c11d-48f6-92f3-8ec4f0b14820","contactEmail":"rchomphel#gmail.com","contactPhones":"+19731488021","createdAt":"2016-07-04T01:42:11.452-05:00","description":"","email":"rchomphel#gmail.com","id":"577a051469702d0380170000","internalId":"rinzin","lastAccessedOn":"2016-07-04T01:42:11.452-05:00","name":"rinzin choephel","phone":"+19731488021","updatedAt":"2016-07-04T01:42:11.452-05:00","userType":"merchant","username":"r
Try this:
#Override
protected void onPostExecute(String s) {
if (s != null) {
Log.e("Fetch_frame_response", s);
try {
JSONObject object=new JSONObject(s);
String userToken=object.getString("authenticationToken");
Log.e("userToken",userToken);
} catch (JSONException e) {
e.printStackTrace();
}
Intent abc = new Intent(MainActivity.this, Orderlist.class);
startActivity(abc);
finish();
} else {
Intent abc = new Intent(MainActivity.this, MainActivity.class);
startActivity(abc);
Toast.makeText(MainActivity.this, "Invalid credentials", Toast.LENGTH_LONG).show();
}
}
}
}
In you postexecute
You must parse your json dont use substring
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject responseObject = new JSONObject(s);
int status = responseObject.getInt("status");
String message =responseObject.getString("message");
if(status == 1){
String UserToken = responseObject.getString("userToken");
Log.i("userToken",UserToken );
Intent abc = new Intent(MainActivity.this, Orderlist.class);
abc.putExtra("userToken",UserToken);
startActivity(abc);
finish();
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}else if(status ==2){
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Intent abc = new Intent(MainActivity.this, MainActivity.class);
startActivity(abc);
Toast.makeText(MainActivity.this, "Invalid credentials", Toast.LENGTH_LONG).show();
}
}
}
}
Note: Use SharedPrefernce to store your user data so that is can be accessed from anywhere

Android payapal integration

this is my first question on stackoverflow.hope i can find my solutuon .i am integrating paypal in android.my device is showing "payment of this marchent are not allowed(invalid client id).here is my code
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID ="my client id";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Rajeev Lochan Sharma")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afcl);
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startService(intent);
ButterKnife.inject(this);
_request3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// signup();
new Test().execute(_names.getText().toString(), _placeofbirth.getText().toString(), _timeofbirth.getText().toString()
);
thingToBuy = new PayPalPayment(new BigDecimal("10"), "USD",
"quote", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(AfcRequest1Activity.this,
PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
});
}
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
private class Test extends AsyncTask {
protected void onPreExecute() {
super.onPreExecute();
//here you can some progress dialog or some view
}
#Override
protected String doInBackground(String... Params) {
String res = "";
try {
byte[] result = null;
String str = "";
HttpClient client;
HttpPost post;
ArrayList<NameValuePair> nameValuePair;
HashMap<String, String> mData;
Iterator<String> it;
HttpResponse response;
StatusLine statusLine;
//here is url api call url
post = new HttpPost("http://astro360horoscope.com/backend/api/form_amc_afc.php");
nameValuePair = new ArrayList<NameValuePair>();
mData = new HashMap<String, String>();
mData.put("username", Params[0]);
mData.put("placeofbirth", Params[1]);
mData.put("timeofbirth", Params[2]);
//for now nothing is there
it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "utf-8"));
client = new DefaultHttpClient();
response = client.execute(post);
statusLine = response.getStatusLine();
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "utf-8");
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
//here we get the response if all is correct
res = str;
} else {
res = str;
return res;
}
} catch (Exception e1) {
res = "error:" + e1.getMessage().toString();
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(AfcRequest1Activity.this,
PayPalFuturePaymentActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
System.out.println(confirm.toJSONObject().toString(4));
System.out.println(confirm.getPayment().toJSONObject()
.toString(4));
Toast.makeText(getApplicationContext(), "Order placed",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
System.out.println("The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
System.out
.println("An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject()
.toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(getApplicationContext(),
"Future Payment code received from PayPal",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("FuturePaymentExample",
"an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration
.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: "
+ correlationId);
// TODO: Send correlationId and transaction details to your server for
// processing with
// PayPal...
Toast.makeText(getApplicationContext(),
"App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}

SQLite Database not updating properly after deleting row

When I delete any data then listitem click is showing error when opening listitem and data are also not correct on custom listview. After deleting row 0 data is not updating properly. Please help..
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
// means this is the view part not the add contact part.
Cursor crs = mydb.getData(Value);
id_To_Update = Value;
crs.moveToFirst();
String nam = crs.getString(crs.getColumnIndex(DBHelper.C_NAME));
String phon = crs.getString(crs
.getColumnIndex(DBHelper.C_PHONE));
String addr = crs.getString(crs
.getColumnIndex(DBHelper.C_ADDRESS));
String dat = crs.getString(crs.getColumnIndex(DBHelper.C_DATE));
String typ = crs.getString(crs.getColumnIndex(DBHelper.C_TYPE));
if (!crs.isClosed()) {
crs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence) phon);
phone.setFocusable(false);
phone.setClickable(false);
type.setText((CharSequence) typ);
type.setFocusable(false);
type.setClickable(false);
address.setText((CharSequence) addr);
address.setFocusable(false);
address.setClickable(false);
date.setText((CharSequence) dat);
date.setFocusable(false);
date.setClickable(false);
}
}
}
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(),
"Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
if (mydb.updateContact(id_To_Update, name.getText().toString(),
phone.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "not Updated",
Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertContact(name.getText().toString(), phone
.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
DBHelper.java
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
}
Finally I have got the solution. I have a text view in custom list view which has Table id which is unique for every row and after deleting the row it's value does not change so I am opening the data of that row on different activity.

I don't get RSS feed values.. I think error in getting Feed values

I am new to JSON. Please any one give a sample code for getting JSON Values...
when i click login button, i want to get User Token valules from Json object..please help me..
here is my code..
Thank you in advanced..
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
String uname = txtUserName.getText().toString();
String pass = txtPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, Loginpage.this);
if(validLogin){
}
}
break;
case R.id.btnCancel:
Intent i = new Intent(Loginpage.this,Loginpage.class);
startActivity(i);
//finish();
break;
}
}
private boolean validateLogin(String uname, String pass, Loginpage loginpage) {
System.out.println("UserToken...");
loginuser();
Intent intent = new Intent(Loginpage.this, Main.class);
intent.putExtra("tokenNumber", token);
startActivity(intent);
return true;
}
private void loginuser() {
// TODO Auto-generated method stub
JSONObject json = JSONfunctions.getJSONfromURL("http://xxx.xxx.x.xxx/my url link...");
token = null;
try {
token = json.getString("UserToken");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("UserToken:"+token);
}
You must search the web to get Example.Bye the way Here is a link.3 minute to json
You must also go to this site to make everything clearJson

Categories

Resources