I am designing an app for scan Barcode. There are three activities where I have used Barcode Scanner, only in one Activity the code is working fine and other two activities its taking too much time to scan and some times scans but displaying wrong result.
I am very confused about what the problem is. Same code I have copy paste in all three activities.
build.gradle:
compile 'me.dm7.barcodescanner:zxing:1.9'
Code:
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class ScanBoxActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView scannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
#Override
public void onResume()
{
super.onResume();
if(scannerView== null)
{
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
}
#Override
public void onDestroy(){
super.onDestroy();
scannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
final String scanResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
Toast.makeText(ScanBoxActivity.this,""+scanResult,Toast.LENGTH_SHORT).show();
}
});
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
onResume();
}
});
builder.setMessage(scanResult);
AlertDialog alert = builder.create();
alert.show();
}
}
compile 'com.edwardvanraak:MaterialBarcodeScanner:0.0.6-ALPHA'
compile 'com.google.android.gms:play-services-vision:11.0.4'
This library has google support and easy to implement and I have implemented it in one of my app. So, if you face any further issue , ask me freely.
DO you have samples of the code you used AYUSH ARYA to share or maybe an e m a i l?
Related
I have a strange problem implementing Google Reward Video. In test mode (with google ad-id) works perfect first time, but not loading video in the second time. In production (with my ids) not loading video at all. Here is my code:
import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import eu.healthydev.quizhero.Common.Common;
import eu.healthydev.quizhero.Model.Question;
import eu.healthydev.quizhero.Model.QuestionScore;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
public class DoneActivity extends AppCompatActivity implements RewardedVideoAdListener{
Button btnTryAgain, exit_game;
TextView txtResultScore, getTxtResultQuestion;
ProgressBar progressBar;
FirebaseDatabase database;
DatabaseReference question_score;
//VideoAd Award
private static final String AD_UNIT_ID = "ca-app-pub-5883754622051955/6179215953";
private static final String APP_ID = "ca-app-pub-5883754622051955~8837168889";
private int coinCount;
private TextView coinCountText;
private RewardedVideoAd rewardedVideoAd;
private Button showVideoButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_done);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this, APP_ID);
rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
rewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
database = FirebaseDatabase.getInstance();
question_score = database.getReference("Question_Score");
txtResultScore = (TextView)findViewById(R.id.txtTotalScore);
getTxtResultQuestion =(TextView)findViewById(R.id.txtTotalQuestion);
progressBar = (ProgressBar)findViewById(R.id.doneProgressBar);
// Create the "retry" button, which tries to show an interstitial between game plays.
btnTryAgain = (Button)findViewById(R.id.btnTryAgain);
exit_game = (Button) findViewById(R.id.exit_game);
btnTryAgain.setVisibility(View.INVISIBLE);
btnTryAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DoneActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
showVideoButton = findViewById(R.id.show_video_button);
showVideoButton.setVisibility(View.VISIBLE);
showVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRewardedVideo();
}
});
exit_game.setVisibility(View.VISIBLE);
exit_game.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
// Display current coin count to user.
coinCountText = findViewById(R.id.coin_count_text);
coinCount = 0;
coinCountText.setText("Coins: " + coinCount);
//Get data from bundle and set view
Bundle extra = getIntent().getExtras();
if(extra != null)
{
int score = extra.getInt("SCORE");
int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtResultScore.setText(String.format("SCORE : %d", score));
getTxtResultQuestion.setText(String.format("PASSED : %d /%d", correctAnswer,totalQuestion));
progressBar.setMax(totalQuestion);
progressBar.setProgress(correctAnswer);
//Upload points to Database
question_score.child(String.format("%s_%s", Common.currentUser.getUserName(),
Common.categoryID))
.setValue(new QuestionScore(String.format("%s_%s", Common.currentUser.getUserName(),
Common.categoryID),
Common.currentUser.getUserName(),
String.valueOf(score),
Common.categoryID,
Common.categoryName));
}
}
private void loadRewardedVideoAd() {
if (!rewardedVideoAd.isLoaded()) {
rewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
}
}
private void addCoins(int coins) {
coinCount += coins;
coinCountText.setText("Coins: " + coinCount);
}
private void showRewardedVideo() {
showVideoButton.setVisibility(View.INVISIBLE);
exit_game.setVisibility(View.INVISIBLE);
if (rewardedVideoAd.isLoaded()) {
rewardedVideoAd.show();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
// Preload the next video ad.
loadRewardedVideoAd();
btnTryAgain.setVisibility(View.INVISIBLE);
showVideoButton.setVisibility(View.VISIBLE);
exit_game.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
Toast.makeText(this, "Ad Video Failed to Load", Toast.LENGTH_SHORT).show();
showVideoButton.setVisibility(View.VISIBLE);
exit_game.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewarded(RewardItem reward) {
Toast.makeText(this,
String.format(" You ve got one free try!", reward.getType(),
reward.getAmount()),
Toast.LENGTH_SHORT).show();
btnTryAgain.setVisibility(View.VISIBLE);
showVideoButton.setVisibility(View.INVISIBLE);
exit_game.setVisibility(View.INVISIBLE);
addCoins(1);
Intent intent = new Intent(DoneActivity.this, HomeActivity.class);
startActivity(intent);
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
System.exit(0);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
I double checked my ids and are correct. Probably my code too as it works ane time exactly as it has to do. I will appriciate any help or idea.
From: https://developers.google.com/admob/android/rewarded-video
#Override
public void onRewardedVideoAdClosed() {
// Load the next rewarded video ad.
loadRewardedVideoAd();
}
We need to re-load once the first one is closed.
My app is working fine due to same. Hope that helps.
I don't understand why my "App" has stopped working?
This is my MainActivity.class code:-
package com.apps.nishant.iwillguessyournumber;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button btnplay = (Button)findViewById(R.id.cmdPlay);
private Button btnexit = (Button)findViewById(R.id.cmdExit);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnButtonClickListener();
}
public void OnButtonClickListener() {
btnplay.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
btnexit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setMessage("Do you really wanna exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
}
);
}
}
and my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.apps.nishant.iwillguessyournumber.MainActivity">
<Button
android:id="#+id/cmdPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
tools:layout_editor_absoluteX="147dp"
tools:layout_editor_absoluteY="219dp" />
<Button
android:id="#+id/cmdExit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
tools:layout_editor_absoluteX="147dp"
tools:layout_editor_absoluteY="328dp" />
</android.support.constraint.ConstraintLayout>
Whenever I am running this app on Genymotion Android:6.0.0 and API 23, it is showing "Unfortunately, (app name) is not working"
What is the problem in my code/platform?
I've tried restarting my apps, looked up a few questions but couldn't yet get my answer when I open a new Activity using Intent, the second activity can't parse the xml file.
The source of your app crash is the following 2 lines,
private Button btnplay = (Button)findViewById(R.id.cmdPlay);
private Button btnexit = (Button)findViewById(R.id.cmdExit);
The method findViewById() should be called inside the onCreate() after the setContentView(). The following code should work,
package com.apps.nishant.iwillguessyournumber;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button btnplay;
private Button btnexit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnplay = (Button)findViewById(R.id.cmdPlay);
btnexit = (Button)findViewById(R.id.cmdExit);
OnButtonClickListener();
}
public void OnButtonClickListener() {
btnplay.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
btnexit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setMessage("Do you really wanna exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
}
);
}
}
I've created an Activity with a Navigation Drawer and replaced the options icon (placed in the top-right corner) with an ImageButton to handle the back click.
The problem is, that I don't know how to do it. I'm a little confused about how to use the back button. What code should I do to go to the previous Activity?
A back button for:
Activity to Another Activity and MainActivity to Fragment activity.
this is my Manifest code:
<activity
android:name="com.teamamazing.with_sidebar.activity.Accomodation"
android:label="Accomodation"
android:parentActivityName="com.teamamazing.with_sidebar.activity.SpecialPage">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.teamamazing.with_sidebar.activity.SpecialPage" />
</activity>
this is my Accommodation activity:
package com.teamamazing.with_sidebar.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.teamamazing.with_sidebar.R;
public class Accomodation extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accomodation);
} }
and this is my SpecialPage code: which will be the parent activity.
package com.teamamazing.with_sidebar.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import com.teamamazing.with_sidebar.R;
public class SpecialPage extends AppCompatActivity {
public ImageButton accomodation;
public void init() {
accomodation = (ImageButton) findViewById(R.id.AccomodationButton);
accomodation.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent accomodation = new Intent(SpecialPage.this, Accomodation.class);
startActivity(accomodation);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_special_page);
init();
}}
Thank you for the answer.
You can use onBackPressed() or finish() Method.
buttonClickOBJ.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onBackPressed();
}
});
onBackPressed ()
Called when the activity has detected the user's press of the back
key. The default implementation simply finishes the current activity,
but you can override this to do whatever you want.
You can also use the following method.
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Easy way
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.app_name);
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("If You Enjoy The App Please Rate us?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent play =
new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=kd.travellingtips"));
startActivity(play);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Firstly, Add the Listener to the button you want to associate with it. Then initiate a back-press option within the method.
This question already has answers here:
Receive result from DialogFragment
(15 answers)
Closed 9 years ago.
I want the DialogFragment to return a value to me that was entered in editQuantity when dismissed.
But i am not getting any way to make it work. I can do this by passing the value through the intent but that destroys the progress of the current activity.
Is there any way other than passing through intent that will return me value?
package com.example.myprojectname;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
public class QuantityDialogFragment extends DialogFragment implements OnClickListener {
private EditText editQuantity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
editQuantity = new EditText(getActivity());
editQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.app_name)
.setMessage("Please Enter Quantity")
.setPositiveButton("OK", this)
.setNegativeButton("CANCEL", null)
.setView(editQuantity)
.create();
}
#Override
public void onClick(DialogInterface dialog, int position) {
String value = editQuantity.getText().toString();
Log.d("Quantity: ", value);
dialog.dismiss();
}
}
Assuming that you want to foward result to the calling Activity:) try this code snippet:
public class QuantityDialogFragment extends DialogFragment implements OnClickListener {
private EditText editQuantity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
editQuantity = new EditText(getActivity());
editQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
return new AlertDialog.Builder(getActivity()).setTitle(R.string.app_name).setMessage("Please Enter Quantity")
.setPositiveButton("OK", this).setNegativeButton("CANCEL", null).setView(editQuantity).create();
}
#Override
public void onClick(DialogInterface dialog, int position) {
String value = editQuantity.getText().toString();
Log.d("Quantity: ", value);
MainActivity callingActivity = (MainActivity) getActivity();
callingActivity.onUserSelectValue(value);
dialog.dismiss();
}
}
and on Your activity add :
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuantityDialogFragment dialog = new QuantityDialogFragment();
dialog.show(getSupportFragmentManager(), "Dialog");
}
/**
* callback method from QuantityDialogFragment, returning the value of user
* input.
*
* #param selectedValue
*/
public void onUserSelectValue(String selectedValue) {
// TODO add your implementation.
}
}
Taking this idea a little further, I created a listener interface inside the dialog and implemented it in the main activity.
public interface OnDialogResultListener {
public abstract void onPositiveResult(String value);
public abstract void onNegativeResult();
}
public void setOnDialogResultListener(OnDialogResultListener listener) {
this.onDialogResultListener = listener;
}
Call onNegativeResult() inside an overriden onCancel(DialogInterface) and onPositiveResult(String) where you want your dialog to return the value.
Note: don't forget to dismiss() your dialog after calling onPositiveResult() or the dialog window will stay opened.
Then inside your main activity you can create a listener for the dialog, like so:
QuantityDialogFragment dialog = new QuantityDialogFragment();
dialog.setOnDialogResultListener(new QuantityDialogFragment.OnDialogResultListener() {
#Override
public void onPositiveResult(String value) {
//Do something...
}
#Override
public void onNegativeResult() {
//Do something...
}
});
This will make your dialog easier to reuse later.
I'm new at Eclipse and the Android applications making so here comes a very rookie question. How can I make this function work properly? I have just copy > paste it to my public class nowActivity extends Activity { and fixed the errors that accord. The function is as follows:
package weather.right;
import weather.right.now.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class nowActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
public void goToSo(View view) {
goToUrl("http://erik-edgren.nu/weather");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Thanks in advance.
protected void onCreate1(Bundle savedInstanceState) should be protected void onCreate(Bundle savedInstanceState)?
You are supposed to override the onCreate() method. See this for more details.
For Android, sub-classes of Activity are supposed to implement certain methods so to do this you have to override certain methods by matching the parent class' methods exactly. onCreate() is one such method.
For the emulator, GPS can be tested by following the guide here. Otherwise it will show up as disabled.