ImageButton setImageResource crashing app - java

So I've got a small problem which is doing my head in. I do know that the solution is something obvious and simple, but I'm new to programming and can't seem to get my head around it.
Basically, I've been following a Flashlight tutorial using Android Studio. In the tutorial, they used a simple button that would toggle into Flashlight ON, and Flashlight OFF modes.
I did not want to use just a button, and instead wanted to use an ImageButton instead, taking up the entire screen, and the clicking of the image would turn on the flashlight and change the image.
So, I simply modified the code after the flash would turn on into a setImageResource change. But clicking the image crashes the app rightaway unfortunately :(
Hope someone can help a noob out! Below is my Main Java file.
package com.dbz.flash;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
private boolean isFlashOn = false;
private Camera camera;
private ImageButton btnSwitch;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
Toast.makeText(getApplicationContext(),
"Your device doesn't have camera!",
Toast.LENGTH_SHORT).show();
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
btnSwitch.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isFlashOn = false;
//button.setText("Torch-ON");
btnSwitch.setImageResource(R.drawable.off);
} else {
Log.i("info", "torch is turned on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
//button.setText("Torch-OFF");
btnSwitch.setImageResource(R.drawable.on);
}
}
});
}
}
`

Related

Im new to creating app using java on android studio. Im creating splash screen but not works as i expected

The splash screen should move towards up and down, then go to the next screen. however, it just change the screen normally. the problem i think maybe between the handler and the animate splashscreen. this is my splash.java. hoping anyone can help thank you.
package com.example.dashboard;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.airbnb.lottie.LottieAnimationView;
public class Splash extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
ImageView logo,splashImg;
TextView appName;
LottieAnimationView lottieAnimationView;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
logo = findViewById(R.id.logo);
appName = findViewById(R.id.appname);
splashImg = findViewById(R.id.img);
lottieAnimationView = findViewById(R.id.lottie);
splashImg.animate().translationY(-1600).setDuration(1000).setStartDelay(3000);
logo.animate().translationY(1400).setDuration(1000).setStartDelay(3000);
appName.animate().translationY(1400).setDuration(1000).setStartDelay(3000);
lottieAnimationView.animate().translationY(1400).setDuration(1000).setStartDelay(3000);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
It looks like you start another Activity at the same time you play your animation. Notice the .setStartDelay(3000); at the end of each of your animation calls.
Just removing this will work. However, there are better ways to handle this.
One of the ways would be to override the onAnimationEnd method of your longest animation so that it either changes the Activity immediately or the change is delayed starting from that point in time. This will look something like this:
splashImg.animate().translationY(-1600).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
}
});

Camera Permission doesn't work at run time

I am working on QR code scanner App which takes user credentials and scan QR code and store User credentials with the content on QR code.
Since, I am beginner on working with Android App Development and hence, facing several issues such as:
(i) While opening camera permissions in App, it doesn't start automatically.I need to restart the app to open the camera to start QR code scanning.
Is there any possibility through which my app opens camera without taking permission from user. I have seen many apps doing so.
Or is there any modifications I can do to my QR scanner Java file so my camera works on runtime permission :qrscan.java
package com.example.android.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.android.loginapp.R;
import com.google.android.gms.common.wrappers.PackageManagerWrapper;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class qrscan extends AppCompatActivity {
private Button takePictureButton;
SurfaceView surfaceView;
CameraSource cameraSource;
TextView textView;
BarcodeDetector barcodeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.qrcode);
super.onCreate(savedInstanceState);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
textView=(TextView)findViewById(R.id.textView);
barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(this,barcodeDetector).setRequestedPreviewSize(640,480).build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(qrscan.this, new String[] {Manifest.permission.CAMERA}, 0);
return;
}
try {
cameraSource.start(holder);
}catch(IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if(qrCodes.size()!=0){
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator=(Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textView.setText(qrCodes.valueAt(0).displayValue);
}
});
}
}
});
}
}
(ii) My second issue is that: I want to store credentials of user with the QR code. But I lack knowledge of database and all those stuff.
Is there any easy way through which I can store such data ?
Something like storing data on google cloud.
I have already seen similar questions on stack overflow but none of them solves my issue.
This question is similar but doesn't help : surface view does not show camera after i gave permission
You need to check for permission to camera in activity where you have qr reader functionality before you start using it. If application do not have permission to that device you push it for ask again or just ignore it and let user know about it by message.
Example code
private void permissionAsk(String permission){
int grant = ContextCompat.checkSelfPermission(this, permission);
if (grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
String permission = Manifest.permission.CAMERA;
permissionAsk(permission);
permissionAsk(Manifest.permission.RECORD_AUDIO);
permissionAsk(Manifest.permission.WRITE_EXTERNAL_STORAGE);
You can easly find more solutions like that almost ready to go.

stop playing sound when another sound is playing in android studio

hello I use MediaPlayer for play sound in my project in android studio
when I click in a button and play sound , and when I click in another button that button play another sound , I want the first sound or another sound be stoped and just the last button that I clicked be played
I try this code but it not worked
package azad.broooska.fartfuns;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MusicFartActivity extends AppCompatActivity implements View.OnClickListener {
private CardView cardView1, cardView2, cardView3, cardView4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cardView1 = findViewById(R.id.card_music1);
cardView2 = findViewById(R.id.card_music2);
cardView3 = findViewById(R.id.card_music3);
cardView4 = findViewById(R.id.card_music4);
cardView1.setOnClickListener(this);
cardView2.setOnClickListener(this);
cardView3.setOnClickListener(this);
cardView4.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
final MediaPlayer s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
final MediaPlayer s2 = MediaPlayer.create(this, R.raw.fart_ballade);
final MediaPlayer s3 = MediaPlayer.create(this, R.raw.fart_uverture);
final MediaPlayer s4 = MediaPlayer.create(this, R.raw.farting_xmas);
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music2) {
s2.start();
s1.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music3) {
s3.start();
s2.stop();
s1.stop();
s4.stop();
} else {
Toast.makeText(this, "noThing", Toast.LENGTH_SHORT).show();
}
}
}
you are creating new instances of MediaPlayer each time something is clicked and assigning the variables to new objects; make s1,s2... class property;
MediaPlayer s1 ,s2,s3,s4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
//some code
s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
//assign the rest;
}
public void onClick(View view) {
int id = view.getId();
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
}
//rest of the code
}
Well, its seems like you don`t want to play very long sounds because you have names like
"fart_ballade" and "fart_uverture" in your code.
If your sounds are not very long it is better to work with the SoundPool class.
The MediaPlayer class sometimes can cause problems if you switch fast between sounds.
So if your sounds are not that long, you can try the SoundPool class.
Here you can learn more about the SoundPool class:
How to use SoundPool
I won`t write any code because SoundPool needs more than 5-6 lines of code to work properly.

How to get current wallpaper, change it, then restore it later

I'm struggling with why this code won't compile, I'm trying to get the current wallpaper, then change it, then give the option to change it back.
Below is my code, it doesn't compile because it can't resolve symbol 'context' and it says my drawable cannot be converted to an integer which doesn't make any sense whatsoever.
I'm trying to change the drawable to a bitmap AND I have imported the import
android.content.Context
so what is it I am doing wrong here?? this is my code, the onClick stores the wallpaper and starts the change activity, the onPush method resets the wallpaper and exits the app, any help would be appreciated thanks!
import android.content.Context;
import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import java.io.IOException;
import static android.app.WallpaperManager.*;
public class SetWallpaperActivity extends Activity {
public Drawable originalWallpaper;
public Bitmap paper1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
originalWallpaper = wm.getDrawable();
paper1 = BitmapFactory.decodeResource(context.getResources(),
originalWallpaper);
Intent intent = new Intent(
ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(EXTRA_LIVE_WALLPAPER_COMPONENT,
new ComponentName(this, MyWallpaperService.class));
startActivity(intent);
}
public void onPush(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
WallpaperInfo wallpaperInfo = wm.getWallpaperInfo();
if (wallpaperInfo != null) {
try {
wm.setBitmap(paper1);
finish();
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
System.exit(0);
}
}
This is the error code I'm getting:
'decodeResource(android.content.res.Resources, int)' in 'android.graphics.BitmapFactory' cannot be applied to '(android.content.res.Resources, android.graphics.drawable.Drawable)'

mCamera cannot be resolved to a variable (Android, Eclipse)

I am very new to Android development. I am following Google's Android "classes" and am receiving an error for this code in Eclipse:
package com.feistie.myfirstapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
//does not behave as a buutton
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
}
}
#Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass
// Stop method tracing that the activity started during onCreate()
android.os.Debug.stopMethodTracing();
}
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// Release the Camera because we don't need it when paused
// and other activities might need to use it.
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage (View view) {
// Do Something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
There is an error for each of these lines:
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
The error for the first and third lines says "mCamera cannot be resolved to a variable." The error for the second line just says "mCamera cannot be resolved."
If you need more information please let me know.
Thanks!
You need to declare mCamera before you can reference it:
public class MainActivity extends Activity {
Camera mCamera;
And then you need to initialize it, probably in onResume()
#Override
protected void onResume() {
super.onResume();
mCamera = Camera.open()
}
Make sure you added the appropriate permission that you manifest:
<uses-permission android:name="android.permission.CAMERA" />
Addition
You need to declare_every_ variable before you try use it in Java. I don't see where you declare mTextView either.
public class MainActivity extends Activity {
Camera mCamera;
TextView mTextView;

Categories