i'm developing a scan Barcode app on android , my application is simple and composed from an activity which contains a button and a textView which will receive the result of the scan.. The app works well but i want that i could realise serial scan in a raw. so after scanning a barcode i need that the capture Activity stay and the appli don't back to the button activity so i can scan the next Barcode. any solution please ?
this is my main java code :
public class MainActivity extends Activity {
private Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan= (Button)findViewById(R.id.btnScan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
});
}
public boolean onTouchEvent(final MotionEvent event) {
IntentIntegrator integrator = new IntentIntegrator();
integrator.initiateScan(null);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
TextView tv = (TextView) findViewById(R.id.scanResult);
tv.setText(data.getStringExtra("SCAN_RESULT"));//this is the result
} else
if (resultCode == RESULT_CANCELED) {
// Handle cancel
} }
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
I had the same problem when I did my scanner activity, and the solution that I found was to make my mainActivity extends Zxing CaptureActivity, like this I overrided handleDecode and I avoided to switch between different activities (as you have to do to obtain your scanner result).
Anyhow, to restart the scanning process after a precedent scan I called the method
restartPreviewAfterDelay(0L)
(that is a method of CaptureActivity) in the onClick function of a button.
Take a look at that method, I think that it is what you need.
i finally found the solution i had just to add this code in the onActivityResult() declaration
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
So after the scan is finished the app is ready to scan again instead of going back to the home activity
Related
The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here
my MainActivity is calling a second activity PopupWindow which contains a listview. when user clicks on listview I need to return that information to first activity (MainActivity). So in MainActivity I have this two methods. the first method calls the second activity the second gets result from second activity
//event listener for authors list menu (popup window)
authorListImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent popupWinIntent = new Intent(getBaseContext(), AuthorsPopup.class);
popupWinIntent.putExtra("allauthors", allAuthors);
startActivity(popupWinIntent);
}
});
//fetching result -- author from AuthorsPopup activity back
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String author = data.getStringExtra("author");
Log.v("author ", author);
}
}
}
this method is outside the onCreate() method. some tutorials suggest to create the avobe method just like onActivityResul() I'm assuming that case it would be inside the onCreate() method. mine is a method declaration. so obiously not executing. In my second activity. I have this
//event listener for authros listview
authorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paren, View view, int position, long id) {
// Log.v("author: ", authorsList[position]);
String author = authorsList[position];
Intent returnResultIntent = new Intent(getBaseContext(), MainActivity.class);
returnResultIntent.putExtra("author", author);
setResult(RESULT_OK, returnResultIntent);
finish();
}
});
what is the proper way to get data back from second activity?
You need to launch the second activity using startActivityForResult(popupWinIntent,1) rather than startActivity(popupWinIntent) and override the onActivityResult method in your first Activity, like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("author");
}
}
}
The first authorListImageView.setOnClickListener code you listed would go in onCreate
1st Activity
How to get value
SharedPreferences sharedPreferences;
sharedPreferences=getSharedPreferences("FileName",0);
sharedPreferences.getString("KEY","DefaultValue");
sharedPreferences.getBoolean("KEY",false);
2nd Activity
How to set or put the value from activity for getting on other activity
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
sharedPreferences=getSharedPreferences("FileName",0);
editor=sharedPreferences.edit();
editor.putString("KEY","Value");
editor.putBoolean("KEY",true);
editor.apply();
I am scanning barcodes and QR codes from an Android app via Intent using the ZXing Library and its port of the Android Application. I added the following two lines in my Gradle dependencies to use the android-integration code without modification:
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
compile 'com.google.zxing:core:3.2.1'
And I am using IntentIntegrator in my Activity to scan a barcode in the onCreate() like this:
integrator = new IntentIntegrator(this);
integrator.setOrientationLocked(false);
integrator.setPrompt(getString(R.string.scanner_text)); // Set the text of the scanner
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(true); // Enable beep in the scanner
integrator.setBarcodeImageEnabled(false); // Do not fetch image from the camera
integrator.initiateScan();
Everything works and I get correct scanned result, but I want a flash button in the lower right corner of the scanner like this:
I can already control the flash using the volume up and down keys because I override the CaptureActivity.
Is a flash button like the one above already there in the barcode scanner which can switch between AUTO, ON and OFF mode? If there is, can I use the addExtra() method of the IntentIntegrator to activate it? Or is the only way to implement this would be to modify the entire code according to my needs?
I had overlooked this page on Embedding BarcodeView and these sample activities which show how to customise the Barcode Scanner according to your needs. The example activity that helped me was CustomScannerActivity.
There isn't a option in the IntentIntegrator class to implement a flash button natively. Instead I should make a custom layout for the Barcode Scanner, use it in a custom activity and call this activity from the IntentIntegrator.
I have two activities. One is the ScannerActivity and other one is the CallingActivity. A mistake that confused me for a while was that I created an instance of IntentIntegrator in the onCreate() method of ScannerActivity. It should be in the CallingActivity.
In the example given a Button is used and the text of the Button is changed according to the flash. I created a new Android Layout called activity_custom_scanner where I replaced the Button with a ToggleButton and used images for the button instead to get my desired Flash On/Off Button.
So my ScannerActivity looks like this:
public class CustomScannerActivity extends Activity implements
CompoundBarcodeView.TorchListener {
private static final int BarCodeScannerViewControllerUserCanceledErrorCode = 99991;
private static final String TAG = CustomScannerActivity.class.getSimpleName();
private CaptureManager capture;
private CompoundBarcodeView barcodeScannerView;
private ToggleButton switchFlashlightButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_scanner);
barcodeScannerView = (CompoundBarcodeView)findViewById(R.id.zxing_barcode_scanner);
barcodeScannerView.setTorchListener(this);
switchFlashlightButton = (ToggleButton)findViewById(R.id.switch_flashlight);
switchFlashlightButton.setText(null);
switchFlashlightButton.setTextOn(null);
switchFlashlightButton.setTextOff(null);
// if the device does not have flashlight in its camera,
// then remove the switch flashlight button...
if (!hasFlash()) {
switchFlashlightButton.setVisibility(View.GONE);
}
switchFlashlightButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Save the state here
if (isChecked) {
barcodeScannerView.setTorchOn();
} else {
barcodeScannerView.setTorchOff();
}
}
});
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
}
#Override
protected void onResume() {
super.onResume();
capture.onResume();
}
#Override
protected void onPause() {
super.onPause();
capture.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
capture.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
capture.onSaveInstanceState(outState);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
/**
* Check if the device's camera has a Flashlight.
* #return true if there is Flashlight, otherwise false.
*/
private boolean hasFlash() {
return getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
#Override
public void onTorchOn() {
// necessary override..
}
#Override
public void onTorchOff() {
// necessary override..
}
}
And the CallingActivity looks like this:
public class CallingActivity extends Activity {
private static final String TAG = CallingActivity.class.getSimpleName();
private static final int BarCodeScannerViewControllerUserCanceledErrorCode = 99991;
String uuid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uuid = getIntent().getStringExtra("uuid");
new IntentIntegrator(this).setOrientationLocked(false).setCaptureActivity(CustomScannerActivity.class).initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
if (scanResult != null) {
// handle scan result
Log.i(TAG, "Text from Barcode Scanner: " + scanResult.getContents());
getIntent().putExtra("data", scanResult.getContents());
getIntent().putExtra("uuid", uuid);
}
}
else if (resultCode == RESULT_CANCELED) {
getIntent().putExtra("error", "User canceled");
getIntent().putExtra("error_code", BarCodeScannerViewControllerUserCanceledErrorCode);
}
else
{
getIntent().putExtra("error", getString(R.string.scanner_error));
getIntent().putExtra("error_code", BarCodeScannerViewControllerUserCanceledErrorCode);
}
setResult(resultCode, this.getIntent());
this.finish();
}
}
I am not sure if it's the perfect way, but that's how I did it.
Hope it helps someone!
There is a setTorchOn method in CompoundBarcodeView so you can check that method out and try to implement it for your needs. Hope it helps.
This question is probably too old, but you can use the Volume buttons to turn on/off the torch while scanning.
I am trying to create a simple grade tracker for android. The way I have it set up is that the user has a list of classes that are in their major. When they click on the title of the class, a new activity starts that has the name of the class, the catalog description, a space to place your grade, and a button to return to the list of classes.
What I would like to do is save the grade number that they input on the second page, and when the button is pressed, on the first page the grade is shown next to the course title.
I have edited to the code to reflect the comments given.
This is the code that works!
CoreClasses
TextView eng101, eng101scr;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.classcore);
eng101 = (TextView)findViewById(R.id.eng101);
eng101scr = (TextView)findViewById(R.id.eng101CoreScr);
eng101.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(ClassCore.this, Eng101.class);
i.putExtra("grades", "eng101" );
startActivityForResult(i, 1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(data.getExtras().containsKey("e101FinalScore")){
eng101scr.setText(data.getStringExtra("e101FinalScore"));
}
Eng101
public class Eng101 extends Activity {
Button btnSubmit;
EditText userGrade;
String strGrade;
OutsideVariables outside = new OutsideVariables();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.eng101);
btnSubmit = (Button)findViewById(R.id.btnE101);
userGrade = (EditText)findViewById(R.id.eng101Scr);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
strGrade = userGrade.getText().toString();
Intent i = getIntent();
String msg = i.getStringExtra("grades");
if(msg.contentEquals("eng101")){
i.putExtra("e101FinalScore", strGrade);
setResult(RESULT_OK, i);
finish();
}
}
});
}
}
You can pass the values to the previous activity by,
Intent intent = new Intent(Eng101.this, ClassCore.class);
intent.putExtra("grade",grade);
startActivity(new Intent(Eng101.this, ClassCore.class));
and in ClassCore you can get the value grade by,
Bundle extras = getIntent().getExtras();
// get data via the key
if(extras!=null){
int value1 = intent.getIntExtra("grade", 0);
if (value1 != null) {
eng101scr.setText(value1);
}
}
Because you're using an instance, each new instance will have it's own storage and values. What you're looking to do is actually much simpler than this, and it's to do everything using static access.
However, the better way to do this would be to create some sort of class like your OutsideVariables and pass an instance into your new activity, that way you're able to access them in both. Take a look at this other post for some more information. How to pass the values from one activity to previous activity
EDIT: onClick is working properly now. The issue was that the button was trying to fire the onClick from the Parent class. now that is fixed. Of course that means a new issue is happening, that is the onActivityResult is never getting called.
So I am not really sure what the hell is going on, when I hit the button nothing happens, nothing in logcat, nothing, as if there is not code, but I am pretty sure this is written correctly, any thoughts?
public class myClass extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_selector);
Button getStore = (Button)findViewById(R.id.getStore);
getStore.setOnClickListener(buttonGetStoreOnClickListener);
}
Button.OnClickListener buttonGetStoreOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
Intent intent = new Intent("com.blah.Blah.client.android.SCAN");
intent.setPackage("com.blah.Blah");
intent.putExtra("com.blah.Blah.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
};
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Log.i("debug tag", "contents: "+contents+" format: "+format);
Intent myIntent = new Intent(this, Ads.class);
myIntent.putExtra("key", contents);
startActivity(myIntent);
setContentView(R.layout.activity_ads);
// Handle successful scan
}
else if (resultCode == RESULT_CANCELED)
{
// Handle cancel
Log.i("xZing", "Cancelled");
}
}
}
};
This is the class you need to import:
import android.view.View.OnClickListener;
And this is the method you should have:
OnClickListener onButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
};
Test it and let me know if it worked.
Regards
Are you sure you got the right button with Button getStore = (Button)findViewById(R.id.getStore); ?
If yes, then it can be something that sometimes happens to me sometimes.
When this happens, my logcat doesn't show anything. What I do to solve this, is to open the Devices view (Window, show view, other, Android, Devices) and select my device. Then when I look at the logcat again, everything's there.