i am working on android studio developing mobile application. i have a payment feature and i integrated PayPal sandbox and when user clicks check out the PayPal page appears. however, when any buyers tries to log in using the appeared page it "incorrect username/password. please try again" although i am sure it is correct and tried multiple accounts and one of them has a valid real credit card but same output. I wonder why this happens? please can someone help me as soon as possible.
this what appears when user tries to log in:
screen shot of PayPal error message
three java classes are related to payment part are provided:
confirmOrder.java:
package com.example.my1stapplication;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.content.Intent;
import com.example.my1stapplication.config.Config;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import android.text.TextUtils;
import android.widget.Toast;
import org.json.JSONException;
import java.io.Serializable;
import java.util.HashMap;
import java.math.BigDecimal;
public class confirmOrder extends AppCompatActivity {
EditText district, streetName, houseNo, phoneNo;
Button checkout;
DatabaseReference ordersref= FirebaseDatabase.getInstance().getReference("Orders");
final HashMap<String, Object> ordersMap=new HashMap<>();
public static final int PAYPAL_REQUEST_CODE=7171;
private static PayPalConfiguration config = new PayPalConfiguration().environment(PayPalConfiguration.ENVIRONMENT_SANDBOX).clientId(Config.PAYPAL_CLIENT_ID);
//Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);
#Override
protected void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_order);
Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
startService(intent);
district = (EditText) findViewById(R.id.district);
streetName = (EditText) findViewById(R.id.streetName);
houseNo = (EditText) findViewById(R.id.houseNo);
phoneNo = (EditText) findViewById(R.id.phoneNo);
checkout = (Button) findViewById(R.id.checkout);
String buyerID = getIntent().getStringExtra("buyerID");
// Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);
//HashMap cart=(HashMap) getIntent().getSerializableExtra("cart");
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String district1 = district.getText().toString();
String streetName1 = district.getText().toString();
String houseNo1 = district.getText().toString();
String phoneNo1 = district.getText().toString();
if (!TextUtils.isEmpty(district1) && !TextUtils.isEmpty(district1)
&& !TextUtils.isEmpty(district1) && !TextUtils.isEmpty(district1)) {
Double totalPrice = getIntent().getDoubleExtra("totalPrice", 0);
HashMap<String, Object> cart = (HashMap<String, Object>) getIntent().getSerializableExtra("cart");
String Orderid = ordersref.push().getKey();
ordersMap.put("orderID", Orderid);
ordersMap.put("totalPrice", (totalPrice));
ordersMap.put("buyerID", FirebaseAuth.getInstance().getCurrentUser().getUid());
ordersMap.put("district", district1);
ordersMap.put("streetName", streetName1);
ordersMap.put("houseNo", houseNo1);
ordersMap.put("phoneNo", phoneNo1);
ordersMap.put("paied", false);
ordersMap.put("shipped", false);
ordersMap.put("takenFromOwner", false);
//ordersMap.put("inCart", adapter);
ordersref.child(Orderid).updateChildren(ordersMap);
ordersref.child(Orderid).child("cart").updateChildren(cart);
processPayment();
} else {
Toast.makeText(getApplicationContext(), "please enter all fields", Toast.LENGTH_LONG).show();
}
}
});
}
private void processPayment(){
Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);
PayPalPayment payPalPayment =new PayPalPayment(new BigDecimal(totalPrice),"USD", "Pay for the material/s" , PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT,payPalPayment);
startActivityForResult(intent,PAYPAL_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);
super.onActivityResult(requestCode, resultCode, 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);
startActivity(new Intent(this, PaymentDetails.class).putExtra("PaymentDetails", paymentDetails).putExtra("PaymentAmount", totalPrice));
} catch (JSONException e) {
e.printStackTrace();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Cancel", Toast.LENGTH_SHORT).show();
}
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Toast.makeText(this, "Invalid Payment", Toast.LENGTH_SHORT).show();
}
}
}
}
PaymentDetails.java:
package com.example.my1stapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONObject;
import android.content.Intent;
import org.json.JSONException;
public class PaymentDetails extends AppCompatActivity {
TextView txtId,txtAmount,txtStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_details);
txtId = (TextView)findViewById(R.id.txtId);
txtStatus = (TextView)findViewById(R.id.txtStatus);
txtAmount = (TextView)findViewById(R.id.txtAmount);
Intent intent=getIntent();
try{
JSONObject jsonObject = new JSONObject(intent.getStringExtra("PaymentDetails"));
showDetails(jsonObject.getJSONObject("response"),intent.getStringExtra("PaymentAmount"));
}
catch (JSONException e){
e.printStackTrace();
}
}
private void showDetails(JSONObject response , String paymentAmount) throws JSONException {
try {
txtId.setText(response.getString("id"));
txtStatus.setText(response.getString("status"));
txtAmount.setText("SR"+paymentAmount);
}
catch(JSONException e){
e.printStackTrace();
}
}
}
Config.java:
package com.example.my1stapplication.config;
public class Config {
public static final String PAYPAL_CLIENT_ID = "AR1bLXBzCYYWa4BCkEyTTcbijrtWPh9u15b3sxQbHQZ-ymhEonDq9zwMo1CqqM95fwHPp-pNjbRF99Am";
}
In order to log into a PayPal Sandbox page, you must use a PayPal Sandbox ( www.sandbox.paypal.com ) account , not a live ( www.paypal.com ) account.
You can create as many PayPal Sandbox accounts as you need within https://www.paypal.com/signin?returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Faccounts
Their email identifiers are fictitious and can be anything not previously used in sandbox. No real emails are ever sent to those addresses; instead, there is a Notifications tab on the left of developer.paypal.com
Related
I am creating an app similar to a notes app. I have an activity that is called AddEditUserActivity, and, as its name implies, it adds OR edits a user (the object that I created). When I click on a user on the RecyclerView, I am supposed to go to the AddEditUserActivity and see the 5 fields full with the info of the selected user with the title of the activity as "Edit User". When I create a new user, I am supposed to go to the same activity, but with the fields empty, and "Add User" as the title. Creating a user works fine, but when I try to edit it, the activity appears with "Add User" as a title and all the fields empty.
The strange thing is that I implemented some Toast messages like "User updated" and "User Created", and they show when they are supposed to. I think that the problem is in the MainActivity. When I click on a user, I putExtra to an Intent and then call startActivityForResult(EDIT_USER_REQUEST, intent). In the AddEditUserActivity, inside onCreate, I specified that if the intent has a specific extra (the id) then it means that I am updating the user. But it ignores that part. So I would really appreciate it if you could help me.
Here is my MainActivity:
package com.example.citadelentrance;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int ADD_USER_REQUEST = 1;
public static final int EDIT_USER_REQUEST = 2;
private UserViewModel userViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton addUserButton = findViewById(R.id.button_add_user);
addUserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddEditUserActivity.class);
startActivityForResult(intent, ADD_USER_REQUEST);
}
});
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final UserAdapter adapter = new UserAdapter();
recyclerView.setAdapter(adapter);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
userViewModel.getAllUsers().observe(this, new Observer<List<User>>() {
#Override
public void onChanged(#Nullable List<User> users) {
adapter.submitList(users);
}
});
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
userViewModel.delete(adapter.getUserAt(viewHolder.getAdapterPosition()));
Toast.makeText(MainActivity.this, "User deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
adapter.setOnItemClickListener(new UserAdapter.OnItemClickListener() {
#Override
public void onItemClick(User user) {
Intent intent = new Intent(MainActivity.this, AddEditUserActivity.class);
intent.putExtra(AddEditUserActivity.EXTRA_ID, user.getId());
intent.putExtra(AddEditUserActivity.EXTRA_NAME, user.getName());
intent.putExtra(AddEditUserActivity.EXTRA_FAMILY, user.getFamily());
intent.putExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE, user.getLicensePlate());
intent.putExtra(AddEditUserActivity.EXTRA_DOCUMENT, user.getDocument());
intent.putExtra(AddEditUserActivity.EXTRA_ADDRESS, user.getAddress());
intent.putExtra(AddEditUserActivity.EXTRA_TIME, user.getTime());
startActivityForResult(intent, EDIT_USER_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_USER_REQUEST && resultCode == RESULT_OK) {
assert data != null;
String name = data.getStringExtra(AddEditUserActivity.EXTRA_NAME);
String family = data.getStringExtra(AddEditUserActivity.EXTRA_FAMILY);
String licensePlate = data.getStringExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE);
String document = data.getStringExtra(AddEditUserActivity.EXTRA_DOCUMENT);
String address = data.getStringExtra(AddEditUserActivity.EXTRA_ADDRESS);
String time = data.getStringExtra(AddEditUserActivity.EXTRA_TIME);
User user = new User(
name,
family,
licensePlate,
document,
address,
time
);
userViewModel.insert(user);
Toast.makeText(this, "User saved", Toast.LENGTH_SHORT).show();
} else if (requestCode == EDIT_USER_REQUEST && resultCode == RESULT_OK) {
assert data != null;
int id = data.getIntExtra(AddEditUserActivity.EXTRA_ID, -1);
if (id == -1) {
Toast.makeText(this, "User couldn't be updated", Toast.LENGTH_SHORT).show();
return;
}
String name = data.getStringExtra(AddEditUserActivity.EXTRA_NAME);
String family = data.getStringExtra(AddEditUserActivity.EXTRA_FAMILY);
String licensePlate = data.getStringExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE);
String document = data.getStringExtra(AddEditUserActivity.EXTRA_DOCUMENT);
String address = data.getStringExtra(AddEditUserActivity.EXTRA_ADDRESS);
String time = data.getStringExtra(AddEditUserActivity.EXTRA_TIME);
User user = new User(
name,
family,
licensePlate,
document,
address,
time
);
user.setId(id);
userViewModel.update(user);
Toast.makeText(this, "User updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "User not saved", Toast.LENGTH_SHORT).show();
}
}
}
And here the AddEditUserActivity:
package com.example.citadelentrance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.time.LocalDateTime;
import java.util.Objects;
public class AddEditUserActivity extends AppCompatActivity {
public static final String EXTRA_ID = "com.example.citadelentrance.EXTRA_ID";
public static final String EXTRA_NAME = "com.example.citadelentrance.EXTRA_NAME";
public static final String EXTRA_FAMILY = "com.example.citadelentrance.EXTRA_FAMILY";
public static final String EXTRA_LICENSE_PLATE = "com.example.citadelentrance.EXTRA_LICENSE_PLATE";
public static final String EXTRA_DOCUMENT = "com.example.citadelentrance.EXTRA_DOCUMENT";
public static final String EXTRA_ADDRESS = "com.example.citadelentrance.EXTRA_ADDRESS";
public static final String EXTRA_TIME = "com.example.citadelentrance.EXTRA_TIME";
private EditText editTextName, editTextFamily,
editTextLicensePlate, editTextDocument, editTextAddress;
private TextView textViewTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
editTextName = findViewById(R.id.edit_text_name);
editTextFamily = findViewById(R.id.edit_text_family);
editTextLicensePlate = findViewById(R.id.edit_text_license_plate);
editTextDocument = findViewById(R.id.edit_text_document);
editTextAddress = findViewById(R.id.edit_text_address);
textViewTime = findViewById(R.id.text_view_time);
Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.drawable.ic_close);
Intent intent = new Intent();
if (intent.hasExtra(EXTRA_ID)) {
setTitle("Edit User");
editTextName.setText(intent.getStringExtra(EXTRA_NAME));
editTextFamily.setText(intent.getStringExtra(EXTRA_FAMILY));
editTextLicensePlate.setText(intent.getStringExtra(EXTRA_LICENSE_PLATE));
editTextDocument.setText(intent.getStringExtra(EXTRA_DOCUMENT));
editTextAddress.setText(intent.getStringExtra(EXTRA_ADDRESS));
textViewTime.setText(intent.getStringExtra(EXTRA_TIME));
} else {
setTitle("Add User");
textViewTime.setText(LocalDateTimeConverter.toDateString(LocalDateTime.now()));
Log.println(Log.ASSERT, "CS50x", "Add user activity");
}
}
private void saveUser() {
String name = getTextFromEdit(editTextName);
String family = getTextFromEdit(editTextFamily);
String licensePlate = getTextFromEdit(editTextLicensePlate);
String document = getTextFromEdit(editTextDocument);
String address = getTextFromEdit(editTextAddress);
String time = textViewTime.toString();
if (name.isEmpty() || family.isEmpty() || licensePlate.isEmpty() ||
document.isEmpty() || address.isEmpty()) {
Toast.makeText(this, "Please don't leave empty fields", Toast.LENGTH_SHORT).show();
return;
}
Intent data = new Intent();
data.putExtra(EXTRA_NAME, name);
data.putExtra(EXTRA_FAMILY, family);
data.putExtra(EXTRA_LICENSE_PLATE, licensePlate);
data.putExtra(EXTRA_DOCUMENT, document);
data.putExtra(EXTRA_ADDRESS, address);
data.putExtra(EXTRA_TIME, time);
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if (id != -1) {
data.putExtra(EXTRA_ID, id);
Log.println(Log.ASSERT, "CS50x", "id != -1");
}
setResult(RESULT_OK, data);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_save_user, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.save_user) {
saveUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private String getTextFromEdit(EditText editText) {
return editText.getText().toString().trim();
}
}
#arget's comment is correct - you need to change this:
Intent intent = new Intent();
to this
Intent intent = getIntent();
or use it directly instead.
Another thing, why don't you make the user class implement Parcelable, and pass the user around instead of all its properties? It would make the code a cleaner.
package com.example.ishan.complainbox;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageButton;
import android.view.View;
import android.widget.EditText;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v7.widget.AppCompatImageView;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.graphics.drawable.BitmapDrawable;
public class Crime extends MainActivity implements
View.OnClickListener,LocationListener {
GoogleMap googleMap;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView imgView,ivImage;
private String userChosenTask;
EditText street, city, pincode, detail;
Button btnsave;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
setContentView(R.layout.activity_crime);
// Get References of Views
street = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pincode = (EditText) findViewById(R.id.pin);
detail = (EditText) findViewById(R.id.detail);
imgView = (ImageView)findViewById(R.id.imgView);
btnsave = (Button) findViewById(R.id.save);
btnSelect = (Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String strt = street.getText().toString();
String cty = city.getText().toString();
String pin = pincode.getText().toString();
String det = detail.getText().toString();
Bitmap bitmap =
((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageInByte = baos.toByteArray();
btnsave = (Button) findViewById(R.id.save);
selectImage();
dbHandler.insertEntry(strt, cty, pin, det,imageInByte);
Toast.makeText(getApplicationContext(), "Complaint
Successfully Filed ", Toast.LENGTH_LONG).show();
}
});
ivImage = (ImageView) findViewById(R.id.img);
}
}
#Override
public void onRequestPermissionsResult ( int requestCode, String[]
permissions,
int[] grantResults){
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (userChosenTask.equals("Take Photo"))
cameraIntent();
else if (userChosenTask.equals("Choose from Library"))
galleryIntent();
} else
break;
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Crime.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=userChosenTask.checkPermission(Crime.this);
if (items[item].equals("Take Photo"))
{
userChosenTask ="Take Photo";
if(result)
cameraIntent();
}
else if (items[item].equals("Choose from Library"))
{
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
}
else if (items[item].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new
File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()
+ ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap
(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
This is one activity class of my android project and this activity depends on another utility class....which is mentioned below:
The statement Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); shows an error in "imageView" and the statement boolean result=userChosenTask.checkPermission(Crime.this); shows an error on "checkPermission"...but I don't understand why...because checkPermission is already defined in the utility class....
package com.example.ishan.complainbox;
/**
* Created by ishan on 11/04/2017.
*/
import android.os.Build;
import android.content.Context;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.DialogInterface;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED)
{
if
(ActivityCompat.shouldShowRequestPermissionRationale((MainActivity) context,
Manifest.permission.READ_EXTERNAL_STORAGE))
{
AlertDialog.Builder alertBuilder = new
AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is
necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new
DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((MainActivity)
context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else
{
ActivityCompat.requestPermissions((MainActivity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else
{
return true;
}
}
}
In your manifests.xml, you need to include permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am getting network error while calling wcf service in android.Actually in this i am using zxing library for barcode scan,and i want that the email what i am getting after scan should go to the service and give me the details of that email id..
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.HashMap;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn;
public TextView formatTxt, contentTxt,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanBtn = (Button) findViewById(R.id.scan_button);
formatTxt = (TextView) findViewById(R.id.scan_format);
contentTxt = (TextView) findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("EMAIL: " + scanContent);
email= contentTxt;
String url = "url"
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("email", scanContent);
AQuery mAQuery = new AQuery(MainActivity.this);
mAQuery.ajax(url, map, String.class, new AjaxCallback<String>() {
#Override
public void callback(String url, String data, AjaxStatus status) {
super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");
}
if (status.getCode() == -101 || null == data) {
//Internet connection error
return;
}
if (null != data && status.getCode() != -101) {
// data : Your response from server
}
}
});
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
I am using com.paypal.android.MEP.PayPalActivity library. I want to edit layout but I can't access it. How can I edit default layout of this library. I am trying to transfer money from an account to another account. It works correctly but user interface seems bad
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalReceiverDetails;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import project.com.holobech.MainActivity;
import project.com.holobech.R;
import project.com.holobech.app.AppConfig;
import project.com.holobech.app.AppController;
import project.com.holobech.model.UserList;
import project.com.holobech.util.PaypalUtil;
public class PaypalActivity extends ActionBarActivity {
// LogCat tag
private static final String TAG = PaypalActivity.class.getSimpleName();
public final int PAYPAL_RESPONSE = 100;
TextView txtOdullendirEmail;
TextView txtOdullendirAmount;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paypal);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
txtOdullendirEmail = (TextView) findViewById(R.id.txt_odullendir_email);
txtOdullendirEmail.setText("Ödüllendirilecek E-Posta : " + ProfileFragment.email);
txtOdullendirAmount= (TextView) findViewById(R.id.txt_odullendir_amount);
txtOdullendirAmount.setText("Ödüllendirilecek Miktar : 1$");
Button paypal_button = (Button) findViewById(R.id.paypal_button);
initLibrary();
paypal_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// pay integration here
PayPalButtonClick(ProfileFragment.email, "1");
}
});
}
public void initLibrary() {
PayPal pp = PayPal.getInstance();
if (pp == null) {
pp = PayPal.initWithAppID(this, PaypalUtil.paypal_liv_id,
PayPal.ENV_LIVE);
}
}
public void PayPalButtonClick(String primary_id, String primary_amount) {
// Create a basic PayPal payment
// PayPalPayment newPayment = new PayPalPayment();
// newPayment.setSubtotal(new BigDecimal("1.0"));
// newPayment.setCurrencyType("USD");
// newPayment.setRecipient("npavankumar34#gmail.com");
// newPayment.setMerchantName("My Company");
// Log.d("pavan", "calling intent");
// if( PayPal.getInstance()!=null){
// Log.d("pavan", "in if");
// Intent paypalIntent = PayPal.getInstance().checkout(newPayment,
// this);
// startActivityForResult(paypalIntent, 1);
//
// config reciever1
PayPalReceiverDetails receiver0;
receiver0 = new PayPalReceiverDetails();
receiver0.setRecipient(primary_id);
receiver0.setSubtotal(new BigDecimal(primary_amount));
// adding payment type
PayPalAdvancedPayment advPayment = new PayPalAdvancedPayment();
advPayment.setCurrencyType("TRY");
advPayment.getReceivers().add(receiver0);
Intent paypalIntent = PayPal.getInstance().checkout(advPayment, this);
this.startActivityForResult(paypalIntent, PAYPAL_RESPONSE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("pavan", "response");
if (requestCode == PAYPAL_RESPONSE) {
switch(resultCode) {
case Activity.RESULT_OK:
//The payment succeeded
String payKey =
data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
Log.d("pavan", "success "+payKey);
Toast.makeText(getApplicationContext(), "Payment done succesfully ", Toast.LENGTH_LONG).show();
setMoneyTransfer();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getApplicationContext(), "Payment Canceled , Try again ", Toast.LENGTH_LONG).show();
break;
case PayPalActivity.RESULT_FAILURE:
Toast.makeText(getApplicationContext(), "Payment failed , Try again ", Toast.LENGTH_LONG).show();
break;
}
}
}
private void setMoneyTransfer() {
// istek iptali için tag
String tag_string_req = "req_money_transfer";
pDialog.setMessage("Lütfen bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_CONTEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Para transferi yanıtı : " + response.toString());
hideDialog();
try{
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// json hatası kontrolü
if (!error) {
// başarılı
Log.d("Response", response.toString());
} else {
// başarısız
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON hatası
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Para transferi Hatası: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// login urle bilgileri gönder
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "money_transfer");
params.put("sender", MainActivity.PROFILE_EMAIL);
params.put("receiver", ProfileFragment.email);
return params;
}
};
// istek kuyruğuna isteği ekle
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
This checkout page layout is default and there is no way you can edit the layout.
Below I've listed my activity code, call out to the web service, and the json parsing class I created to parse the web service results. I'm trying to pass a user object back to the activity to determine what they can/can't do, however, I'm not getting past the "after execute" log statement. onRequestFinished never gets called which is where I would have expected it to end up. Any help would be greatly appreciated as there doesn't seem to be much activity with DataDroid...
LoginActivity.java
package com.motosho.ui;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener;
import com.motosho.R;
import com.motosho.data.model.User;
import com.motosho.data.requestmanager.RequestFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
public final class LoginActivity extends DataDroidActivity implements RequestListener,
OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bindViews();
}
protected void onResume() {
super.onResume();
for(int i=0; i < mRequestList.size(); i++) {
Request request = mRequestList.get(i);
if(mRequestManager.isRequestInProgress(request)) {
mRequestManager.addRequestListener(this, request);
setProgressBarIndeterminateVisibility(true);
} else {
mRequestManager.callListenerWithCachedData(this, request);
i--;
mRequestList.remove(request);
}
}
}
protected void onPause() {
super.onPause();
if(!mRequestList.isEmpty()) {
mRequestManager.removeRequestListener(this);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
private void bindViews() {
((Button) findViewById(R.id.sign_in_button)).setOnClickListener(this);
}
private void callLoginWS(String username, String pin, String eventId) {
Log.i("LOGIN", "in callLoginWS - username=" + username + ", pin=" + pin + ", eventid=" + eventId);
setProgressBarIndeterminateVisibility(true);
Request request = RequestFactory.getLoginRequest(username, pin, eventId);
mRequestManager.execute(request, this);
Log.i("LOGIN", "after execute");
mRequestList.add(request);
}
public void onClick(View view) {
switch(view.getId()) {
case R.id.sign_in_button:
EditText emailText = (EditText) findViewById(R.id.email);
EditText pinText = (EditText) findViewById(R.id.pin);
Log.i("LOGIN","set email and pin text");
callLoginWS(emailText.getText().toString(), pinText.getText().toString(),"9");
break;
}
}
#Override
public void onRequestFinished(Request request, Bundle resultData) {
Log.i("LOGIN", "inside onRequestFinished");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
Log.i("LOGIN", "request found");
mRequestList.remove(request);
Toast toast = Toast.makeText(this, "request finished", Toast.LENGTH_SHORT);
toast.show();
User user = resultData.getParcelable("user");
if(user != null) {
startActivity(new Intent(this, MainActivity.class).putExtras(resultData));
}
}
}
#Override
public void onRequestConnectionError(Request request, int statusCode) {
Log.i("LOGIN", "onRequestConnectionError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
//show error
Toast toast = Toast.makeText(this, "connection error", Toast.LENGTH_SHORT);
toast.show();
mRequestList.remove(request);
}
}
#Override
public void onRequestDataError(Request request) {
Log.i("LOGIN", "onRequestDataError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
mRequestList.remove(request);
//show error
Toast toast = Toast.makeText(this, "data error", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRequestCustomError(Request request, Bundle resultData) {
// Never called
}
public void connectionErrorDialogRetry(Request request) {
Log.i("LOGIN", "connectionErrorDialogRetry");
String username = request.getString("username");
String pin = request.getString("pin");
String eventId = request.getString("eventid");
callLoginWS(username,pin,eventId);
}
}
LoginOperation.java
package com.motosho.data.operation;
import java.util.HashMap;
import android.content.Context;
import android.os.Bundle;
import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.network.NetworkConnection;
import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult;
import com.foxykeep.datadroid.network.NetworkConnection.Method;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.motosho.config.WSConfig;
import com.motosho.data.factory.LoginJsonFactory;
public final class LoginOperation implements Operation {
#Override
public Bundle execute(Context context, Request request)
throws ConnectionException, DataException, CustomRequestException {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", request.getString("username"));
params.put("pin", request.getString("pin"));
params.put("eventid", request.getString("eventid"));
NetworkConnection networkConnection = new NetworkConnection(context, WSConfig.WS_LOGIN_URL);
networkConnection.setMethod(Method.POST);
networkConnection.setParameters(params);
ConnectionResult result = networkConnection.execute();
return LoginJsonFactory.parseResult(result.body);
}
}
LoginJsonFactory.java
package com.motosho.data.factory;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import com.foxykeep.datadroid.exception.DataException;
import com.motosho.config.JSONTag;
import com.motosho.data.model.User;
public final class LoginJsonFactory {
private static final String TAG = LoginJsonFactory.class.getName();
private LoginJsonFactory() { }
#SuppressWarnings("null")
public static Bundle parseResult(String wsResponse) throws DataException {
User user = new User();
try {
JSONObject parser = new JSONObject(wsResponse);
JSONObject jsonRoot = parser.getJSONObject(JSONTag.USER_ELEM);
user.firstName = jsonRoot.getString(JSONTag.USER_ELEM_FIRST_NAME);
user.lastName = jsonRoot.getString(JSONTag.USER_ELEM_LAST_NAME);
user.phoneNumber = jsonRoot.getString(JSONTag.USER_ELEM_PHONE_NUMBER);
user.role = jsonRoot.getString(JSONTag.USER_ELEM_ROLE);
JSONArray jsonPositionsArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_POSITIONS);
int size = jsonPositionsArray.length();
List<String> tempPositionsArray = null;
for (int i=0; i < size; i++) {
tempPositionsArray.add(jsonPositionsArray.getString(i));
}
user.positions = tempPositionsArray;
JSONArray jsonCapabilitiesArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_CAPABILITIES);
size = jsonCapabilitiesArray.length();
List<String> tempCapabilitiesArray = null;
for(int i=0; i < size; i++) {
tempCapabilitiesArray.add(jsonCapabilitiesArray.getString(i));
}
user.capabilities = tempCapabilitiesArray;
} catch (JSONException e) {
Log.e(TAG, "JSONException", e);
throw new DataException(e);
}
Bundle bundle = new Bundle();
bundle.putParcelable("user", user);
return bundle;
}
}