Cannot Implement ContentView inside Fragment - java

I want to set ZXingscanner as a content view inside my fragment, but it's not working. I have app with some tabs and on one of these tabs I want to have this ZXingscanner view, but when I try to set it it doesn't work.Isn't there any setContentView for fragment or something like that to work for this specific case ? And also Alert dialog builder shows error, it says alert dialog cannot be applied to fragment.Any help would be very helpful.
Here's the code:
package com.hist_area.imeda.histarea.fragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class EmptyFragment extends Fragment implements ZXingScannerView.ResultHandler {
public static EmptyFragment create() {
return new EmptyFragment();
}
Vibrator vibrator;
private static final int CAMERA_PERMISSION_REQUEST_CODE = 8675309;
private ZXingScannerView mScannerView;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
invokecamera();
}
}
}
public void invokecamera() {
mScannerView = new ZXingScannerView(this);
return View(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void handleResult(Result result) {
vibrator.vibrate(369);
Log.w("handleResult", 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 which) {
mScannerView.resumeCameraPreview(EmptyFragment.this);
}
});
invokecamera();
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}

Related

onCreate being called twice causing app to exit prematurely

I went through the other SO posts but didn't find anything relevant to my problem.
I am trying to create an app that will get the user's step count from the last reboot. Here is my main Activity:
package com.assignment.bwowassignment;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements MainActivityContract.View {
MainActivityPresenter presenter;
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.d("mihir", "hello");
presenter = new MainActivityPresenter(this);
presenter.requestActivityPermission(this);
}
#Override
public void onGetStepsSuccess(float[] values) {
Log.d("mihir", Arrays.toString(values));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == presenter.ACTIVITY_REQUEST_CODE)
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
presenter.registerListener(this);
else {
Log.d("mihir", "kill me");
finish();
}
}
#Override
protected void onPause() {
super.onPause();
presenter.sensorManager.unregisterListener(presenter);
}
}
MainActivityPresenter.java
package com.assignment.bwowassignment;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.logging.Logger;
public class MainActivityPresenter implements MainActivityContract.Presenter, SensorEventListener {
MainActivityContract.View view;
SensorManager sensorManager;
Sensor sensor;
public MainActivityPresenter(MainActivityContract.View view) {
this.view = view;
sensorManager = (SensorManager) ((Context) view).getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}
#Override
public void registerListener(Context context) {
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
public void requestActivityPermission(Context context) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED)
registerListener(context);
else if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACTIVITY_RECOGNITION))
new AlertDialog.Builder(context)
.setTitle("Permission required")
.setMessage("This permission is required to fetch the sensor data from your phone, denying it will cause the app to exit")
.setPositiveButton("Give permission", (dialog, which) -> ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, ACTIVITY_REQUEST_CODE))
.setNegativeButton("Deny", (dialog, which) -> ((Activity) context).finish())
.show();
else
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, ACTIVITY_REQUEST_CODE);
}
#Override
public void onSensorChanged(SensorEvent event) {
view.onGetStepsSuccess(event.values);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
MainActivityContract.java
package com.assignment.bwowassignment;
import android.content.Context;
public interface MainActivityContract {
interface View {
void onGetStepsSuccess(float[] values);
}
interface Presenter {
int ACTIVITY_REQUEST_CODE = 1;
void registerListener(Context context);
void requestActivityPermission(Context context);
}
}
As you can see there are two Logs with my name in the tag, what is happening here is the "hello" log is getting logged twice. I am guessing it's the first onCreate which is responsible for my app finishing before starting since I get this warning in the logcat:
W/Activity: Can request only one set of permissions at a time
I am only requesting one permission but due to the onCreate being called twice the first permission gets automatically denied which causes the app to finish() before it already started! I have been scratching my head over this since yesterday, any help is appreciated!
I figured it out!
The culprit was this line:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
So apparently, this causes a configuration change, causing the onCreate method to be called twice, to get over this, call it BEFORE the call to super in onCreate like this:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

How to ask for Location Permission up-front on App Launch in Java

I am trying to ask for Device permission Upfront on app Launch to no avail. I am not using any Libraries since I am following this document(https://developer.android.com/training/permissions/requesting)
and I am intending to use it, What am I doing wrong?
Here is my Manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
This is my what I have tried on MainActivity and my minSdkVersion is 26
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_CODE = 100;
private Activity mActivity;
private Context mContext;
String[] appPermissions = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivity = MainActivity.this;
mContext = getApplicationContext();
requestAppPermissions();
}
private void requestAppPermissions() {
try {
if(ContextCompat.checkSelfPermission(
mActivity,Manifest.permission.ACCESS_FINE_LOCATION
)+ContextCompat.checkSelfPermission(
mActivity,Manifest.permission.ACCESS_COARSE_LOCATION
)== PackageManager.PERMISSION_GRANTED
){
///perform action
Toast.makeText(mContext,"Permissions already granted",Toast.LENGTH_SHORT).show();
}else {
if (
//Do something when permission is not granted
ActivityCompat.shouldShowRequestPermissionRationale(
mActivity, Manifest.permission.ACCESS_FINE_LOCATION
) || ActivityCompat.shouldShowRequestPermissionRationale(
mActivity, Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setMessage("Location Permission is required by App.");
builder.setTitle("Please grant location Permission");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(
mActivity, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
},
REQUEST_CODE
);
}
});
builder.setNeutralButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_CODE:{
if(
(
grantResults.length>0)&&(
grantResults[0]+grantResults[1]
==PackageManager.PERMISSION_GRANTED
)
){
Toast.makeText(mContext,"Permissions granted.",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mContext,"Permissions Denied.",Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}

How to open a new activity from a dialog fragment

My program opens a DialogFragment class while running in MainActivity.java
I want to be able to click on the "neutral button" of that dialog and open a new activity, SensorDataDisplay.java
I am having trouble finding the right way to reference the Context in my button's onClick.
package com.august.customtisensortagclient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import java.util.ArrayList;
public class GetInfoDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String thisWhichGetInfoDialog = ((MainActivity)getActivity()).getWhichGetInfoDialog();
final ArrayList<String> thisScannedDevicesArrayList =
((MainActivity)getActivity()).getScannedDevicesArrayList();
final int thisIsInLeftConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInLeftConnectedDeviceDisplay();
final int thisIsInRightConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInRightConnectedDeviceDisplay();
int thisIsInThisConnectedDeviceDisplay = 0;
if (thisWhichGetInfoDialog == "Left") {
thisIsInThisConnectedDeviceDisplay = thisIsInLeftConnectedDeviceDisplay;
} else if (thisWhichGetInfoDialog == "Right")
thisIsInThisConnectedDeviceDisplay = thisIsInRightConnectedDeviceDisplay;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(thisWhichGetInfoDialog + " Sensor Info");
builder.setMessage("MAC Address: " + thisScannedDevicesArrayList.get(thisIsInThisConnectedDeviceDisplay));
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(?????, SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
?????.startActivity(myIntent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
}
DialogFragment has getActivity() and getContext() methods (which it inherits from Fragment), both will work in your case. If you're having trouble accessing these methods from the anonymous class (which shouldn't be the case), you can use the GetInfoDialog.this.getActivity() syntax.
getActivity() returns the Activity the fragment is attached to
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
getActivity().startActivity(myIntent);
}
});

How to capture and pass Mat object to a new activity?

I am planning on implementing ocr, the idea is for the user to capture an image and the app will write it as text to a file on the phone. I have managed to display the feed from the camera to the javacameraview using CvCameraViewListener2.
I now want to capture the frame as an Mat object and pass it to a new activity. The solution's I saw all involve saving the photo, or displaying the processed image or live processing. I just need to pass the Mat to another class for processing then I can release it. I'm having trouble find a methodology for doing this though it seems as though it should be fairly straightforward.
The question is essentially how to get the Mat object from the cameraview?
Any help or direction would be greatly appreciated.
Thank you stackoverflow
The relevant code is here
import android.Manifest;
import android.content.Intent;
Import android.content.pm.ActivityInfo; importandroid.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION_RESULT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation != 90) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.cameraInit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//marshmallow permissions
takePhoto();
}
});
}
private void callCamera(){
Intent startCameraIntent = new Intent(getApplicationContext(), OpenCVCamera.class);
startActivity(startCameraIntent);
}
public void takePhoto() {
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this, "This app requires camera access", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_RESULT);
}
} else {
callCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CAMERA_PERMISSION_RESULT){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
Toast.makeText(this, "Permission Denied.", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
public class OpenCVCamera extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
// need to correct view size (i think this can be done in the xml
// else refer to cmaera video app
// also orientation needs to be corrected
private static final String TAG = "OpenCVCamera";
private CameraBridgeViewBase cameraBridgeViewBase;
private BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
cameraBridgeViewBase.enableView();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_open_cvcamera);
cameraBridgeViewBase = (CameraBridgeViewBase) findViewById(R.id.camera_view);
cameraBridgeViewBase.setVisibility(SurfaceView.VISIBLE);
cameraBridgeViewBase.setCvCameraViewListener(this);
}
#Override
public void onResume(){
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, baseLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
baseLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
#Override
public void onCameraViewStarted(int width, int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
//original just returns inputFrame.rgba()
Core.rotate(inputFrame.rgba(), inputFrame.rgba(), Core.ROTATE_90_CLOCKWISE); //ROTATE_180 or ROTATE_90_COUNTERCLOCKWISE
return inputFrame.rgba();
}
}

Place Picker loads to long, variables don't change correctly

I'm making a simple place picker program in android. I want to save some text when user choose a point on map with place picker. And the problem is when I click on button the place picker opens too long and variable which is responsible for place can't keep up change and dialog that responses for enter text never opens. I think, maybe problem is with threads, isn't it?
MapsActivity.java
package com.example.kirill.myapplication;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, View.OnClickListener {
private static final int PLACE_PICKER_REQUEST = 1;
private GoogleMap mMap;
private Button addEventBtn;
private PlacePicker.IntentBuilder builder;
private Place place;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
if (place != null) {
openDialog();
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
addEventBtn = (Button) findViewById(R.id.AddEventButton);
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
Marker marker = mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
addEventBtn.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
}
}
}
public void openDialog() {
DialogEventCreate dialogEventCreate = new DialogEventCreate();
dialogEventCreate.show(getSupportFragmentManager(), "dialog Event Create");
}
public void callPlacePicker() {
builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
DialogEventCreate.java
package com.example.kirill.myapplication;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
public class DialogEventCreate extends AppCompatDialogFragment {
private EditText editEventName;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view)
.setTitle("Create Event")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
editEventName = view.findViewById(R.id.editEventName);
return builder.create();
}
}
Please help me, what could go wrong?
Your problem is that the Place Picker communicates with your main activity asynchronously, so you're opening your dialog before it returns. Try waiting until Place Picker has returned before opening the dialog like so:
.
.
.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
break;
}
}
.
.
.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
openDialog();
}
}
}

Categories