I use ZXing library to scan QrCode.
From the drawer menu i call a new intent where i start a custom activity scan with a custom view :
integrator.setCaptureActivity(QrCodeCaptureActivity.class);
public class QrCodeActivity extends AppCompatActivity {
private static final String TAG = "QrCodeActivity";
private String message = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrcode);
setToolbar();
scanBarcodeCustomLayout();
}
/** Set la toolbar */
private void setToolbar(){
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void scanBarcodeCustomLayout() {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setOrientationLocked(false);
integrator.setCaptureActivity(QrCodeCaptureActivity.class);
integrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
message = result.getContents();
if(result.getContents() == null) {
Log.d(TAG, "Cancelled scan");
finish();
// Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
showConfirmDialog();
Log.d(TAG, "Scanned: " + result.getContents());
// Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
private void showConfirmDialog(){
Intent confirmIntent = new Intent(QrCodeActivity.this, QrCodeConfirmActivity.class);
confirmIntent.putExtra(Constants.QR_CODE_MESSAGE, message);
startActivity(confirmIntent);
}
}
The capture activity looks like this :
public class QrCodeCaptureActivity extends CaptureActivity {
#Override
protected DecoratedBarcodeView initializeContent() {
setContentView(R.layout.capture_small);
return (DecoratedBarcodeView)findViewById(R.id.zxing_barcode_scanner);
}
}
You can see, when the scan is done i open a new activity with the result for confirmation :
private void showConfirmDialog(){
Intent confirmIntent = new Intent(QrCodeActivity.this, QrCodeConfirmActivity.class);
confirmIntent.putExtra(Constants.QR_CODE_MESSAGE, message);
startActivity(confirmIntent);
}
When i'm in this activity and when i close this, I return on a blank activity.
I think this blank activity is the Capture Activity for custom apparence :
integrator.setCaptureActivity(QrCodeCaptureActivity.class);
Where is the mistake ?
Thanks
Just a simple thing you have to add in it ::
Add one new line after ::
startActivity(confirmIntent);
finish();
So your last QR code activity will be no longer visible at all.
I found the mistake ...
I call a activity instead of call directly the method
integrator.initiateScan();
Related
Completely new to this and to Android development, looking for a bit of help if possible. I am developing my first application for Android at the moment and have very little coding experience...I basically have an application at the moment that is allowing me to add/delete/update users to and from a sqlite database. I am looking for a way just to add a button on the main homepage that allows me to access the camera and take a picture. The main activity is simply a page with buttons to add/delete etc:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("Please enter a name!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("User Added!");
} else {
toastMessage("Something went wrong");
}
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
The code I have for implementing the camera is shown below(it works for invoking the camera and taking a picture but only from the camera outside the application)
Is it possible for me to just a button on the main activity page that allows me to "take picture" from within the application
(code for invoking camera)
public class MainActivity extends AppCompatActivity {
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager. PERMISSION_GRANTED){
getPhoto();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else{
getPhoto();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
try {
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sorry if the question seems stupid, completely new to Android development and new to coding so I am very unsure.
I'm not sure about what you are looking for, but here is code to take a picture :
https://developer.android.com/training/camera/photobasics.html
To add the button, you need to add it in the layout then get the reference in your activity class with the findViewById method
Hope this help
I am trying to make image selector for application.For that i am using multi-image-selector library which is perfeclty works when used in activity ,but here i want to use it in fragment.so in fragment OnActivityResult() method is not getting called.Can anyone help me to solve this?
Here's my code:
MainActivity.java:(My Main Activity)
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.frame, new Image_Selecter()).commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Utilz.printLog("Parentactivity", "onActivityResult");
Log.e("hererererer", "hererererer");
if (requestCode == REQUEST_IMAGE) {
new Image().onActivityResult(requestCode, resultCode, data);
}
}
}
Image:(My Fragment)
public class Image extends Fragment {
private ArrayList<String> mSelectPath;
private static final int REQUEST_IMAGE = 2;
ArrayList<Uri> mMedia = new ArrayList<Uri>();
Uri uri;
ImageView img;
protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_image, container, false);
img = (ImageView) view.findViewById(R.id.img);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickImage();
}
});
return view;
}
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getActivity());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getActivity(), REQUEST_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == getActivity().RESULT_OK) {
mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
mMedia.clear();
for (String p : mSelectPath) {
Uri uri = Uri.parse(p);
mMedia.add(uri);
}
uri = mMedia.get(0);
Log.e("uri", " " + uri);
if (!uri.toString().contains("content://")) {
uri = Uri.fromFile(new File(uri.toString()));
Log.e("in if", " uri = " + uri);
}
try {
Glide.with(this)
.load(uri)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(img);
} catch (Exception e) {
Log.e("Exceptionn", " " + e);
}
}
}
}
Try this in your activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Parentactivity", "onActivityResult");
if (requestCode == REQUEST_IMAGE) { //use request code as REQUEST_IMAGE while starting intent for camera
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);//calling fragments onActivityResult here
}
}
IIRC onActivityResult doesn't get called on a Fragment, it gets called on your parent Activity. You would need to catch this in the Activity and forward the result on to the fragment.
There are two methods which looks same but behaves little bit different.
If method is called by from activity, its not going to give callback to fragment unless called from fragment.
Activity.startActivityForResult()
Fragment.startActivityForResult()
Check out the library if there is way to calling it from fragment.
I dont know the library, just imaging if you can pass fragment to
MultiImageSelector selector = new MultiImageSelector(getActivity()); or selector.start(getActivity(), REQUEST_IMAGE);
Good luck
Emre
you have to call it with intent
public void pickImage() {
Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
startActivityForResult(intent, REQUEST_IMAGE);
}
if you were doing getActivity().startActivityForResult(intent, REQUEST_IMAGE);
the on OnActivityResult() will happen on activity instead of fragment. The way you are using it is like that, so you need to use the intent way.
also that maybe will make your code to work
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getContext());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getContext(), REQUEST_IMAGE);
}
I have two activities: A and B.
In activity A: On "btn_navSimilarColor" buttonClick - I made a call to B with startActivityForResult. There are already some intents inside A to use camera and gallery and a intent data i am receiving from previous activity.
In activity B: I made a asyncTask call inside onCreate() and in asyncTask's onPostExecute() i am sending back intent extra to Activity A.
Activity A:
public class A extends Activity
{
...
#Override
public void onCreate(Bundle savedInstanceState)
{
...
Bundle extras = getIntent().getExtras();
if (extras != null) {
edtTxtColorCode.setText(extras.getString("xtra_selectedColor"));
} else {
Toast.makeText(this, "There was a problem in the response!", Toast.LENGTH_SHORT).show();
}
}
public void buttonOnClick(View view)
{
switch (view.getId())
{
case R.id.btnCamera:
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), FLAG_CAMERA);
break;
case R.id.btnGallery:
startActivityForResult(
new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), FLAG_GALLERY);
break;
case R.id.btn_navSimilarColor:
Intent intnt_similar = new Intent(A.this, B.class);
intnt_similar.putExtra("xtraColor", edtTxtColorCode.getText().toString());
startActivityForResult(intnt_similar, FLAG_navSimilarColorAct);
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.v("resultCode","="+resultCode);
if (resultCode == Activity.RESULT_OK)
{
mCursor = null;
if (requestCode == FLAG_GALLERY)
onSelectFromGalleryResult(data);
else if (requestCode == FLAG_CAMERA)
onCaptureImageResult(data);
else if(requestCode == FLAG_navSimilarColorAct)
{ Bundle extras = getIntent().getExtras();
String stt = extras.getString("intnt_similarColor");
if (extras != null)
edtTxtColorCode.setText(extras.getString("intnt_similarColor"));
}
}
}
}
Activity B:
public class B extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
....
receiveIntent();
new AsyncConver().execute();
}
private void receiveIntent() {
Bundle extras = getIntent().getExtras();
if (extras != null)
strIntentrecvdColor = extras.getString("xtraColor");
else
Toast.makeText(this, "There was a problem in the response!", Toast.LENGTH_SHORT).show();
}
class AsyncConvert extends AsyncTask<String, Integer, String>
{
...
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
Custom_SimilarColorListAdapter gridAdapter = new Custom_SimilarColorListAdapter(SimilarColors.this, list_SimilarColors);
grdVw.setAdapter(gridAdapter);
grdVw.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String str_colorCodeSimilar = ((TextView) v.findViewById(R.id.listrow_similar_code)).getText().toString();
Toast.makeText(getApplicationContext(), "ID:: "+ str_colorCodeSimilar , Toast.LENGTH_SHORT).show();
Intent retrnIntnt = new Intent();
retrnIntnt.putExtra("intnt_similarColor", str_colorCodeSimilar);
setResult(RESULT_OK, retrnIntnt);
finish();
}
});
}
}
}
Problem:
Now the problem is that i am getting data in activity B - as i am already checking it with
Toast.makeText(getApplicationContext(), "ID:: "+ str_colorCodeSimilar , Toast.LENGTH_SHORT).show();
But in Activity A's onActivityResult i am not getting the bundle extra data for "intnt_similarColor" which is:
String stt = extras.getString("intnt_similarColor");
instead i am getting bundle extra for "xtra_selectedColor" which is inside onCreate().
Why is this happening and how am i getting the previous bundle data , not the one that has been passed from activity B?
change Bundle extras = getIntent().getExtras(); to Bundle extras = data.getExtras();
Get string from data intent that you receive from onActivityResult. You use Bundle extras = getIntent().getExtras(); where getIntent() is actually class A's received intent.
So you have to use:
String stt = data.getStringExtra("intnt_similarColor");
This question already has an answer here:
return value to fragment from activity android
(1 answer)
Closed 6 years ago.
I know that this question may be asked someone else but I can't find a solution that worked for me. Basically I have a fragment with one button. When user press that button new activity is opened (that activity just scans qr code) and I want to pass scan result back to my fragment. So basically
public class UiFragment extends Fragment implements ServiceCallBack {
// tons of code
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ScanActivity.class); // start scan activity
startActivity(intent);
}
});
}
public class ScanActivity extends AppCompatActivity {
// lots of code
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String result = scanResult.getContents();
if(result != null && result.length() > 0){
// now I want to go back to my previous fragment and pass result
}
}
finish();
}
}
Please note that I want activity to fragment communication! I have tried to use interface, however that doesn't worked for me. Is it possible to do that?
If I understood your question correctly, then you must be having 1 activity which launches a fragment. Let's name that activity as MainActivity.
Now change your UiFragment to look like
public class UiFragment extends Fragment implements ServiceCallBack {
// tons of code
public static final SCAN_REQUEST_CODE = 1001; //Any number
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ScanActivity.class); // start scan activity
startActivityForResult(intent, SCAN_REQUEST_CODE);
}
});
}
Your MainActivity will have onActivityResult()
public class MainActivity extends AppCompatActivity {
// lots of code
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == UiFragment.SCAN_REQUEST_CODE){
//Check for result code if you want to
if(resultCode == RESULT_OK){
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String result = scanResult.getContents();
if(result != null && result.length() > 0){
//Now check if your fragment is visible
UiFragment uiFragment = (UiFragment) getSupportFragmentManager().findFragmentByTag(your_fragment_tag_name);
if (uiFragment != null && uiFragment.isAdded()) {
//Call your fragment's public method here. let's say you have a method update in your fragment then write
uiFragment.update(); // you can pass arguments in this method depending on your requirements.
}
}
}
}
}
}
}
Your ScanActivity will not have onActivityResult() method
public class ScanActivity extends AppCompatActivity {
// lots of code
//Some method which scans and setResult
public void scan() {
setResult(RESULT_OK);
finish();
}
}
EDIT-----: So I did manage to make it show me users and be able to select some, and to send me back the selected users to my app but there is a slight problem. "Uri.parse("picker://friend");" doesn't give me the list of my friends, but only a list of the friends that I have and have my app installed.
I followed this example: https://developers.facebook.com/docs/android/scrumptious/show-friends but I am trying to modify it, so basically I took out the selectionActivity and Fragment. So I have from my activity a button that calls the PickerActivity which contains FriendPickerFragment. I can select my friends from there, but back in my activities onActivityResult i get back "data" as null.
I have an Application class in my app, where i save the FB session, and also have the login function in there.
In my MainActivity onCreate I have this:
MyApp.getInstance().facebookLogin(PSAddFriendsActivity.this, new CrudStateCallback() {
#Override
public void onResponse(final String string) {
Log.i("", "session : session is opened? : " + MyApp.getInstance().fbSession.getAccessToken());
}
});
After having logged in, I instantiate a list with the current friends I have in my app, and the first position of this list is a FB button:
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
if(position == 0){
startPickerActivity(PSPickerActivity.FRIEND_PICKER, 0);
}else if(position ==1){
//TODO: OPEN CONTACTS PAGE TO ADD FRIENDS
}
}
This is my onACtivityResult and the "startPickerActivity" from this class:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Log.i("","--------------data is : " + data);
Log.i("","--------------resultCode is : " + resultCode);
Log.i("","--------------requestCode is : " + requestCode);
}
public void startPickerActivity(Uri data, int requestCode) {
Intent intent = new Intent();
intent.setData(data);
intent.setClass(PSAddFriendsActivity.this, PickerActivity.class);
startActivityForResult(intent, requestCode);
}
This is the PickerActivity, how I took it from FB:
public class PickerActivity extends FragmentActivity{
private FriendPickerFragment friendPickerFragment;
public static final Uri FRIEND_PICKER = Uri.parse("picker://friend");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pickers);
Bundle args = getIntent().getExtras();
FragmentManager manager = getSupportFragmentManager();
Fragment fragmentToShow = null;
Uri intentUri = getIntent().getData();
if (FRIEND_PICKER.equals(intentUri)) {
if (savedInstanceState == null) {
friendPickerFragment = new FriendPickerFragment(args);
} else {
friendPickerFragment =
(FriendPickerFragment) manager.findFragmentById(R.id.picker_fragment);
}
// Set the listener to handle errors
friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> fragment,
FacebookException error) {
PSPickerActivity.this.onError(error);
}
});
// Set the listener to handle button clicks
friendPickerFragment.setOnDoneButtonClickedListener(
new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
finishActivity();
}
});
fragmentToShow = friendPickerFragment;
} else {
// Nothing to do, finish
setResult(RESULT_CANCELED);
finish();
return;
}
manager.beginTransaction()
.replace(R.id.picker_fragment, fragmentToShow)
.commit();
}
private void onError(Exception error) {
onError(error.getLocalizedMessage(), false);
}
private void onError(String error, final boolean finishActivity) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.error_dialog_title).
setMessage(error).
setPositiveButton(R.string.error_dialog_button_text,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (finishActivity) {
finishActivity();
}
}
});
builder.show();
}
private void finishActivity() {
setResult(RESULT_OK, null);
finish();
}
#Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
friendPickerFragment.loadData(false);
} catch (Exception ex) {
onError(ex);
}
}
}
#Override
protected void onResume() {
Log.i("", "location test onResume");
super.onResume();
MyApp.getInstance().pref.setIsBackground(this, false);
MyApp.getInstance().startLocationClient();
}
#Override
protected void onPause() {
Log.i("", "location test onPause");
super.onPause();
MyApp.getInstance().pref.setIsBackground(this, true);
}
}
Now I looked over this fragment, do not know if I have to add something or save something from the fragment on "onDoneButtonClicked"? or what exactly, because my main activity does return null as data..
forgot to call this in the finishActivty:
if (FRIEND_PICKER.equals(getIntent().getData())) {
if (friendPickerFragment != null) {
MyApp.getInstance().setSelectedUsers(friendPickerFragment.getSelection());
}
}
Now I can get from my Application the list of selected users.
About my edit, after this i found out that with Graph2.0 you cannot get a list of your whole friendlist. You can only get back the info of friends that also liked the app. It is possible to invite friends to like an app but only if you set it as a Game from the FB developers page