I am developping an application which convert scanned data (barcode) to GoogleSheet data, and I am trying to transfer the barcode number (from Page2.java) into another java file (ListItem.java)
I saw that a usual way to do it is to create intents. So I did it.
But the toast I put in ListItem.java gives me "null" instead of the scanned number (for example 0123456789012)
Please, can you tell me where am I wrong ? Thank you so much !
1st Code (Page2.java , where I get "scanContent2", the variable I need) :
public class Page2 extends Activity implements OnClickListener {
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
scanBtn2 = (Button) findViewById(R.id.scan_button2);
scanBtn2.setOnClickListener(this);
}
public Button scanBtn2;
public String scanContent2;
#Override
public void onClick(View v) {
if (v.getId() == R.id.scan_button2) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
scanContent2 = scanningResult.getContents();
Intent intenta = new Intent(getApplicationContext(),ListItem.class);
intenta.putExtra("theScanContent2", scanContent2);
startActivity(intenta);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
2nd code (ListItem.java, where I get "null" on the toast) :
public class ListItem extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
String scanContent2 = getIntent().getStringExtra("theScanContent");
Toast toast = Toast.makeText(getApplicationContext(),
"BarCode number: " + scanContent2, Toast.LENGTH_SHORT);
toast.show();
}
}
In the Listitem.java in the following line,
String scanContent2 = getIntent().getStringExtra("theScanContent");
You are trying to get String with key theScanContent, while you are putting scanContent2 with key theScanContent2 in Page2.java in line
intent.putExtra("theScanContent2", scanContent2);
Make sure the keys are same for the Intent while putting the data in intent and accessing the data from the intent to avoid getting null Results.
Related
I am trying to make my app to accept videos from the phone's library to be uploaded and converted into GIF format. My code is giving out this build error though:-
error: <anonymous com.example.bim.Video2gif$2> is not abstract and does not override abstract method onReschedule(String,ErrorInfo) in UploadCallback
and also this warning on my onActivityResult method:-
Overriding method should call super.onActivityResult
The code is as below : -
public class Video2gif extends AppCompatActivity {
private Button uploadBtn;
private ProgressBar progressBar;
private int SELECT_VIDEO = 2;
private ImageView img1;
private DownloadManager downloadManager;
private Button download_btn;
private String gifUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video2gif);
MediaManager.init(this);
progressBar = findViewById(R.id.progress_bar);
MediaManager.init(this);
img1 = findViewById(R.id.img1);
uploadBtn = findViewById(R.id.uploadBtn);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickVideoFromGallery();
}
private void pickVideoFromGallery() {
Intent GalleryIntent = new Intent();
GalleryIntent.setType("video/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(GalleryIntent,
"select video"), SELECT_VIDEO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode == SELECT_VIDEO && resultCode == RESULT_OK) {
Uri selectedVideo = data.getData();
MediaManager.get()
.upload(selectedVideo)
.unsigned("myid")
.option("resource_type", "video")
.callback(new UploadCallback(){
#Override
public void onStart(String requestId) {
progressBar.setVisibility(View.VISIBLE);
Toast.makeText(Video2gif.this,
"Upload Started...", Toast.LENGTH_SHORT).show();
}
public void onProgress() {
}
public void onSuccess(String requestId, Map resultData) {
Toast.makeText(Video2gif.this, "Uploaded Succesfully",
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
uploadBtn.setVisibility(View.INVISIBLE);
String publicId = resultData.get("public_id").toString();
gifUrl = MediaManager.get().url().resourceType("video")
.transformation(new Transformation().videoSampling("25")
.delay("200").height(200).effect("loop:10").crop("scale"))
.resourceType("video").generate(publicId+".gif");
Glide.with(getApplicationContext()).asGif().load(gifUrl).into(img1);
download_btn.setVisibility(View.VISIBLE);
}
public void onError(String requestId, ErrorInfo error) {
Toast.makeText(Video2gif.this,
"Upload Error", Toast.LENGTH_SHORT).show();
Log.v("ERROR!!", error.getDescription());
}
});
}
}
}
I am also using Cloudinary to help process the video to GIF. Any help would be appreciated, many thanks!
When you’re using interfaces in android you need to include in your activity/fragment (override) the callback methods that they include. Also overriding some of the system methods requires you calling their super which means that many activities might be listening for the same callback when they inherit from one another. By adding the super in those callbacks you allow the result to travel through all of them. So in the case of the OnActivityResult just add the following line in your method:
super.onActivityResult(requestCode, resultCode, data);
For onReschedule you can let Android Studio generate that for you. Just go to Code->Generate-Override Methods and select the onReschedule
So I have the zxing barcode scanner running and in my main activity I have the onResultActivity function telling my activity to push to a new activity with a result from the scanner.
The problem is that my scanner just scans any old QR code regardless of what it is.
I need the scanner to only accept my QR code to pass a successful result and ignore all other QR codes (this should pass a toaster to say "incorrect QR code, try again").
Here's what I currently have:
MainActivity
...
static final int SCAN_RESULT = 1; // The request code
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check which request we're responding to
if (requestCode == SCAN_RESULT) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Action to take if result successful
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
ScannerActivity
...
public class ScanBarcodeActivity extends AppCompatActivity {
Button mBtnClose;
private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
private ViewfinderView viewfinderView;
private void initViews() {
mBtnClose = findViewById(R.id.barcode_header_close);
barcodeScannerView = findViewById(R.id.zxing_barcode_scanner);
viewfinderView = findViewById(R.id.zxing_viewfinder_view);
}
private void initListener() {
mBtnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
initViews();
initListener();
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
changeMaskColor(null);
}
#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);
}
public void changeMaskColor(View view) {
}
}
EDIT: I've tried this but it's obviously not working, this is basically what I'm looking to get working. If the SCAN_RESULT = the QR_CODE then go to next activity, else pop a message saying try again.
static final int SCAN_RESULT = 1; // The request code
String QR_CODE = "EC0111-1234567899";
int RESULT = Integer.parseInt(QR_CODE);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check which request we're responding to
if (requestCode == SCAN_RESULT) {
// Make sure the request was successful
if (SCAN_RESULT == RESULT) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
} else {
Toast.makeText(this, "Incorrect QR code, please try again", Toast.LENGTH_LONG).show();
}
}
}
There are some approaches you can try.
Encrypt information: You can encrypt information coded in QR so that other can't read it as well as you can identify your own QR. To do so
Encrypt information with a key
Generate QR with encrypted information
Read and try to decrypt information. If you can decrypt than it's your QR.
Develop your own QR: It may be costly for you but it is a wonderful idea to generate your own styled QR like facebook messenger , snapchat and whatsapp etc. In that case you can't use standard ZXING library. You have to customised ZXING library or develop a new one.
Add tag to information: You can add a unique tag(text) in your QR information. By which you can identify your QR code.
I't trying to implement a local VpnService to have my app do some tasks, but I'm a little confused as to how to stop it one it started. The VpnService class and client activity are based on this repo:
https://github.com/hexene/LocalVPN
The caller activity is basically this:
public class MainActivity extends AppCompatActivity {
private static final int VPN_REQUEST_CODE = 0x0F;
private boolean waitingForVPNStart;
private BroadcastReceiver vpnStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (LocalVPNService.BROADCAST_VPN_STATE.equals(intent.getAction()))
if (intent.getBooleanExtra("running", false))
waitingForVPNStart = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button vpnButton = (Button)findViewById(R.id.vpn);
vpnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVPN();
}
});
final Button vpnStopButton = (Button)findViewById(R.id.stopVpnButton);
vpnStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopVPN();
}
});
waitingForVPNStart = false;
LocalBroadcastManager.getInstance(this).registerReceiver(vpnStateReceiver,
new IntentFilter(LocalVPNService.BROADCAST_VPN_STATE));
}
private void startVPN() {
Intent vpnIntent = VpnService.prepare(this);
if (vpnIntent != null)
startActivityForResult(vpnIntent, VPN_REQUEST_CODE); //Prepare to establish a VPN connection. This method returns null if the VPN application is already prepared or if the user has previously consented to the VPN application. Otherwise, it returns an Intent to a system activity.
else
onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VPN_REQUEST_CODE && resultCode == RESULT_OK) {
waitingForVPNStart = true;
startService(new Intent(this, LocalVPNService.class));
enableButton(false);
}
}
What confuses me is: how would I call the service's onDestroy() method or something similar if I don't keep an instance if it in my main activity?
I looked at this answer and this and seen implementations of stopService, but I'm not sure how to handle the Intent, because it's not only used to call startService() but also involved in calling VpnService.prepare().
Edit: I tried
stopService(new Intent(this, LocalVPNService.class)); but it doesn't stop it. I tried stopService(vpnIntent); and IT WORKS, but makes my app crash/close.
In your LocalVPNService class create a new broadcast:
private BroadcastReceiver stopBr = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if ("stop_kill".equals(intent.getAction())) {
stopself();
}
}
};
and in the onCreate method add this:
LocalBroadcastManager lbm =
LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(stopBr, new IntentFilter("stop_kill"));
in your activity:
Intent intent = new Intent("stop_kill");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
So I'm trying to build a QR Code Scanner, but my result only showing a text. Even the QR Code is have a URL link on it. It can't be open to a browser.
Here's my code for the scanner:
public class ReaderActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
Button scan_btn = findViewById(R.id.scan_btn);
final Activity activity = this;
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}}
What should I add or change to get clickable URL result? Can someone fix this? Please help me to get my project done. I really need it.
You will get QR results on result.getContents() as soon as you get it you should have to use action intent for view to open URL in browser
Hi I'm new in Android Development.
I have doing a lot of research .
Everything go rights however there is no any output sound from the text I entered.
Did I miss out any important part ?
The following bellow is the coding :
public class SpeechTextActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
inputText = (EditText) findViewById(R.id.edit_speechText);
speakButton = (Button) findViewById(R.id.btn_speechOut);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(SpeechTextActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(SpeechTextActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(SpeechTextActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}
Just now I test in my tablet it work! But in my phone not workable =(
Change the implements OnInitListener to TextToSpeech.OnInitListener.
Try to unplug the USB cable from your phone before testing. TTS is recognized to encountered some issues in debug mode.