How to prevent method to be called twice? - java

I want to check programmatically whether the function is called or not. If it is called before, then do not allow and ignore to be called for the second time, if not then let button to call. Why i need to do this is because of i have a longClick button to run certain functionality, if user forgot to do this then however user will click another button which i will place the same functionality. I need to prevent running same function for twice.
public class ActivityA extends Activity{
private static boolean isScreenShotTaken = false;
blankcard.setOnLongClickListener(new OnLongClickListener() {
if(!isScreenShotTaken)
{
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
isScreenShotTaken = true;
}
return false;
}
});
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Templates.this, MailCard.class);
intent.putExtra("name", Name);
if(!isScreenShotTaken)
{
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
isScreenShotTaken = true;
}
startActivity(intent);
}
});
public Bitmap takeScreenshot() {
// code exist here
//if called once, second call ignore
}
public void saveBitmap(Bitmap bitmap) {
// code exist here
//if called once, second call ignore
}
}
Thank you for suggestions.

My version:
I'd write it so:
// In the declaration section of your class.
private static boolean isScreenShotTaken = false;
// In the code.
btnsend.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(!isScreenShotTaken)
{
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
isScreenShotTaken = true;
}
}
}
);
blankcard.setOnLongClickListener
(
new OnLongClickListener()
{
#Override
public boolean onLongClick(View arg0)
{
if(!isScreenShotTaken)
{
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
isScreenShotTaken = true;
}
}
}
);

simple:
public Bitmap takeScreenshot() {
// before start
blankcard.setEnabled(false);
btnsend.setEnabled(false);
// do your sutff
... here ...
// at the end
blankcard.setEnabled(true);
btnsend.setEnabled(true);
}
if you're using an AsyncTask or similar, put those calls in preExecute and postExecute

If you have a button
once the button is pressed on .. In onclickListener
button.setclickable(false);
then button can't be pressed .
and if you have some method. than take a gloabal boolean variable
boolean isFirstTime= false;
and once you get into the method set it to true;
isFirstTime= true;

Why dont you use a global flag variable??
something like,
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
if(flag == true)
{
public void onClick(View v) {
// TODO Auto-generated method stub
// Bitmap bitmap = takeScreenshot();
// saveBitmap(bitmap);
flag = 1;
}
}
});
So even though setOnClickListener is called, it wont execute the code within.

Related

How to start looping a function after button was pressed

I'm making an android application that serves as house guard. For now it works like this: after pressing a button it takes picture without intent, compare it with the picture taken last time, if there's a significant difference it saves it, sends sms and uploads picture using ftp. I'm new to Java and Android...
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
[...]
//Take a picture
view.findViewById(R.id.capture_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Take picture using the camera without preview.
//...wanted to put here for loop but didn't work
takePicture();
}
}
return view;
}
// ----------------------------------------------------
protected void takePicture() {
if (mCameraPreview != null) {
if (mCameraPreview.isSafeToTakePictureInternal()) {
mCameraPreview.takePictureInternal();
}
} else {
throw new RuntimeException("Background camera not initialized. Call startCamera() to initialize the camera.");
}
}
// ----------------------------------------------------
#Override
public void onImageCapture(#NonNull File imageFile) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap1 = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
// here it compares last and old picture
[...]
// if comparison failed alert
new FtpTask().execute(path);
sendSMS("767555444", "ALARM ALARM");
}
// ----------------------------------------------------
void takePictureInternal() {
safeToTakePicture = false;
if (mCamera != null) {
mCamera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] bytes, Camera camera) {
new Thread(new Runnable() {
#Override
public void run() {
//Convert byte array to bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//Rotate the bitmap
Bitmap rotatedBitmap;
if (mCameraConfig.getImageRotation() != CameraRotation.ROTATION_0) {
rotatedBitmap = HiddenCameraUtils.rotateBitmap(bitmap, mCameraConfig.getImageRotation());
//noinspection UnusedAssignment
bitmap = null;
} else {
rotatedBitmap = bitmap;
}
//Save image to the file.
if (HiddenCameraUtils.saveImageFromFile(rotatedBitmap,
mCameraConfig.getImageFile(),
mCameraConfig.getImageFormat())) {
//Post image file to the main thread
new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCameraCallbacks.onImageCapture(mCameraConfig.getImageFile());
}
});
} else {
//Post error to the main thread
new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCameraCallbacks.onCameraError(CameraError.ERROR_IMAGE_WRITE_FAILED);
}
});
}
mCamera.startPreview();
safeToTakePicture = true;
}
}).start();
}
});
} else {
mCameraCallbacks.onCameraError(CameraError.ERROR_CAMERA_OPEN_FAILED);
safeToTakePicture = true;
}
}
What I want to achieve is that after button press it starts the loop in which pictures are taken and compared again and again until I stop by clicking the button. I don't want new loop to start before old one is still being processed (image comparison pixel by pixel takes time). Being more precise, I want to ask where exactly should I add a loop to make it works?
Sorry if there is too much or too little code. If I forgot to add something please tell me and I'll upload.
it sounds like you will be better off with the camera capture session.
See this article - it should help you understand what you can do: https://medium.com/androiddevelopers/understanding-android-camera-capture-sessions-and-requests-4e54d9150295

Android App StartApp Ads Error

I made a game and used an ads company on it (StartApp). I wanna use Interstitial Ads on it. I followed the step they show but can't achieve it. I'm getting error. Here is the LogCat:
http://i.stack.imgur.com/SaIXE.png
Here is the codes:
GameActivity.java
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException
{
StartAppAd.init(this, "10254544", "20454573");
}
MenuScene.java
private StartAppAd startAppAd = new StartAppAd(activity);
#Override
public void createScene() {
startAppAd.showAd();
startAppAd.loadAd();
}
Check the Manifest.xml file. Be sure you wrote the right package name in there.
Try This code and u should update manifest file also
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartAppSearch.showSearchBox(this);
StartAppAd.init(this, "107181003", "211487617");
StartAppSearch.init(this, "107181003", "211487617");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); //load next add
Intent intent=new Intent(getApplicationContext(),Second.class);
startActivity(intent);
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
boolean _active = true;
}
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
startAppAd.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
startAppAd.onResume();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private StartAppAd startAppAd = new StartAppAd(this);
#Override
public void onBackPressed() {
startAppAd.onBackPressed();
super.onBackPressed();
}
and update in manifest file also
You can not use the
startAppAd.showAd();
startAppAd.loadAd();
inside the Scene class (MenuScene). Instead you can try below method.
In GameActivity class you must be having KeyEvent method. put the code to show the startApp ads in there as below,
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
if(SceneManager.getInstance().getCurrentSceneType().toString() == "SCENE_MENU"){
try{
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); // load the next ad
}catch(Exception e){
}
}
try{
SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
}catch(Exception e){
}
}
return false;
}
Regards,
Deepak

Get user location on tap/longpress on the screen mapforge API

I would like to get user location when I tap/longpress on the screen using the mapforge API...
this code is not fired even if I longpressed on the screen.
mapView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
toastLong("onlongclick");
return false;
}
});
With Little Modify
mapView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Long Clicked is working ", Toast.LENGTH_SHORT).show();
return true;
}
});

Setting background of imageView in RelativeLayout

I am setting a background of an imageView of a relative layout using Helper.sync_settting_2(img_sync, context).
try {
final RelativeLayout layout_img_sync = (RelativeLayout) findViewById(R.id.relative_lay_6);
final ImageView img_sync = (ImageView) findViewById(R.id.img_sync);
layout_img_sync.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Helper.sync_settting_2(img_sync, context);
}
});
} catch (Exception e) {
};
Here is the function Helper.sync_settting_2(ImageView sync, Context ct).
public static void sync_settting_2(ImageView sync, Context ct) {
Toast.makeText(ct, "Sync Started", Toast.LENGTH_LONG).show();
getJobData getJobs = new getJobData(null);
sync.setBackground(ct.getResources().getDrawable(
com.org.courier.R.drawable.sync_image_orange));
getJobs.setOnApiLIstner(new onApiCompleted() {
#Override
public void onApiResults(ArrayList<job_entity> events_list) {
getMessageData getMessage = new getMessageData(null);
getMessage.setOnApiLIstner(new getMessageData.onApiCompleted() {
#Override
public void onApiResults(
ArrayList<message_entity> events_list) {
getContactData getContact = new getContactData(null);
getContact
.setOnApiLIstner(new getContactData.onApiCompleted() {
#Override
public void onApiResults(
ArrayList<contact_entity> events_list) {
}
});
getContact.execute();
}
});
getMessage.execute();
}
});
getJobs.execute();
sync.setBackground(ct.getResources().getDrawable(
com.org.courier.R.drawable.sync_image_03));
Toast.makeText(ct, "Sync Finished", Toast.LENGTH_SHORT)
.show();
}
It showing an error
"java.lang.NoSuchMethodError: android.widget,ImageView.setBackground"
View.setBackground wasn't added until API 16. I ran into this issue myself, and couldn't figure out for the life of me why it was happening, since I didn't get any newAPI warnings.
If you want it to be compatible with all versions of Android, you should use:
setBackgroundResource()
or
setBackgroundDrawable()
However, for an ImageView, you should instead be setting the SRC, not the Background:
setImageResource() or setImageDrawable()

Webview shows white blank page in Ice Cream Sandwitch

In my webview I have loaded a URL which have an embeded video player of a tv channel live stream. It is working correctly in all the OS version of Android except ICS(4). First time It plays the video well, but when I go back and come again in that page containing the video then the video doesnt loads and shows a blank white page. If I force stop the app from the application setting and start the app again then It runs well then appears white screen again as usual, I have implemented a lot of tactics and this is the latest , I am totally stuck here:
public class Livetvwebview extends Activity {
RelativeLayout a;
WebView webtv;
String url;
VideoView video;
WChromeClient chromeClient;
WebViewClient wvClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.livewebview);
Toast.makeText(getApplicationContext(),
"Channel is loading..This may take upto a minute",
Toast.LENGTH_LONG).show();
url = getIntent().getStringExtra("tvchannel");
Log.i("TVURL", url);
webtv = (WebView) findViewById(R.id.webViewlive);
webtv.clearCache(true);
webtv.loadUrl(url);
webtv.getSettings().setLoadWithOverviewMode(true);
webtv.getSettings().setUseWideViewPort(true);
webtv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webtv.setWebChromeClient(new WChromeClient());
webtv.setWebViewClient(new myWebClient());
webtv.getSettings().setJavaScriptEnabled(true);
webtv.getSettings().setPluginState(PluginState.ON);
webtv.getSettings().setDomStorageEnabled(true);
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
#SuppressLint("NewApi")
#Override
protected void onPause() {
// TODO Auto-generated method stub
WebSettings webSettings = webtv.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webtv.onPause();
this.finish();
super.onPause();
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
webtv.onResume();
super.onResume();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
// android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache",
Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
class WChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int progress) {
Log.i("Method", "Onrogresschanged");
Livetvwebview.this.setTitle("Loading...");
Livetvwebview.this.setProgress(progress * 100);
if (progress == 100)
Livetvwebview.this.setTitle("LiveTv");
}
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
// TODO Auto-generated method stub
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout) {
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView) {
webtv.setVisibility(View.GONE);
video = (VideoView) frame.getFocusedChild();
FrameLayout.LayoutParams par = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
par.gravity = Gravity.CENTER_HORIZONTAL;
video.setLayoutParams(par);
frame.removeView(video);
a.addView(video);
video.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(Livetvwebview.this,
"Video completed", Toast.LENGTH_LONG)
.show();
}
});
video.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what,
int extra) {
Toast.makeText(Livetvwebview.this,
"Encountered some error", Toast.LENGTH_LONG)
.show();
return true;
}
});
video.start();
}
}
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Can anyone help me please?
After researching for a long long time I myself figured out that when I write in the onPause()
webtv.destroy();
instead of
webtv.onPause();
solves the problem :)

Categories