Image is not generating/uploading in the server - java

I am developing an android app in which i want to save images on server(free server 000webhost).To do this i am encoding my image into string using base64. And sending this string with the POST method using volley.
But the image is not generating on the server side. Can anyone tell me what's wrong?
upload.php
<?php
$servername = "localhost";
$database = "id8258200_image";
$username = "id8258200_qmine1";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
if(isset($_POST["image"])){
$encoded_string = $_POST["image"];
$image_name="img";
$decoded_string = base64_decode($encoded_string);
$path = "image/$image_name.jpeg";
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
echo "success";
}
else {
echo "error";
}
?>
Mainactivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL = "https://qmine.000webhostapp.com/question/upload.php";
private int PICK_IMAGE_REQUEST = 1;
private Button buttonChoose;
private Button buttonUpload;
private Button buttonView;
private ImageView imageView;
private Bitmap bitmap;
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonView = (Button) findViewById(R.id.buttonViewImage);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Log.d("tr", "qwerty" + encodedImage);
return encodedImage;
}
private void uploadImage() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "errorrrr", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> Params = new HashMap<String, String>();
String img = getStringImage(bitmap);
Log.d("qw", "aasas" + img);
Params.put("image", img);
return Params;
}
};
queue.add(request);
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
if (v == buttonView) {
viewImage();
}
}
private void viewImage() {
// startActivity(new Intent(this, ImageListView.class));
}
}

Code looks fine to me. Seems like a permission issue. Add these lines to top of your PHP script.
<?php
ini_set('display_errors', 1); // telling PHP to explicitly print all errors
error_reporting(E_ALL); // Show all notices, warnings and fatal errors
Second thing to check if the folder is having enough permission to write a file. Give write permission if not there and see if the code works.
Hope this helps. Happy coding!

Related

I cannot get my imageview uploaded from gallery to stay once the application closes

I cannot get my imageview uploaded from gallery to stay once the application closes. I already looked at other questions like this one but it is not working for me. I tried shared pref but it is not working. I might be doing it wrong. Could someone look at my code? I want the imageview uploaded from gallery to stay in the imageview even after the application is closed. I want it to only changed when a new picture is uploaded from the gallery.I have already tried shared preference, but I am pretty sure I did it wrong. It is in the code that I have below. I also used base64.
need help..thanks in advance
here is my code :
package com.example.upload;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import com.squareup.picasso.Picasso;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
public class MainActivity extends Activity {
String TAG = "Hello";
private Button mButtonChooseImage;
private ImageView mImageView;
private Uri mImageUri;
private static final int PICK_IMAGE_REQUEST = 1;
private Bitmap bitmap;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.image_view);
mButtonChooseImage = (Button) findViewById(R.id.button_choose_image);
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
Intent intent = getIntent();
if (getIntent().getExtras() != null) {
// for get data from intent
bitmap = intent.getParcelableExtra("PRODUCT_PHOTO");
// for set this picture to imageview
mImageView.setImageBitmap(bitmap);
sharedPreferences();
} else {
retrivesharedPreferences();
}
}
private void sharedPreferences() {
SharedPreferences shared = getSharedPreferences("App_settings", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("PRODUCT_PHOTO", encodeTobase64(bitmap));
editor.commit();
}
private void retrivesharedPreferences() {
SharedPreferences shared = getSharedPreferences("MyApp_Settings", MODE_PRIVATE);
String photo = shared.getString("PRODUCT_PHOTO", "photo");
assert photo != null;
if (!photo.equals("photo")) {
byte[] b = Base64.decode(photo, Base64.DEFAULT);
InputStream is = new ByteArrayInputStream(b);
bitmap = BitmapFactory.decodeStream(is);
mImageView.setImageBitmap(bitmap);
}
}
public static String encodeTobase64(Bitmap image) {
Bitmap bitmap_image = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap_image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
selectedImagePath = getPath(mImageUri);
}
}
private String getPath(Uri mImageUri) {
if (mImageUri == null) {
}
return null;
}
#Override
protected void onResume() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", MODE_PRIVATE);
selectedImagePath = sp.getString("ImagePath", "");
Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
mImageView.setImageBitmap(myBitmap);
Picasso.get().load(mImageUri).into(mImageView);
super.onResume();
}
public void ff(View view) {
Intent i = new Intent(this, Main2Activity.class);
startActivity(i);
}
}

Passing a Camera Intent to Android Input Stream

I am working on an Android Activity where I want to pass a Camera Intent to an Input Stream, in order to process it further through the Activity;
The aim is that the user can make a Camera picture and that the picture is then processed as an Input Stream and passed to an API.
I am not sure if that´s the best way to "convert" a Camera Image into an Input Stream, therefore I am open to any suggestion and hint; this is my code so far:
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.AnnotateImageRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse;
import com.google.api.services.vision.v1.model.FaceAnnotation;
import com.google.api.services.vision.v1.model.Feature;
import com.google.api.services.vision.v1.model.Image;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import static java.nio.channels.Pipe.open;
public class VisionAPIActivity extends AppCompatActivity {
ImageView imgFavorite;
public final static int CAMERA_REQUEST = 1888;
public void TakePicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_REQUEST);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TakePicture();
setContentView(R.layout.activity_vision_api);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Vision.Builder visionBuilder = new Vision.Builder(
new NetHttpTransport(),
new AndroidJsonFactory(),
null);
visionBuilder.setVisionRequestInitializer(
new VisionRequestInitializer("AIzaSyCnPwvnEQakkUXpkFaj2TcwJs_E3DPqjm0"));
final Vision vision = visionBuilder.build();
Log.i("log-", "passed VisionBuilder Initialisation");
// Create new thread
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// Convert photo to byte array
final InputStream inputStream =
getResources().openRawResource(R.raw.skate);
byte[] photoData = new byte[0];
Log.i("log-", "Content of Photo Data" + photoData);
try {
photoData = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Image inputImage = new Image();
inputImage.encodeContent(photoData);
Feature desiredFeature = new Feature();
desiredFeature.setType("FACE_DETECTION");
AnnotateImageRequest request = new AnnotateImageRequest();
request.setImage(inputImage);
Log.i("log-", "Content of inputImage" + inputImage);
request.setFeatures(Arrays.asList(desiredFeature));
BatchAnnotateImagesRequest batchRequest =
new BatchAnnotateImagesRequest();
batchRequest.setRequests(Arrays.asList(request));
BatchAnnotateImagesResponse batchResponse =
null;
try {
batchResponse = vision.images().annotate(batchRequest).execute();
List<FaceAnnotation> faces = batchResponse.getResponses()
.get(0).getFaceAnnotations();
// Count faces
int numberOfFaces = faces.size();
Log.i("log-", "number Of Faces" + numberOfFaces);
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageView mImageView;
mImageView = findViewById(R.id.imageViewId);
InputStream is = getResources().openRawResource(R.raw.skate);
mImageView.setImageBitmap(BitmapFactory.decodeStream(is));
}
});
// Get joy likelihood for each face
String likelihoods = "";
for (int i = 0; i < numberOfFaces; i++) {
likelihoods += "\n It is " +
faces.get(i).getJoyLikelihood() +
" that face " + i + " is happy";
}
// Concatenate everything
final String message =
"This photo has " + numberOfFaces + " faces" + likelihoods;
// Display toast on UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}
});
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void imageClick(View view){
imgFavorite = findViewById(R.id.imageView1);
open();
}
public void open(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //IMAGE CAPTURE CODE
startActivityForResult(intent, 0);
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap=(Bitmap)data.getExtras().get("data");
imgFavorite.setImageBitmap(bitmap);
}
You can trigger a Camera intent and tell it where to save your picture, after that you can open the file as an InputStream. To do so you need to pass the file Uri like this:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
If you don't pass the File Uri you'll receive a thumbnail not the full size photo. For more details take a look a the docs:
https://developer.android.com/training/camera/photobasics#TaskPath

logcat file showing errors

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" />

Is this is a correct way to call wcf service in android?

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();
}
}
}

How to edit paypal activities layout

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.

Categories

Resources