I devloped an android app for barcode scanner,now in that i want to carry out further processing on the retrieved scan results, such as loading URLs or looking the data up in a third party data source.So how can i do this.I am using android studio for devloping app.
Here is my code for MAinActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
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;
private TextView formatTxt, contentTxt;
#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("CONTENT: " + scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
And i am using zxing library.
Here is my edited code:
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("CONTENT: " + scanContent);
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("url");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
It is the correct way or not?
Start your scanner Activity with startActivityForResult and override onActivityResult for processing the retrieved data.
Take a look at the examples here.
You have to start new Activity to open your URL.
private void openUrl(String url) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
Call this method inside your onActivityResult method. Probably scanContent variable is your URL.
Related
Everytime I try to go between activities, I save the editText texts because user experience and all that, but for some reason, while intents get through no problem, the savedinstanceState just won't ever be not null. I've added the onSave and onRestore methods, overrided them, did what had to be done inside, yet it is always null. What am I missing here?
package com.gmproxy.pastilarma;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import com.gmproxy.DAO.PathologyUserRepository;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import com.gmproxy.Util.ImageConverter;
import com.gmproxy.ViewModels.UserViewModel;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserAddScreen extends AppCompatActivity {
Button gotoBack, addObservation, saveUser, addPathologies;
EditText addUsername, addSurname, addAge, addRoomNumber;
Spinner addGender;
ImageView selectImage;
String obs;
Pathology paths;
Context context;
UserViewModel userViewModel;
int pathAct = 0;
int obsAct = 0;
PathologyUserRepository paUsRe;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
context = this.getApplicationContext();
pathAct = getIntent().getIntExtra("path-record", 0);
obsAct = getIntent().getIntExtra("obs-record", 0);
paUsRe = new PathologyUserRepository(this.getApplication());
setContentView(R.layout.activity_user_add_screen);
gotoBack = findViewById(R.id.GotoBack);
addObservation = findViewById(R.id.AddObservation);
saveUser = findViewById(R.id.SaveUser);
addPathologies = findViewById(R.id.AddPathologies);
addUsername = findViewById(R.id.AddUsername);
addSurname = findViewById(R.id.AddSurname);
addAge = findViewById(R.id.AddAge);
addRoomNumber = findViewById(R.id.AddRoomNumber);
addGender = findViewById(R.id.AddGender);
selectImage = findViewById(R.id.SelectImage);
if (pathAct == 1 || obsAct == 1 && savedInstanceState!=null) {
onRestoreInstanceState(savedInstanceState);
}
if (savedInstanceState == null){
Log.println(Log.INFO,"Test","El bundle está vacio");
}
userViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(UserViewModel.class);
/*
From this line to 94, we create the spinner, since there's only two options there really is no need of poblating the list from the database.
*/
List<String> genderList = new ArrayList<>();
genderList.add("M");
genderList.add("F");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner, genderList);
adapter.setDropDownViewResource(R.layout.spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addGender.setAdapter(adapter);
addGender.setSelection(0);
if (savedInstanceState == null){
obs = intent.getStringExtra("observation");
} else {
obs = savedInstanceState.getString("Observacion-usuario");
}
if (obs != null){
Log.println(Log.INFO,"test obs", obs);
}
paths = (Pathology) intent.getSerializableExtra("paths");
}
public void gotoBack(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
}
public void addObservation(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserObservationScreen.class);
startActivity(mainAct);
finish();
}
public void addPathology(View view) {
Intent mainAct = new Intent(UserAddScreen.this, PathologiesSearchScreen.class);
startActivity(mainAct);
finish();
}
/**
* This saves all recorded data for when we come back to the activity
* #param savedInstanceState
*/
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
if (!addUsername.getText().toString().equals("")) {
savedInstanceState.putString("Nombre_usuario", addUsername.getText().toString());
}
if (!addSurname.getText().toString().equals("")) {
savedInstanceState.putString("Apellido_usuario", addSurname.getText().toString());
}
if (!addAge.getText().toString().equals("")) {
savedInstanceState.putString("Edad_usuario", addAge.getText().toString());
}
if (!addRoomNumber.getText().toString().equals("")) {
savedInstanceState.putString("Habitacion_usuario", addRoomNumber.getText().toString());
}
savedInstanceState.putInt("Sexo_usuario", addGender.getSelectedItemPosition());
if (obs != null){
savedInstanceState.putString("Observacion-usuario", obs);
}
if (paths != null){
savedInstanceState.putSerializable("Patologia-usuario", paths);
}
super.onSaveInstanceState(savedInstanceState);
Log.println(Log.INFO,"Guardado","guardado");
}
/**
* This loads up all recorded things in the view
* #param savedInstanceState
*/
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
addUsername.setText(savedInstanceState.getString("Nombre_usuario"));
addSurname.setText(savedInstanceState.getString("Apellido_usuario"));
addAge.setText(savedInstanceState.getString("Edad_usuario"));
addRoomNumber.setText(savedInstanceState.getString("Habitacion_usuario"));
addGender.setSelection(savedInstanceState.getInt("Sexo_usuario"));
obs = savedInstanceState.getString("Observacion-usuario");
paths = (Pathology) savedInstanceState.getSerializable("Patologia-usuario");
}
/*
The next two methods are for
A: Opening either the camera, gallery, or getting a picture from assets
B: Actually selecting the image and making it show in the imageButton
*/
public void selectImageAction(View view) {
final CharSequence[] options = {"Hacer una foto", "Elegir de la galería", "Usar una genérica", "Cancelar"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserAddScreen.this);
builder.setTitle("¡Añade una foto!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Hacer una foto")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivity(intent);
finish();
} else if (options[item].equals("Elegir de la galería")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivity(intent);
finish();
} else if (options[item].equals("Cancelar")) {
dialog.dismiss();
} else if (options[item].equals("Usar una genérica")) {
selectImage.setImageResource(R.drawable.ic_user_generic_foreground);
selectImage.setBackgroundResource(R.drawable.ic_user_generic_foreground);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
selectImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, System.currentTimeMillis() + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("..******************...", picturePath + "");
ImageView viewImage;
selectImage.setImageBitmap(thumbnail);
}
}
}
/**
* Actually creates the user in the database
* #param view
*/
public void saveUser(View view) {
//Just this to turn the image into a blob
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.id.SelectImage);
ImageConverter imgCon = new ImageConverter();
byte[] bytearray = imgCon.bitmapToBiteArray(bitmap);
if (addUsername.getText().toString() != null || addSurname.getText().toString() != null
|| addAge.getText().toString() != null || addRoomNumber.getText().toString() != null){
Toast.makeText(this, "Usuario creado.", Toast.LENGTH_SHORT).show();
User user = new User(addUsername.getText().toString(), addSurname.getText().toString(), addAge.getText().toString(),
Integer.parseInt(addRoomNumber.getText().toString()), addGender.getSelectedItem().toString(), obs, bytearray);
userViewModel.insert(user);
paUsRe.insertObject(userViewModel.getIdByNameAndSurname(user.getUser_name(), user.getUser_surname()), paths.getId_pathology());
Toast.makeText(this, "Patología " + paths.getPathologyName() + " añadida", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
} else {
Toast.makeText(this, "Por favor, introduce todos los parámetros necesarios.", Toast.LENGTH_SHORT).show();
}
}
}
onSaveInstanceState() is called right before your activity is about to be killed or restarted because of memory pressure or screen orientation change. Since you are just switching between activities, onSaveInstance() is not called thus the null instance. Wound suggest SharedPreference instead
I am using a "ACTION_OPEN_DOCUMENT" intent to choose a file and open it.
This works just fine when I go to read the file.
However, when the file resides on EXTERNAL storage, and I run a query to obtain the file name, my program crashes. If the file resides on INTERNAL storage, I have no issues.
I DO have (and check for) external storage access permissions.
I have the query enclosed in a try{}, but the exception is not caught. I am developing on a Chrome book, so I am unable to run the debugger on it. But I have isolated the issue to the result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); statement.
I know that access to files on external storage has been limited, but I would think that if I can read a file that I should also be able to query it as well.
Here is my code:
package com.muddco.demo3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
Activity mAct;
TextView rvalue, fnamevalue;
Button btn1, btn2;
Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
rvalue = findViewById(R.id.readResult);
fnamevalue = findViewById(R.id.textView2);
mAct = this;
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Launch a file picker
*/
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select a GPX file"), 1);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Get and display file name
*/
String fname = getFileName(fileUri);
fnamevalue.setText(fname);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted and now can proceed
Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// add other cases for more permissions
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream = null;
Uri uri = null;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
// Process GPX file
uri = data.getData();
try {
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
rvalue.setText(readFile(inputStream));
} catch (FileNotFoundException e) {
Toast.makeText(this, "File not found: " + uri.toString(), Toast.LENGTH_SHORT).show();
}
//String fName = getFileName(uri);
//Toast.makeText(mAct, "Filename: "+fName, Toast.LENGTH_LONG).show();
fileUri = uri;
btn2.setVisibility(View.VISIBLE);
}
}
}
/*
* Read a FileStream
*
*/
String readFile(InputStream is) {
String ret = "";
String line = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
ret += line + "\n";
}
br.close();
} catch (Exception e) {
// if any I/O error occurs
e.printStackTrace();
ret = "Exception!";
}
return ret;
}
/*
* Obtain the filename from a URI
*/
public String getFileName(Uri uri) {
String result = "<empty>";
Cursor cursor;
if (uri.getScheme().equals("content")) {
ContentResolver cr = getContentResolver();
try {
cursor = cr.query(uri, null, null, null, null);
} catch (Exception e) {
Toast.makeText(this, "Cursor exception: " + e.toString(), Toast.LENGTH_LONG).show();
return null;
}
try {
if (cursor != null && cursor.moveToFirst()) {
//
// THE NEXT STATEMENT CRASHES WHEN FILE RESIDES ON EXTERNAL STORAGE
//
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
else {
Toast.makeText(mAct, "Bad cursor", Toast.LENGTH_SHORT).show();
return "Bad Cursor";
}
} catch (Exception e) {
Toast.makeText(this, "Cursor exception: " + e.toString(), Toast.LENGTH_LONG).show();
return "Cursoe Exception";
} finally {
cursor.close();
}
}
else
result="Non content URI";
return result;
}
}
When I press the first button, the file requestor pops up and I select my test text file. The contents of the file are listed in a textbox, then a second button is made visible. When that second button is pressed, I query the file and place the filename in a second textbox.
The entire project, along with the test.txt file I am using to test, can be found here
I am trying to make a app that takes high quality photo and the upload them but one of the most important part won't work, the camera. Intent data is null so no image a being display. I took the infor from https://developer.android.com/training/camera/photobasics#TaskPath.
I have tried different way but nothing is working from me.
package com.example.gn.nextcamtest;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView txt_Test;
Button btn_Cam;
ImageView iv_image;
static final int REQUEST_IMAGE_CAPTURE = 1;
String mCurrentPhotoPath;
public static final int RequestPermissionCode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_Cam = (Button) findViewById(R.id.btn_Cam);
iv_image = (ImageView) findViewById(R.id.iv_Test);
txt_Test = (TextView) findViewById(R.id.txt_test);
EnableRuntimePermissionToAccessCamera();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
txt_Test.setText(" " + bundle.getString("test"));
}
btn_Cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
if (data.getExtras() != null && data.getExtras().get("data") instanceof Bitmap) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv_image.setImageBitmap(imageBitmap);
// iv_image.setImageBitmap((Bitmap)data.getExtras().get("data"));
} else {
iv_image.setImageResource(R.drawable.ic_launcher_background);
Toast.makeText(this, "Fail to load image", Toast.LENGTH_LONG).show();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ );
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "com.example.gn.nextcamtest.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
// Requesting runtime permission to access camera.
public void EnableRuntimePermissionToAccessCamera() {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION
}, 101);
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Printing toast message after enabling runtime permission.
Toast.makeText(this, "CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.CAMERA
}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
I tried this too a couple of days ago and had to struggle a lot. Then I figured it myself.
Here is how my code looks :
1) In onCreate :
capture.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, storagePermissionCode);
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, cameraPermissionCode);
} else {
ContentValues values = new ContentValues();
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, cameraRequestCode);
}
}
});
2) In onActivityResult :
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode == cameraRequestCode) {
if (resultCode == Activity.RESULT_OK) {
FileOutputStream stream = null;
try {
Bitmap photo = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
String saveFilePath = getRealPathFromURI(imageUri);
stream = new FileOutputStream(saveFilePath);
photo.compress(Bitmap.CompressFormat.JPEG, 25, stream);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Can't save image !", Toast.LENGTH_SHORT).show();
} finally {
try {
if (stream != null) {
stream.close();
Toast.makeText(getApplicationContext(), "Image saved successfully !", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Can't save image, try again !", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Can't capture image !", Toast.LENGTH_SHORT).show();
}
}
}
3) getRealPathFromURI function :
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
why when i trying to upload image with size 1.5 mb it's said error while uploading, but actually the image is successfully upload? and if i trying to upload with size 100 kb it's said Image Uploaded Successfully
WC_Activity.java
package com.emergency.e_place;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.HashMap;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAGS = "DEBUG";
String Latitude;
String Longitude;
private final String TAG = this.getClass().getName();
ImageView ivCamera, ivGallery, ivUpload, ivImage;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST = 13323;
final int GALLERY_REQUEST = 22131;
String selectedPhoto;
EditText etIpAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAGS, "onLocationChanged: " + Longitude);
etIpAddress = (EditText)findViewById(R.id.etIpAddress);
cameraPhoto = new CameraPhoto(getApplicationContext());
galleryPhoto = new GalleryPhoto(getApplicationContext());
ivImage = (ImageView)findViewById(R.id.ivImage);
ivCamera = (ImageView)findViewById(R.id.ivCamera);
ivGallery = (ImageView)findViewById(R.id.ivGallery);
ivUpload = (ImageView)findViewById(R.id.ivUpload);
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
cameraPhoto.addToGallery();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while taking photos", Toast.LENGTH_SHORT).show();
}
}
});
ivGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(galleryPhoto.openGalleryIntent(), GALLERY_REQUEST);
}
});
ivUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedPhoto == null || selectedPhoto.equals("")){
Toast.makeText(getApplicationContext(), "No Image Selected.", Toast.LENGTH_SHORT).show();
return;
}
try {
Bitmap bitmap = ImageLoader.init().from(selectedPhoto).requestSize(1024, 1024).getBitmap();
String encodedImage = ImageBase64.encode(bitmap);
Log.d(TAG, encodedImage);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("image", encodedImage);
PostResponseAsyncTask task = new PostResponseAsyncTask(WC_Activity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if(s.contains("uploaded_success")){
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully.",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error while uploading.",
Toast.LENGTH_SHORT).show();
}
}
});
String ip = etIpAddress.getText().toString();
task.execute("http://" +ip + "/AndroidUpload/upload.php");
task.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error.",
Toast.LENGTH_SHORT).show();
}
});
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while encoding photos", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST){
String photoPath = cameraPhoto.getPhotoPath();
selectedPhoto = photoPath;
Bitmap bitmap = null;
try {
bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(getRotatedBitmap(bitmap, 90));
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
}
}
else if(requestCode == GALLERY_REQUEST){
Uri uri = data.getData();
galleryPhoto.setPhotoUri(uri);
String photoPath = galleryPhoto.getPath();
selectedPhoto = photoPath;
try {
Bitmap bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
}
}
}
}
private Bitmap getRotatedBitmap(Bitmap source, float angle){
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap bitmap1 = Bitmap.createBitmap(source,
0, 0, source.getWidth(), source.getHeight(), matrix, true);
return bitmap1;
}
}
my app needs to get user's meetup id. meetup uses oauth 2.0. found different pieces of code across the web, will paste in stackoverflow as answer to this question, for the next person.
import a library via graddle build file:
dependencies {
compile 'net.smartam.leeloo:oauth2-common:0.1'
compile 'net.smartam.leeloo:oauth2-client:0.1'
}
create a class for meetup authenticating. this class written by adrianmaurer (https://gist.github.com/adrianmaurer/4673944), thank you adrianmaurer!
MeetupAuthActivity:
package pixtas.com.nightout;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
// leeloo oAuth lib https://bitbucket.org/smartproject/oauth-2.0/wiki/Home
import net.smartam.leeloo.client.OAuthClient;
import net.smartam.leeloo.client.URLConnectionClient;
import net.smartam.leeloo.client.request.OAuthClientRequest;
import net.smartam.leeloo.client.response.OAuthAccessTokenResponse;
import net.smartam.leeloo.client.response.OAuthAuthzResponse;
import net.smartam.leeloo.common.exception.OAuthProblemException;
import net.smartam.leeloo.common.exception.OAuthSystemException;
import net.smartam.leeloo.common.message.types.GrantType;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* Created by tmr_byronMac on 4/24/15.
*/
public class MeetupAuthActivity extends Activity {
private final String TAG = getClass().getName();
// Meetup OAuth Endpoints
public static final String AUTH_URL = "https://secure.meetup.com/oauth2/authorize";
public static final String TOKEN_URL = "https://secure.meetup.com/oauth2/access";
// Consumer
//public static final String REDIRECT_URI_SCHEME = "oauthresponse";
//public static final String REDIRECT_URI_HOST = "com.yourpackage.app";
//public static final String REDIRECT_URI_HOST_APP = "yourapp";
//public static final String REDIRECT_URI = REDIRECT_URI_SCHEME + "://" + REDIRECT_URI_HOST + "/";
public static final String REDIRECT_URI = "NightOut://meetup.com";
public static final String CONSUMER_KEY = "YOUR_KEY";
public static final String CONSUMER_SECRET = "YOUR_SECRET";
private WebView _webview;
private Intent _intent;
private Context _context;
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
_intent = getIntent();
_context = getApplicationContext();
_webview = new WebView(this);
_webview.setWebViewClient(new MyWebViewClient());
setContentView(_webview);
_webview.getSettings().setJavaScriptEnabled(true);
OAuthClientRequest request = null;
try {
request = OAuthClientRequest.authorizationLocation(
AUTH_URL).setClientId(
CONSUMER_KEY).setRedirectURI(
REDIRECT_URI).buildQueryMessage();
} catch (OAuthSystemException e) {
Log.d(TAG, "OAuth request failed", e);
}
_webview.loadUrl(request.getLocationUri() + "&response_type=code&set_mobile=on");
}
public void finishActivity() {
//do something here before finishing if needed
finish();
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String code = uri.getQueryParameter("code");
String error = uri.getQueryParameter("error");
if (code != null) {
new MeetupRetrieveAccessTokenTask().execute(uri);
// setResult(RESULT_OK, _intent);
// finishActivity();
} else if (error != null) {
setResult(RESULT_CANCELED, _intent);
finishActivity();
}
return false;
}
}
private class MeetupRetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
#Override
protected Void doInBackground(Uri... params) {
Uri uri = params[0];
String code = uri.getQueryParameter("code");
OAuthClientRequest request = null;
try {
request = OAuthClientRequest.tokenLocation(TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(
CONSUMER_KEY).setClientSecret(
CONSUMER_SECRET).setRedirectURI(
REDIRECT_URI).setCode(code)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthAccessTokenResponse response = oAuthClient.accessToken(request);
// do something with these like add them to _intent
// Intent returnIntent = new Intent();
// returnIntent.putExtra("access_token", response.getAccessToken());
// setResult(RESULT_OK,returnIntent);
Log.d(TAG, "access token: " + response.getAccessToken());
Log.d(TAG, response.getExpiresIn());
Log.d(TAG, response.getRefreshToken());
_intent.putExtra("access_token", response.getAccessToken());
setResult(RESULT_OK, _intent);
finish();
} catch (OAuthSystemException e) {
Log.e(TAG, "OAuth System Exception - Couldn't get access token: " + e.toString());
Toast.makeText(_context, "OAuth System Exception - Couldn't get access token: " + e.toString(), Toast.LENGTH_LONG).show();
} catch (OAuthProblemException e) {
Log.e(TAG, "OAuth Problem Exception - Couldn't get access token");
Toast.makeText(_context, "OAuth Problem Exception - Couldn't get access token", Toast.LENGTH_LONG).show();
}
return null;
}
}
#Override
public void onBackPressed()
{
setResult(RESULT_CANCELED, _intent);
finishActivity();
}
}
call MeetupAuthActivity from your main activity.
MainActivity:
public void getMeetupAccessToken(){
Intent intent;
intent = new Intent(this, MeetupAuthActivity.class);
// startActivity(intent);
startActivityForResult(intent,GET_MEETUP_ACCESS_TOKEN_ACTIVITY);
}
in MainActivity, capture the results form auth activity.
MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// if(requestCode == 1 && resultCode == RESULT_OK)
if(requestCode == GET_MEETUP_ACCESS_TOKEN_ACTIVITY)
{
accessToken = data.getExtras().getString("access_token");
saveMeetupAccessTokenToSharedPreferences();
//save meetupid plus device id to parse
getMyMeetupIdFromMeetupServer();
// Log.i(DEBUG_TAG,"MainActivity, accessToken" + accessToken);
}
}