Take picture in android fails - java

I went over all the related posts and no answer was found.
I'm trying to take a picture with the Camera library and it fails on take picture method.
What the code is suppose to do, is when pressed a button to show an image over the ImageView (simple as this sounds).
The app crashes when it gets to take picture, stack trace attached at end.
MainActivity.java
package com.drivesafe.drivesafe;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.*;
import android.view.*;
import android.widget.*;
import android.hardware.Camera;
import java.util.Timer;
public class MainActivity extends AppCompatActivity {
public static ProgressDialog detectionProgressDialog;
public static ImageView imageView;
public static Camera camera;
public static Camera.PictureCallback pictureCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)findViewById(R.id.imageView1);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
take_picture();
}
});
this.detectionProgressDialog = new ProgressDialog(this);
this.pictureCallback = new PhotoHandler(getApplicationContext());
this.initFrontCamera();
}
private void take_picture() {
camera.startPreview();
camera.takePicture(null, null, null, this.pictureCallback);
}
private void initFrontCamera() {
camera = Camera.open(1); //front camera
}
}
PhotoHandler.java
package com.drivesafe.drivesafe;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class PhotoHandler implements PictureCallback {
private final Context context;
public PhotoHandler(Context context) {
this.context = context;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
MainActivity.imageView.setImageBitmap(bitmap);
}
}
Stack Trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.drivesafe.drivesafe, PID: 28460
java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1545)
at com.drivesafe.drivesafe.MainActivity.take_picture(MainActivity.java:43)
at com.drivesafe.drivesafe.MainActivity.access$000(MainActivity.java:13)
at com.drivesafe.drivesafe.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22433)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Application terminated.
Permissions
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera"
android:required="true" />
I would love some help please.

Related

Make Android app get bluetooth manufacturer data

I am working on an Android app android 10 and nordic nrf52840 which is advertising at channel 37,38,39 I want to get the manufacturer data from my nordic bluetooth device. Like the picture shown below. Now I can scan and find my device, but I don't know how to get manufacturer data.
package com.example.test373839;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.BatchingListUpdateCallback;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter=null;
private BluetoothManager mbluetoothManager=null;
private BroadcastReceiver mReceiver=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnScan=(Button)findViewById(R.id.button);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
}
public void StartScan(View view) {
Log.d("Button","click");
checkBTPermission();
mBluetoothAdapter.startDiscovery();
IntentFilter dicoveryDeviceIntent=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastreceiver,dicoveryDeviceIntent);
}
private void checkBTPermission(){
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
int pc=this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
pc+=this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if(pc!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}else {
Log.d("Bluetooth","checkBT permission");
}
}
}
final private BroadcastReceiver mBroadcastreceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
Log.d("Bluetooth",device.getAddress()+":"+device.getName());
}
}
};
}

FragmentManager has not been attached to a host error while running an Activity

Im new to android and they(some people :) ) gave me an half developed app and im still confused about some things.
Im getting an error which i can't understand what it means. So the error is what i wrote in the title : java.lang.IllegalStateException: FragmentManager has not been attached to a host, and is hapening when this activity runs:
package com.example.loginregistodb;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class ClienteActivity extends AppCompatActivity {
Spinner tipo_intervencao;
Button bt_cliente_seguinte;
EditText et_inserir_cliente;
ImageView icon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente);
bt_cliente_seguinte = (Button) findViewById(R.id.bt_cliente_seguinte);
et_inserir_cliente = findViewById(R.id.et_inserir_cliente);
tipo_intervencao = findViewById(R.id.tipo_intervencao);
icon1 = findViewById(R.id.icon2);
bt_cliente_seguinte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cliente = et_inserir_cliente.getText().toString();
String tipoIntervencao = "" + tipo_intervencao.getSelectedItem().toString();
preencherExcel Excel = new preencherExcel();
Excel.entradaWhatsapp(cliente, tipoIntervencao);
if (cliente.equalsIgnoreCase("")) {
Toast.makeText(ClienteActivity.this, "Preencha o campo Cliente!", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(ClienteActivity.this, EmpresaActivity.class);
startActivity(i);
}
}
});
}
}
EDIT :
the error message i get is this :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginregistodb, PID: 15275
java.lang.IllegalStateException: FragmentManager has not been attached to a host.
at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1938)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1996)
at androidx.fragment.app.FragmentManager.executePendingTransactions(FragmentManager.java:600)
at com.google.firebase.firestore.core.ActivityScope.lambda$onFragmentActivityStopCallOnce$1(ActivityScope.java:180)
at com.google.firebase.firestore.core.ActivityScope$$ExternalSyntheticLambda1.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

How to create in flutter plugin for intent method using java

How to make intent call to any class in flutter plugin using java.
I am facing some errors OnMethodCall how to use intent inside call method in flutter plugin.
I searched on different platform for to get help about this problem.I am fail to find.
My Imports :
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import static androidx.core.content.ContextCompat.createDeviceProtectedStorageContext;
import static androidx.core.content.ContextCompat.startActivity;
OnMethodCall
#Override
public void onMethodCall(#NonNull MethodCall call, #NonNull Result result) {
if (call.method.equals("getPlatformVersion")) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setClassName("com.android.settings", "com.android.settings.RadioInfo");
startActivity(intent);
} else {
result.notImplemented();
}
}

How to make Instagram's Sharing a Sticker Asset example work?

I'm trying to follow Facebook's docs for Sharing a Sticker Asset on Android without any luck. Basically when executed the app flickers and then crash.
Could someone look at this code and point out why the app crashes after calling activity.startActivityForResult(intent, 0);? (debugging the code using logcat, I can see the code is definitely executing startActivityForResult)
package com.app.my;
import android.net.Uri;
import android.content.Intent;
import android.app.Activity;
import android.util.Log;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class InstagramStoriesModule extends ReactContextBaseJavaModule {
private static ReactApplicationContext reactContext;
InstagramStoriesModule(ReactApplicationContext context) {
super(context);
reactContext = context;
}
//Mandatory function getName that specifies the module name
#Override
public String getName() {
return "InstagramStories";
}
//Custom function that we are going to export to JS
#ReactMethod
public void share(ReadableMap options) {
String stickerImage = "https://www.example.com/image.jpeg";
String backgroundColor = "#000000";
Uri stickerAssetUri = Uri.parse(stickerImage);
Intent intent = new Intent("com.instagram.share.ADD_TO_STORY");
intent.setType("image/jpeg");
intent.putExtra("interactive_asset_uri", stickerAssetUri);
intent.putExtra("top_background_color", backgroundColor);
intent.putExtra("bottom_background_color", backgroundColor);
Activity activity = reactContext.getCurrentActivity();
activity.grantUriPermission("com.instagram.android", stickerAssetUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (activity.getPackageManager().resolveActivity(intent, 0) != null) {
activity.startActivityForResult(intent, 0);
}
}
}

NullPointerException getPackageName() on bindService

I'm trying to create a remote service for an android app. I've more or less copied the code from the Android Developers website, retooling it for my purposes. When I get to the bindService step, though, I get a NullPointerException on android.content.Context.getPackageName(). What am I doing wrong?
I've used an in process service with an earlier version of the app, but it wasn't enough for what I wanted from it. The service itself remained the same between the two, other than the necessary changes in code. I've looked at all the results on here, but they were either not related or didn't help me any.
I've tried moving the calls from onCreate to onStart. No difference. onCreate for the BinderActivity never executed. I tried startService instead of bindService, but it gave me the same error. I've checked that this, the intent, and mConnection were all non-null (they are). I know that the service isn't started, but I'm using Context.BIND_AUTO_CREATE (which is supposed to start it if it's not). Short of waving a dead chicken over the problem, I'm not sure what else to do here.
My MainActivity:
package com.example.trainchecker;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Message;
import android.os.Messenger;
import java.io.*;
import java.util.ArrayList;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BinderActivity ba = new BinderActivity();
ba.BindService();
}
}
This is the BinderActivity, where the magic is supposed to happen. Instead, the error does:
package com.example.trainchecker;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.os.Message;
import android.os.Handler;
import android.os.Messenger;
public class BinderActivity extends Activity {
public Messenger ms = null;
private MainActivity ma;
class IncomingHandler extends Handler{
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
}
}
final Messenger mm = new Messenger(new IncomingHandler());
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d("MCon","Sentinel Online");
ms = new Messenger(service);
try {
Message msg = Message.obtain(null,TCService.MSG_REGISTER_CLIENT);
msg.replyTo = mm;
ms.send(msg);
} catch (RemoteException e){ e.printStackTrace();}
}
public void onServiceDisconnected(ComponentName className) {
Log.d("MCon","Sentinel Offline");
try {
Message msg = Message.obtain(null,2);
msg.replyTo = mm;
ms.send(msg);
} catch (RemoteException e){ e.printStackTrace();}
}
};
public void BindService() {
bindService(new Intent(this, TCService.class), mConnection, Context.BIND_AUTO_CREATE);
}
}
And, finally, the service itself. Not much there, but it's mine:
package com.example.trainchecker;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import android.os.Message;
import android.os.Messenger;
public class TCService extends Service {
ArrayList<Messenger> mc = new ArrayList<>();
#Override
public IBinder onBind(Intent i) {
Log.d("TCS", "Binding Now");
return mm.getBinder();
}
static final int MSG_REGISTER_CLIENT = 1;
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
mc.add(msg.replyTo);
break;
case 2:
mc.remove(msg.replyTo);
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mm = new Messenger(new IncomingHandler());
}
Here is the error in it's entirety:
09-15 11:39:04.518 15448-15448/com.example.trainchecker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.trainchecker, PID: 15448
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trainchecker/com.example.trainchecker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4468)
at com.example.trainchecker.BinderActivity.BindService(BinderActivity.java:58)
at com.example.trainchecker.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6285)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.access$900(ActivityThread.java:150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:171) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Programmatically instantiating an Activity instance doesn't trigger lifecycles therefore your context isn't valid there. Pass it to your BindService() call. Technically speaking your BinderActivity doesn't need to exist and can live in your MainAcitivity or a service.

Categories