I've written an application which should take picture and record video and then show it on the screen. When trying it on phone the camera won't work but works in emulator.
When executing the app this is what exactly happens:
Every time I clicked on the button to open the camera, the app stopped and the error it display is Appname has stopped, Open app again
When I clicked on Open app again it return to normal state
I have granted the camera permission in my program
below is my code:
public class EventActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
public static final String KEY_MENU_TYPE = "menutype";
//public static final String KEY_PREF_USER_DETAILS = "prefUserDetails";
private static final String TAG = EventActivity.class.getSimpleName();
private static final String SERVER_IMAGE_PATH = "http://edo.com/imageupload/";
private static final String SERVER_PATH = "http://edo.com/";
String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private EditText event, eventDescription, name;
private TextView attachmentStatus;
private static final int TAKE_PICTURE = 1;
private static final int PERMISSION_ALL = 3;
private Uri capturedImageUri;
private Uri videoUri;
private String mediaFile;
private String videoFile;
private static final int MY_SOCKET_TIMEOUT_MS = 5000;
private String[] serverData;
private static final int REQUEST_VIDEO_CAPTURE = 300;
private boolean isImage;
private String locationResult;
String menutype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
Intent intent = getIntent();
/* ActionBar mBar = getSupportActionBar();
if(mBar != null){
mBar.setDisplayHomeAsUpEnabled(true);
}*/
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = createLocationRequest();
Button photoVideoButton = (Button)findViewById(R.id.take_image_video);
photoVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showOptionDialog();
}
});
attachmentStatus = (TextView)findViewById(R.id.file_status);
event = (EditText)findViewById(R.id.enter_event);
eventDescription =(EditText)findViewById(R.id.enter_event_description);
name = (EditText)findViewById(R.id.name);
Button cancelUploadButton = (Button) findViewById(R.id.cancel_upload);
assert cancelUploadButton != null;
cancelUploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resetViewControls();
}
});
Button sendToServerButton = (Button) findViewById(R.id.send_to_server);
assert sendToServerButton != null;
sendToServerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String eventValue = event.getText().toString().trim();
String eventDescriptionValue = eventDescription.getText().toString();
String nameValue = name.getText().toString();
String locationValue = "";
if(TextUtils.isEmpty(eventValue) || TextUtils.isEmpty(eventDescriptionValue) || TextUtils.isEmpty(nameValue)){
Toast.makeText(EventActivity.this, getString(R.string.send_to_server_error), Toast.LENGTH_LONG).show();
return;
}
if(locationResult == null || locationResult.equals("")){
locationValue = "";
}else{
locationValue = locationResult;
}
if(TextUtils.isEmpty(mediaFile) && TextUtils.isEmpty(videoFile)){
Toast.makeText(EventActivity.this, "Please attach a photo or video", Toast.LENGTH_LONG).show();
return;
}
if(!TextUtils.isEmpty(mediaFile) && isImage){
// send the information to remote server
Bitmap storeBitmap = BitmapFactory.decodeFile(mediaFile);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(storeBitmap, 640, 420, true);
String imageBasedString = convertBitmapToBaseImageString(resizedBitmap);
serverData = new String[]{eventValue, eventDescriptionValue, nameValue, imageBasedString, locationValue};
sendCapturedImageToServer(serverData);
//move stored video to a new folder
String photoPath = getMovedFilePath(mediaFile, eventValue);
moveFileToNewDestination(mediaFile, photoPath);
}else if(!TextUtils.isEmpty(mediaFile) && !isImage){
//Store the video to your server
uploadVideoToServer(videoFile, eventValue, eventDescriptionValue, nameValue, locationValue);
//move stored video to a new folder
String photoPath = getMovedFilePath(videoFile, eventValue);
moveFileToNewDestination(videoFile, photoPath);
}else{
// Image or video is missing. Show message to user
Toast.makeText(EventActivity.this, getString(R.string.upload_image_or_video), Toast.LENGTH_LONG).show();
}
}
});
this.menutype = intent.getStringExtra(KEY_MENU_TYPE);
if (this.menutype == null) {
this.menutype = "";
}
}
public void goBack(View view) {
Intent intent;
if (this.menutype.equals("PRE")) {
intent = new Intent(this, PreElectionMenuActivity.class);
} else if (this.menutype.equals("ACC")) {
intent = new Intent(this, AccreditationMenuActivity.class);
} else if (this.menutype.equals("ELE")) {
intent = new Intent(this, VotingMenuActivity.class);
} else if (this.menutype.equals("INC")) {
intent = new Intent(this, IncidentMenuActivity.class);
} else {
intent = new Intent(this, HomeActivity.class);
}
startActivity(intent);
}
private String getMovedFilePath(String filePath, String eventName){
int indexPosition = filePath.lastIndexOf(".");
String fileExtension = filePath.substring(indexPosition, filePath.length());
String newFilename = eventName + fileExtension;
return getFileDestinationPath(newFilename);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == TAKE_PICTURE) {
capturedImageUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = "";
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
Log.d(TAG, "Capture image path" + mediaFile);
attachmentStatus.setText("Image file has been attached");
isImage = true;
}
}
if (requestCode == REQUEST_VIDEO_CAPTURE) {
videoUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else{
videoFile = getRealPathFromURIPath(videoUri, EventActivity.this);
Log.d(TAG, "Captured video path " + videoUri);
Log.d(TAG, "New path " + videoFile);
attachmentStatus.setText("Video file has been attached");
isImage = false;
}
}
}
}
private void resetViewControls(){
event.setText("");
eventDescription.setText("");
name.setText("");
attachmentStatus.setText(R.string.attached_file);
}
#Override
protected void onResume() {
super.onResume();
if(capturedImageUri != null){
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
}
}
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
private String convertBitmapToBaseImageString(Bitmap bitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
return Base64.encodeToString(byte_arr, 0);
}
private void sendCapturedImageToServer(String[] photoDetails){
Map<String, String> params = new HashMap<String,String>();
params.put("EVENT", photoDetails[0]);
params.put("EVENT_DESCRIPTION", photoDetails[1]);
params.put("NAME", photoDetails[2]);
params.put("CAPTURE_IMAGE", photoDetails[3]);
params.put("EVENT_LOCATION", photoDetails[4]);
GsonRequest<ServerObject> serverRequest = new GsonRequest<ServerObject>(
Request.Method.POST,
SERVER_IMAGE_PATH,
ServerObject.class,
params,
createRequestSuccessListener(),
createRequestErrorListener());
serverRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(EventActivity.this).addToRequestQueue(serverRequest);
}
private Response.Listener<ServerObject> createRequestSuccessListener() {
return new Response.Listener<ServerObject>() {
#Override
public void onResponse(ServerObject response) {
try {
Log.d(TAG, "Json Response " + response.getSuccess());
if(!TextUtils.isEmpty(response.getSuccess()) && response.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
};
};
}
private Response.ErrorListener createRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
public static void getAddressFromLocation(final double lat, final double lon, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(lat, lon, 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality() + ", " + address.getCountryName() ;
Log.d(TAG, "The converted Address " + result);
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to GeoCoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
#SuppressLint("HandlerLeak")
private class GeoCoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationResult = bundle.getString("address");
Log.d(TAG, "Location Result " + locationResult);
break;
default:
locationResult = null;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.d(TAG, "Connection method has been called");
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
else{
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
getAddressFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), EventActivity.this, new GeoCoderHandler());
}
}
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_ALL: {
// If request is cancelled, the result arrays are empty.
if(grantResults[0] == PackageManager.PERMISSION_DENIED){
Toast.makeText(EventActivity.this, "Sorry!!!, you can't use this app without granting this permission", Toast.LENGTH_LONG).show();
finish();
}
if (grantResults[1] == PackageManager.PERMISSION_DENIED || grantResults[2] == PackageManager.PERMISSION_DENIED) {
// permission was denied, show alert to explain permission
showPermissionAlert();
}else{
//permission is granted. Get current location values
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
}
}
}
}
private void showPermissionAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permission_request_title);
builder.setMessage(R.string.app_permission_notice);
builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(EventActivity.this, R.string.permission_refused, Toast.LENGTH_LONG).show();
}
});
builder.show();
}
protected LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private boolean isLocationEnabled(){
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
return false;
}
return true;
}
private void showLocationAlert(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_enable));
dialog.setPositiveButton(getResources().getString(R.string.network_location), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
EventActivity.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private void moveFileToNewDestination(String fromPath, String toPath){
File fromFile = new File(fromPath);
File toFile = new File(toPath);
if(!toFile.exists()){
try {
toFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fromStream = null;
FileOutputStream toStream = null;
try {
fromStream = new FileInputStream(fromFile);
toStream = new FileOutputStream(toFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] sourceByte = new byte[1024];
int index;
try {
while((index = fromStream.read(sourceByte)) > 0){
if (toStream != null) {
toStream.write(sourceByte, 0, index);
}
}
Log.d(TAG, "Video successfully moved to a new location");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getFileDestinationPath(String filename){
String filePathEnvironment = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
File directoryFolder = new File(filePathEnvironment + "/events/");
if(!directoryFolder.exists()){
directoryFolder.mkdir();
}
Log.d(TAG, "Full path " + filePathEnvironment + "/events/" + filename);
return filePathEnvironment + "/events/" + filename;
}
private void uploadVideoToServer(String pathToVideoFile, String eventName, String eventDescription, String eventCoverage, String eventLocation){
File videoFile = new File(pathToVideoFile);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
RequestBody event = RequestBody.create(MediaType.parse("text/plain"), eventName);
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), eventDescription);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), eventCoverage);
RequestBody location = RequestBody.create(MediaType.parse("text/plain"), eventLocation);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create())
.build();
VideoInterface vInterface = retrofit.create(VideoInterface.class);
Call<ResultObject> serverCom = vInterface.uploadVideoToServer(vFile, event, description, name, location);
serverCom.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
ResultObject result = response.body();
if(!TextUtils.isEmpty(result.getSuccess()) && result.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
Log.d(TAG, "Error message " + t.getMessage());
}
});
}
private void showOptionDialog(){
final Dialog dialog = new Dialog(EventActivity.this);
dialog.setTitle("SELECT ACTION TO COMPLETE");
dialog.setContentView(R.layout.image_video_layout);
final TextView takePhoto = (TextView)dialog.findViewById(R.id.take_photo);
final TextView recordVideo = (TextView)dialog.findViewById(R.id.record_video);
dialog.show();
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Take a picture");
if(isLocationEnabled()){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}else{
showLocationAlert();
}
dialog.dismiss();
}
});
recordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Record a video");
Intent videoCaptureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(videoCaptureIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(videoCaptureIntent, REQUEST_VIDEO_CAPTURE);
}
dialog.dismiss();
}
});
}
private boolean gps_enabled;
private boolean network_enabled;
Related
I want to show my image in imageview after click but i don't know why this error occur and i searched a lot on this but i could no find solution of this problem and i tried to implement code after see solution but it doesn't work,so i m confused what's going wrong.This is my code:
package kmsg.com.onetouch.activity;
public class UploadDocumentActivity extends AppCompatActivity {
JSONParser parser;
Bitmap photo;
ImageView mImgDocument;
Button mBtnBill,mBtnPres,mBtnGetFile,mBtnUpload;
EditText mEtBillDate,mEtbillValue,mEtStoreRefID,mEtDoctorID;
LinearLayout mBillLinear,mPresLinear;
String mBillDate,mBillValue,mStoreRefID,mDoctorID;
boolean flag= true;
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_document);
parser = new JSONParser(this);
init();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
private void init() {
mImgDocument=(ImageView)findViewById(R.id.imgDocument);
mBtnBill=(Button)findViewById(R.id.btnBill);
mBtnPres=(Button)findViewById(R.id.btnPres);
mBtnGetFile=(Button)findViewById(R.id.btnGetFile);
mBtnUpload=(Button)findViewById(R.id.btnUpload);
mEtBillDate=(EditText)findViewById(R.id.et_billDate);
mEtbillValue=(EditText)findViewById(R.id.et_billValue);
mEtStoreRefID=(EditText)findViewById(R.id.et_refID);
mEtDoctorID=(EditText)findViewById(R.id.et_doctorID);
mBillLinear=(LinearLayout)findViewById(R.id.bill_linear);
mPresLinear=(LinearLayout)findViewById(R.id.prescription_linear);
}
public void getBill(View view) {
flag= true;
mPresLinear.setVisibility(View.GONE);
mBillLinear.setVisibility(View.VISIBLE);
}
public void getPrescription(View view) {
flag=false;
mBillLinear.setVisibility(View.GONE);
mPresLinear.setVisibility(View.VISIBLE);
}
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureNm = getPictureName();
imageFile = new File(pictureDirectory , pictureNm);
Uri pictureUri = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
/* public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CAMERA_REQUEST);
}
}
*/
private String getPictureName(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "paymentProof" + timestamp + ".jpg";
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_CANCELED){
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImgDocument.setImageBitmap(photo);
}
}
}
private boolean validateFormForBill() {
mBillDate = mEtBillDate.getText().toString().trim();
mBillValue = mEtbillValue.getText().toString().trim();
mStoreRefID = mEtStoreRefID.getText().toString().trim();
mEtBillDate.setError(null);
mEtbillValue.setError(null);
mEtStoreRefID.setError(null);
if (TextUtils.isEmpty(mBillDate.trim())) {
mEtBillDate.setError("Bill Date cannot be blank");
return false;
}
if (TextUtils.isEmpty(mBillValue.trim())) {
mEtbillValue.setError("Bill Value cannot be blank");
return false;
}
if (TextUtils.isEmpty(mStoreRefID.trim())) {
mEtStoreRefID.setError("Ref ID cannot be blank");
return false;
}
return true;
}
private boolean validateFormForPres() {
mDoctorID = mEtDoctorID.getText().toString().trim();
mEtDoctorID.setError(null);
if (TextUtils.isEmpty(mDoctorID.trim())) {
mEtDoctorID.setError("Doctor ID cannot be blank");
return false;
}
return true;
}
public void uploadDocument(View view) {
if (UtilityServices.checkInternetConnection(UploadDocumentActivity.this)) {
if (flag) {
if (UploadDocumentActivity.this.validateFormForBill()) {
new UploadBill().execute();
}
} else {
if (UploadDocumentActivity.this.validateFormForPres()) {
// new UploadPres().execute();
}
}
}else {
Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
}
}
private class UploadBill extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("billAmt", mBillValue));
partList.add(new StringPart("billDate", mBillDate));
partList.add(new StringPart("storeId", mStoreRefID));
System.out.println("Data"+mBillDate+mBillValue+mStoreRefID);
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")));
/* try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
String url = Constants.UPLOAD_BILL;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
private class UploadPres extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("storeId", mDoctorID));
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")+""));
try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String url = Constants.UPLOAD_PRESCRIPTION;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
}
This is my class and i am trying to capture an image on click a button and then save into directory after that show into imageview and then want to send to server,i hope you will help me as a best programmer.
this question may be a duplicate of this.
Basically, when you pass an OutPut file to the intent, you cannot read data from extra, you have to make sure that CameraApplication has access to your files. You are getting this exception, because CameraApplication cannot save the file on your directory, you need to add a file provider...
Please make your code is same as the base android documentation.
Try This
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
I am trying to take a screenshot of google maps android and pass the image to a new activity but I keep getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.snapshot(com.google.android.gms.maps.GoogleMap$SnapshotReadyCallback)' on a null object reference
at com.jjoey.transportr.activities.BookRideActivity.initViews(BookRideActivity.java:480)
at com.jjoey.transportr.activities.BookRideActivity.onCreate(BookRideActivity.java:101)
at android.app.Activity.performCreate(Activity.java:5990)
I have tried writing the code in onResume and onMapReady methods of activity but still error persists.
Here's my code for activity:
public class BookRideActivity extends FirebaseUtils implements OnMapReadyCallback {
private static final String TAG = BookRideActivity.class.getSimpleName();
private static final int LOC_REQ_CODE = 2035;
private Toolbar toolbar;
private ImageView backIV;
private SharedPrefsHelper prefsHelper;
private SupportMapFragment mapFragment;
private GoogleMap mGmap;
private LocationRequest locationRequest;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback callback;
private Location mCurrLocation;
private Marker marker;
private Bitmap locnImg;
private EditText startET, dropET, et_coupon, et_payment_options, et_rider;
private TextView estimatedPUTimeTV;
private Button bookNowBtn, cancelBtn;
private double lat = 0f, lon = 0f;
private String start = null, drop = null;
private boolean isValid = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_ride);
initViews();
start = getIntent().getStringExtra("start_addr");
drop = getIntent().getStringExtra("dest_addr");
if (start != null && drop != null) {
startET.setText(start);
dropET.setText(drop);
} else {
clearInputs();
}
setSupportActionBar(toolbar);
prefsHelper = new SharedPrefsHelper(this);
prefsHelper.setLoggedOut(false);
backIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(BookRideActivity.this, ClientHomeActivity.class));
}
});
et_coupon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Coupon Clicked");
showCouponDialog();
}
});
checkPerms();
handlePlacesInput();
}
private void checkPerms() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
} else {
startLocationListener();
}
}
private void reqPerms() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOC_REQ_CODE);
}
private void startLocationListener() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setInterval(UPDATE_INTERVAL);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest settingsRequest = builder.build();
SettingsClient client = LocationServices.getSettingsClient(this);
client.checkLocationSettings(settingsRequest);
drawLocationOnMap();
}
private void drawLocationOnMap() {
callback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrLocation = locationResult.getLastLocation();
if (marker != null && mCurrLocation != null) {
marker.remove();
lat = mCurrLocation.getLatitude();
lon = mCurrLocation.getLongitude();
}
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lon));
options.title("You");
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_marker));
marker = mGmap.addMarker(options);
mGmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 18.0f));
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.myLooper());
//mGmap.setMyLocationEnabled(true);
} else {
reqPerms();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case LOC_REQ_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationListener();
}
break;
}
}
private void handlePlacesInput() {
startET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startET.setText("");
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(BookRideActivity.this);
startActivityForResult(intent, START_PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
}
}
});
dropET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dropET.setText("");
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(BookRideActivity.this);
startActivityForResult(intent, DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case START_PLACE_AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String txt = place.getAddress().toString();
startET.setText(txt);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
Log.d(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
}
break;
case DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String txt = place.getAddress().toString();
dropET.setText(txt);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
Log.d(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
}
break;
}
}
private boolean validate() {
String startAddr = startET.getText().toString();
String destAddr = dropET.getText().toString();
if (TextUtils.isEmpty(startAddr) && TextUtils.isEmpty(destAddr)) {
isValid = false;
} else if (!TextUtils.isEmpty(startAddr) && !TextUtils.isEmpty(destAddr)) {
isValid = true;
}
return true;
}
private void clearInputs() {
startET.setText("");
dropET.setText("");
}
private void initViews() {
toolbar = findViewById(R.id.toolbar);
backIV = findViewById(R.id.backIV);
dropET = findViewById(R.id.dropLocationET);
startET = findViewById(R.id.startLocationET);
bookNowBtn = findViewById(R.id.bookNowBtn);
cancelBtn = findViewById(R.id.cancelBtn);
GoogleMap.SnapshotReadyCallback snapshotReadyCallback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
locnImg = bitmap;
Log.d(TAG, "Snapshot Ready");
}
};
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
mGmap.snapshot(snapshotReadyCallback);
Log.d(TAG, "Snapshot Taken");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
View mapBtn = (View) ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mapBtn.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 30, 30);
}
}
I have tried following this tutorial but it doesn't work in my case.The error occurs when I try mGmap.snapshot(snapshotReadyCallback);. I have initialized the map in the lines above and gotten the location using FusedLocationProviderClient api.
Can anyone help me understand why it's throwing this error? Thanks
I have a problem about using IntentService.If my app is in background or close i cant update my current location and cant get notification.If I open app again i get notification .
So i cant get notification on time.I mean i dont have a problem with creating notification or updating current location.Do i need a broadcast receiver for this problem. How can i handle with this.
My Mainclass :
public class CurrentLocationActivity extends AppCompatActivity {
private final static int PLACE_PICKER_REQUEST = 999;
TextView t1, t2, t3, textViewLocations;
Location targetLocation = new Location("");
double targetlatitude, targetlongitude;
String address;
EditText e1, e2;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference locationsRef = db.collection("Locations");
String docid;
FirebaseAuth mAuth;
private String emailString;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
checkPermissionOnActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PLACE_PICKER_REQUEST:
Place place = PlacePicker.getPlace(data, this);
//String placeName = String.format("Place: %s", place.getName());
targetlatitude = place.getLatLng().latitude;
targetlongitude = place.getLatLng().longitude;
Geocoder geocoder = new Geocoder(this);
try {
List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
//String country = addresses.get(0).getAddressLine(2);
t3.setText(address);
} catch (IOException e) {
e.printStackTrace();
}
targetLocation.setLatitude(targetlatitude);
targetLocation.setLongitude(targetlongitude);
t1.setText(String.valueOf(targetlatitude));
t2.setText(String.valueOf(targetlongitude));
}
}
}
private void checkPermissionOnActivityResult(int requestCode, int resultCode, Intent data) {
}
private static final int REQUEST_CODE = 1000;
TextView lat, lon;
Button getLocation, stopupdates;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback;
#Override
protected void onStart() {
super.onStart();
locationsRef.whereEqualTo("email", emailString)
.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
return;
}
String data = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
LocationClass locationClass = documentSnapshot.toObject(LocationClass.class);
locationClass.setDocumentId(documentSnapshot.getId());
// String documentId = note.getDocumentId();
emailString = mAuth.getCurrentUser().getEmail();
String title = locationClass.getTitle();
String description = locationClass.getDescription();
String address = locationClass.getAddress();
data += "\nTitle: " + title + "\nDescription: " + description
+ "\nAddress: " + address
+ " \n\n";
//notebookRef.document(documentId)
}
textViewLocations.setText(data);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
emailString = mAuth.getCurrentUser().getEmail();
setContentView(R.layout.activity_current_location);
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
// for activty
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
// for fragment
//startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
textViewLocations = findViewById(R.id.text_view_Locations);
e1 = findViewById(R.id.locationtitle);
e2 = findViewById(R.id.locationdescription);
t1 = findViewById(R.id.pickedlatitude);
t2 = findViewById(R.id.pickedlongitude);
t3 = findViewById(R.id.address);
stopupdates = findViewById(R.id.stopupdates);
lat = findViewById(R.id.latitude);
lon = findViewById(R.id.longitude);
getLocation = findViewById(R.id.getLocation);
//check permissions runtime
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
} else {
//if permission is granted
buildLocationRequest();
buildLocationCallback();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
getLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String locationtitle = e1.getText().toString();
final String locationdescription = e2.getText().toString();
String locationaddress = address;
emailString = mAuth.getCurrentUser().getEmail();
LocationClass locationClass = new LocationClass(emailString, locationtitle, locationdescription, locationaddress);
docid = locationClass.getDocumentId();
locationsRef.add(locationClass);
if (ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CurrentLocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Intent intentt=new Intent(getApplicationContext(),LocationReceiver.class);
PendingIntent pendingIntent=PendingIntent.getService(getApplicationContext(),1,intentt,0);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, pendingIntent);
startService(intentt);
//fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
//change state of button
getLocation.setEnabled(!getLocation.isEnabled());
stopupdates.setEnabled(!stopupdates.isEnabled());
SharedPreferences settings = getSharedPreferences("preferences",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Edit and commit
editor.putFloat("tlat", (float) targetlatitude);
editor.putFloat("tlon", (float) targetlongitude);
editor.putString("address", address);
editor.putString("title", e1.getText().toString());
editor.putString("description", e2.getText().toString());
editor.commit();
}
});
stopupdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CurrentLocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
//change state of button
getLocation.setEnabled(!getLocation.isEnabled());
stopupdates.setEnabled(!stopupdates.isEnabled());
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE: {
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
}
}
}
}
private void buildLocationCallback() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
lat.setText(String.valueOf(location.getLatitude()));
lon.setText(String.valueOf(location.getLongitude()));
if (ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(CurrentLocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CurrentLocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
//Intent intentt = new Intent(getApplicationContext(), LocationReceiver.class);
//PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intentt, 0);
//fusedLocationProviderClient.requestLocationUpdates(locationRequest, pendingIntent);
}
}
};
}
private void buildLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setSmallestDisplacement(10);
}}
My IntentService class:
public class LocationReceiver extends IntentService{
public LocationReceiver() {
super("Schedulemealksdlamsd");
}
#Override
protected void onHandleIntent(#Nullable Intent ıntent) {
Location location1=new Location("");
SharedPreferences settings = getSharedPreferences("preferences",
Context.MODE_PRIVATE);
double tlat=settings.getFloat("tlat",0);
double tlon=settings.getFloat("tlon",0);
String address=settings.getString("address","");
location1.setLatitude(tlat);
location1.setLongitude(tlon);
if(LocationResult.hasResult(ıntent)){
LocationResult locationResult=LocationResult.extractResult(ıntent);
Location location=locationResult.getLastLocation();
if(location!=null){
System.out.println("amksdma"+String.valueOf(location.getLatitude()));
if(location.distanceTo(location1)<300){
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), alarmUri);
ringtone.play();
System.out.println("mesafe 300den küçük");
NotificationHelper mNotificationHelper = new NotificationHelper(getApplicationContext());
NotificationCompat.Builder nb = mNotificationHelper.getC2Notification(settings.getString("title",""),settings.getString("description",""));
mNotificationHelper.getManager().notify(2, nb.build());
}
}
}
}
}
I have a problem about using IntentService.If my app is in background or close i cant update my current location and cant get notification.If I open app again i get notification .
Because IntenService gets finished after it has completed its task. As IntentService is just used for same purpose only.
IntentSevice gets finished once it completes code execution.
Android will not call it again as your application is not in foreground now.
If many calls are made to intentservice then only one will be executed and rest calls will be kept in waiting queue, Once previous call is finished then next awaited call will start executing same intentservice again but after one by one.
I will suggest use a service instead and make it foreground service and use START_STICKY onCommandStart.
How do i upload a files for a specific section and download the file specific for a section from my webserver to my android app? whenever i tap on display the files from the server it displays all the files. I want it to show only specific files for a section.
this is my code:
Upload files
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_professor_upload_file_to_server);
button = (ImageButton) findViewById(R.id.imageButton);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
return;
}
}
enable_button();
}
private void enable_button() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new MaterialFilePicker()
.withActivity(ProfessorUploadFileToServerActivity.this)
.withRequestCode(10)
.start();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 100 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
enable_button();
}else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
}
}
}
#Override
public void onBackPressed(){
Intent intent = new Intent(ProfessorUploadFileToServerActivity.this,ProfessorMainMenuActivity.class);
ProfessorUploadFileToServerActivity.this.startActivity(intent);
finish();
}
ProgressDialog progress;
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if(requestCode == 10 && resultCode == RESULT_OK){
progress = new ProgressDialog(ProfessorUploadFileToServerActivity.this);
progress.setTitle("Uploading");
progress.setMessage("Please wait...");
progress.show();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("https://orwell-systems.000webhostapp.com/UploadToServer.php")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if(!response.isSuccessful()){
throw new IOException("Error : "+response);
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
My Download File
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_download_file);
permission_check();
}
private void permission_check() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
return;
}
}
initialize();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
initialize();
}else {
permission_check();
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(StudentDownloadFileActivity.this,StudentMainMenuActivity.class);
StudentDownloadFileActivity.this.startActivity(intent);
finish();
}
private void initialize() {
button = (Button) findViewById(R.id.button);
listView = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,files_on_server);
listView.setAdapter(arrayAdapter);
handler = new Handler();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Downloading...");
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://orwell-systems.000webhostapp.com/DownloadFromServer.php?list_files").build();
Response response = null;
try {
response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i <array.length(); i++){
String file_name = array.getString(i);
if(files_on_server.indexOf(file_name) == -1)
files_on_server.add(file_name);
}
handler.post(new Runnable() {
#Override
public void run() {
arrayAdapter.notifyDataSetChanged();
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selected_file = ((TextView)view).getText().toString();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://orwell-systems.000webhostapp.com//uploads/" + selected_file).build();
Response response = null;
try {
response = client.newCall(request).execute();
float file_size = response.body().contentLength();
BufferedInputStream inputStream = new BufferedInputStream(response.body().byteStream());
OutputStream stream = new FileOutputStream(Environment.getExternalStorageDirectory()+"/Download/"+selected_file);
byte[] data = new byte[8192];
float total = 0;
int read_bytes=0;
handler.post(new Runnable() {
#Override
public void run() {
progressDialog.show();
}
});
while ( (read_bytes = inputStream.read(data)) != -1 ){
total = total + read_bytes;
stream.write( data, 0, read_bytes);
progressDialog.setProgress((int) ((total / file_size)*100));
}
progressDialog.dismiss();
stream.flush();
stream.close();
response.body().close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
Thank you in advance
Im getting this error, when click deny permission in "Allow app to access photos, media and files on your device ? "
FATAL EXCEPTION: main
Process: com.viantti.app, PID: 12349
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
java error line,
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
When user denies the authorization, you cannot access the media files, you should use this code only if the authorization is accepted
Try the following code, since it will proceed only when all the required permissions has been allowed by the user.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
chooseimage();
} else {
finish();
}
break;
}
}
At first read about Android Runtime Permissions here .
If you deny your app from accessing media you won't be able to take photos.
java code here,
Img_profile_pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (!checkAccessFineLocationPermission() || !checkWriteExternalStoragePermission()) {
requestPermission();
} else {
chooseimage();
}
} else {
chooseimage();
}
}
});
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera_FileUri = getOutputMediaFileUri(1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, camera_FileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, galleryRequestCode);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", camera_FileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
camera_FileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == UCrop.REQUEST_CROP) {
try {
if (requestCode == REQUEST_TAKE_PHOTO) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(camera_FileUri.getPath(), options);
Bitmap thumbnail = bitmap;
final String picturePath = camera_FileUri.getPath();
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File curFile = new File(picturePath);
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
// thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
} catch (IOException ex) {
Log.e("TAG", "Failed to get Exif data", ex);
}
System.out.println("edit-----" + Iconstant.Edit_profile_image_url);
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == galleryRequestCode) {
Uri selectedImage = data.getData();
if (selectedImage.toString().startsWith("content://com.sec.android.gallery3d.provider")) {
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
final String picturePath = c.getString(columnIndex);
c.close();
File curFile = new File(picturePath);
Picasso.with(ProfilePage.this).load(picturePath).resize(100, 100).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Bitmap thumbnail = bitmap;
mSelectedFilePath = picturePath;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
} else {
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
final String picturePath = c.getString(columnIndex);
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap thumbnail = bitmap; //getResizedBitmap(bitmap, 600);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File curFile = new File(picturePath);
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
} catch (IOException ex) {
Log.e("TAG", "Failed to get Exif data", ex);
}
thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
c.close();
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
}
}
if ( requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
try {
selectedBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
Img_profile_pic.setImageBitmap(selectedBitmap);
Img_profile_pic.setImageURI(resultUri);
UploadDriverImage(Iconstant.Edit_profile_image_url);
} else if (resultCode == UCrop.RESULT_ERROR) {
final Throwable cropError = UCrop.getError(data);
System.out.println("========muruga cropError==========="+cropError);
}
}
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
private void UploadDriverImage(String url) {
dialog = new Dialog(ProfilePage.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loading);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
TextView dialog_title = (TextView) dialog.findViewById(R.id.custom_loading_textview);
dialog_title.setText(getResources().getString(R.string.action_loading));
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
System.out.println("------------- image response-----------------"+response.data);
String resultResponse = new String(response.data);
System.out.println("------------- response-----------------"+resultResponse);
String sStatus = "", sResponse = "",SUser_image="",Smsg="";
try {
JSONObject jsonObject = new JSONObject(resultResponse);
sStatus = jsonObject.getString("status");
if (sStatus.equalsIgnoreCase("1")) {
// JSONObject responseObject = jsonObject.getJSONObject("response");
// SUser_image = jsonObject.getString("image");
Smsg = jsonObject.getString("image_url");
// Img_profile_pic.setImageBitmap(bitMapThumbnail);
session.setuser_image(Smsg);
Picasso.with(ProfilePage.this).load(Smsg).placeholder(R.drawable.no_user_image).into(Img_profile_pic);
NavigationDrawer.navigationNotifyChange();
Locale locale = null;
switch (language_code){
case "en":
locale = new Locale("en");
session.setlamguage("en","en");
break;
case "es":
locale = new Locale("es");
session.setlamguage("es","es");
// session.setlamguage("Ar",language_change.getSelectedItem().toString());
// System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
// Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
// finish();
// startActivity(i);
// Intent bii = new Intent();
// bii.setAction("homepage");
// sendBroadcast(bii);
// finish();
break;
case "ta":
locale = new Locale("ta");
session.setlamguage("ta","ta");
// session.setlamguage("Ar",language_change.getSelectedItem().toString());
// System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
// Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
// finish();
// startActivity(i);
// Intent bii = new Intent();
// bii.setAction("homepage");
// sendBroadcast(bii);
// finish();
break;
default:
locale = new Locale("en");
session.setlamguage("en","en");
break;
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());
Alert(getResources().getString(R.string.action_success),getResources().getString(R.string.edit_profile_success_label));
} else {
sResponse = jsonObject.getString("response");
Alert(getResources().getString(R.string.my_rides_rating_header_sorry_textview), sResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
Toast.makeText(ProfilePage.this,"Something happened , try again",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message + " Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message + " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message + " Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
System.out.println("------------Authkey------cabily---------" + Agent_Name);
System.out.println("------------userid----------cabily-----" + UserID);
System.out.println("------------apptoken----------cabily-----" + gcmID);
System.out.println("------------applanguage----------cabily-----" + language_code);
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authkey", Agent_Name);
headers.put("isapplication",Iconstant.cabily_IsApplication);
headers.put("applanguage",language_code);
headers.put("apptype", Iconstant.cabily_AppType);
headers.put("userid",UserID);
headers.put("apptoken",gcmID);
/* System.out.println("servicereques apptype------------------"+Iconstant.cabily_AppType);
System.out.println("servicereques apptoken------------------"+gcmID);
System.out.println("servicereques userid------------------"+UserID);
Map<String, String> headers = new HashMap<String, String>();
headers.put("User-agent",Iconstant.cabily_userAgent);
headers.put("isapplication",Iconstant.cabily_IsApplication);
headers.put("applanguage",Iconstant.cabily_AppLanguage);
headers.put("apptype",Iconstant.cabily_AppType);
headers.put("apptoken",gcmID);
headers.put("userid",UserID);*/
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("user_id",UserID);
System.out.println("user_id---------------"+UserID);
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
params.put("user_image",new DataPart("cabily_user.jpg", byteArray));
System.out.println("user_image--------edit------"+byteArray);
return params;
}
};
//to avoid repeat request Multiple Time
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
multipartRequest.setRetryPolicy(retryPolicy);
multipartRequest.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
multipartRequest.setShouldCache(false);
AppController.getInstance().addToRequestQueue(multipartRequest);
}
// --------------------Method for choose image to edit profileimage--------------------
private void chooseimage() {
photo_dialog = new Dialog(ProfilePage.this);
photo_dialog.getWindow();
photo_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
photo_dialog.setContentView(R.layout.image_upload_dialog);
photo_dialog.setCanceledOnTouchOutside(true);
photo_dialog.getWindow().getAttributes().windowAnimations = R.style.Animations_photo_Picker;
photo_dialog.show();
photo_dialog.getWindow().setGravity(Gravity.CENTER);
RelativeLayout camera = (RelativeLayout) photo_dialog
.findViewById(R.id.profilelayout_takephotofromcamera);
RelativeLayout gallery = (RelativeLayout) photo_dialog
.findViewById(R.id.profilelayout_takephotofromgallery);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePicture();
photo_dialog.dismiss();
}
});
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
photo_dialog.dismiss();
}
});
}
private boolean checkAccessFineLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkAccessCoarseLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkWriteExternalStoragePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED || grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
chooseimage();
} else {
finish();
}
break;
}
}