Android Studio CameraX Module - java

I am working on an app that can open camera to take picture and then show it on Imageview in the next activity or select picture from file and then view it in ImageView on next activity.
I have a java class named CameraActivity for my App.
Below is a code I want to use. It was working before on another app. But with Android Studio Update it is not working in new App.
I guess It's depreciated. I need this code to wokk. Help me with necessary changes.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Rational;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class CameraActivity extends AppCompatActivity {
TextureView viewFinder;
ImageView imgCapture;
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
viewFinder=findViewById(R.id.viewFinder);
imgCapture = findViewById(R.id.imgCapture);
startCamera();
}
#SuppressLint("RestrictedApi")
public void startCamera(){
CameraX.unbindAll();
Rational aspectRatio = new Rational(viewFinder.getWidth(),viewFinder.getHeight());
Size screen = new Size(viewFinder.getWidth(),viewFinder.getHeight());
PreviewConfig previewConfig = new PreviewConfig.Builder().setTargetAspectRatio(aspectRatio).setTargetResolution(screen).build();
Preview preview = new Preview(previewConfig);
preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
#Override
public void onUpdated(Preview.PreviewOutput output) {
ViewGroup parent = (ViewGroup)viewFinder.getParent();
parent.removeView(viewFinder);
parent.addView(viewFinder,0);
viewFinder.setSurfaceTexture(output.getSurfaceTexture());
updateTransform();
}
});
ImageCaptureConfig imageCaptureConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
final ImageCapture imageCapture = new ImageCapture(imageCaptureConfig);
imgCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(Environment.getExternalStorageDirectory()+"/"+System.currentTimeMillis()+".jpg");
imageCapture.takePicture(file, new ImageCapture.OnImageSavedListener() {
#SuppressLint("ShowToast")
#Override
public void onImageSaved(#NonNull File file) {
Toast.makeText(getApplicationContext(),"Pic Captured at" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(CameraActivity.this,ShowPhotoActivity.class);
intent.putExtra("path",file.getAbsoluteFile()+"");
startActivity(intent);
}
#Override
public void onError(#NonNull ImageCapture.UseCaseError useCaseError, #NonNull String message, #Nullable Throwable cause) {
Toast.makeText(getApplicationContext(),"Pic Captured Failed! " + message, Toast.LENGTH_SHORT).show();
if(cause!=null){
cause.printStackTrace();
}
}
});
}
});
CameraX.bindToLifecycle((LifecycleOwner)this, preview, imageCapture);
}
public void updateTransform(){
Matrix mx = new Matrix();
float w = viewFinder.getMeasuredWidth();
float h = viewFinder.getMeasuredHeight();
float cx = w/2f;
float cy = h/2f;
int rotationDgr = 90;
int rotation = (int)viewFinder.getRotation();
switch(rotation){
case Surface.ROTATION_0:
rotationDgr = 0;
break;
case Surface.ROTATION_90:
rotationDgr = 90;
break;
case Surface.ROTATION_180:
rotationDgr = 180;
break;
case Surface.ROTATION_270:
rotationDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotationDgr,cx,cy);
viewFinder.setTransform(mx);
}
}
I am attaching he images below to help with identifying the errors

Use these dependencies.
// CameraX
implementation "androidx.camera:camera-core:1.2.0-beta02"
// link UI's lifecycle with camera-x (It will handle by itself)
implementation "androidx.camera:camera-lifecycle:1.2.0-beta02"
// Get camera-x's previewView
implementation "androidx.camera:camera-view:1.2.0-beta02"
// For bokeh & else
implementation "androidx.camera:camera-extensions:1.2.0-beta02"
// Added for choosing best quality Camera Selection
implementation 'androidx.camera:camera-camera2:1.1.0'

Related

How to loop a function and wait a second between every loop in google maps project in android studio?

I want to create a program that mark a place on the google map and every second from when I push the "Start" button the marker would jump a km to a random direction until I push the "Stop" button.
I want the marker to jump, wait a second, jump, wait a second and so on... Until I push the "Stop" button.
When I am using the "while" loop the program stuck even before the showing of the "Stop" button.
But if I don't use the loop it's working good. Can you help me please?
This is my code:
import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
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.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.Random;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private double currLat = 32.671677;
private double currLng = 35.195678;
private Marker _marker;
private boolean _stopBWasNotPressed = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// Setting the icon instead of the default marker.
private BitmapDescriptor bitmapDescriptorFromVector(Context context, #DrawableRes int vectorDrawableResourceId) {
Drawable background = ContextCompat.getDrawable(context, R.drawable.car_icon);
background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
background.draw(canvas);
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Hide the Stop button.
Button stopB = (Button) findViewById(R.id.stopB);
stopB.setVisibility(View.GONE);
// Hide the Reset button.
Button resetB = (Button) findViewById(R.id.resetB);
resetB.setVisibility(View.GONE);
// Add a marker in my home and move the camera.
LatLng home = new LatLng(currLat, currLng);
_marker = mMap.addMarker(new MarkerOptions().position(home).icon(bitmapDescriptorFromVector(this, R.drawable.car_icon)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));
// Show the Start button.
Button startB = (Button) findViewById(R.id.startB);
startB.setVisibility(View.VISIBLE);
startB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Hide the Start button.
Button startB = (Button) findViewById(R.id.startB);
startB.setVisibility(View.GONE);
// Show the Stop button.
final Button stopB = (Button) findViewById(R.id.stopB);
stopB.setVisibility(View.VISIBLE);
while (_stopBWasNotPressed) {
// Making the program wait a second until it moving the marker again.
new Handler().postDelayed(new Runnable() {
public void run() {
startMoving();
}
}, 1000); // 1 second.
}
}
});
}
// This func generates a random number to use as a direction.
public int generateRandomDirection(){
final int min = 1;
final int max = 4;
final int random = new Random().nextInt((max - min) + 1) + min;
return random;
}
// This func makes the new location and sends it to the animateMarker func.
public void startMoving(){
int directionNumber = generateRandomDirection();
final LatLng toPos;
switch(directionNumber) {
case 1:
toPos = new LatLng((currLat + 0.01), currLng); // North.
_marker.setPosition(toPos);
break;
case 2:
toPos = new LatLng((currLat - 0.01), currLng); // South.
_marker.setPosition(toPos);
break;
case 3:
toPos = new LatLng(currLat, (currLng + 0.01)); // East.
_marker.setPosition(toPos);
break;
default:
toPos = new LatLng(currLat, (currLng - 0.01)); // West.
_marker.setPosition(toPos);
break;
}
}
public void stopButtonClick(View view) {
_stopBWasNotPressed = false; // Stops the while loop.
// Hide the Stop button.
Button stopB = (Button) findViewById(R.id.stopB);
stopB.setVisibility(View.GONE);
// Show the Reset button.
final Button resetB = (Button) findViewById(R.id.resetB);
resetB.setVisibility(View.VISIBLE);
resetB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
_marker.setVisible(false);
currLat = 32.671677;
currLng = 35.195678;
onMapReady(mMap);
}
});
}
}
I searched a bit and I found that I can't use the while loop and the delay function together so I changed it to this:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
while (_stopBWasNotPressed) {
try {
Thread.sleep(1000); // Making the program wait a second until it continues.
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
startMoving();
}
});
}
}
};
Thread myThread = new Thread(runnable); // Creating a thread for the marker movement.
myThread.start();

How to added specific Android code to Flutter

I have an application which runs correctly without any issue $ I added Java code to it to use a method channel and the problem is that the application isn't able to run sound microphone camera and did not show me any authorization to accept using camera or sound $.
The code which I added from Android works correctly and show me exactly what I want.
package com.example.akk;
import android.content.ContextWrapper;
import android.os.BatteryManager;
import android.os.Bundle;
import android.content.Intent;
import android.content.IntentFilter;
//import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.app.FlutterActivity;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL="samples.flutter.dev/battery";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(),CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler(){
#Override
public void onMethodCall(MethodCall methodCall,MethodChannel.Result result ){
if(methodCall.method.equals("getBatteryLevel")){
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
});
}
private int getBatteryLevel() {
// int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
int deviceHealth;
int x=10;
Intent intent = new ContextWrapper(getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
deviceHealth = (intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0));
if(deviceHealth == BatteryManager.BATTERY_HEALTH_DEAD){
x=0; }
if (deviceHealth == BatteryManager.BATTERY_HEALTH_GOOD){
x=1; }
if(deviceHealth == BatteryManager.BATTERY_HEALTH_OVERHEAT){
x=2; }
if (deviceHealth == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
x=3; }
if (deviceHealth == BatteryManager.BATTERY_HEALTH_UNKNOWN){
x=4; }
if (deviceHealth == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
x=5; }
return x;
}
}
i need some helps and thank you

Reference to "method" is ambiguous

When calling Builder() I am given the error message:
Reference to 'Builder' is ambiguous, both 'androidx.camera.core.impl.UseCaseConfig.Builder' and 'androidx.camera.core.impl.ImageOutputConfig.Builder' match
The error is produced within the startCamera() function.
How would I make sure the compiler knows to use the UseCaseConfig option?
Any help is appreciated, thank you for your time and help.
package com.example.atlas2.Activities.Login.UserCreation.ProfilePhotoCamerax;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.impl.PreviewConfig;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.content.pm.PackageManager;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.Rational;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import android.widget.Toast;
import com.example.atlas2.R;
public class ProfilePhotoActivityX extends AppCompatActivity {
private int REQUEST_CODE_PERMISSIONS = 101;
private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA",
"android.permission.WRITE_EXTERNAL_STORAGE"};
TextureView textureView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_photo_x);
textureView = findViewById(R.id.view_finder);
if(allPermissionsGranted()){
startCamera(); //start camera if permission has been granted by user
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}
private void startCamera() {
Rational aspectRatio = new Rational(textureView.getWidth(), textureView.getHeight());
Size screen = new Size(textureView.getWidth(), textureView.getHeight());
PreviewConfig pConfig = new PreviewConfig.Builder<>();
}
private void updateTransform(){
Matrix mx = new Matrix();
float w = textureView.getMeasuredWidth();
float h = textureView.getMeasuredHeight();
float cX = w / 2f;
float cY = h / 2f;
int rotationDgr;
int rotation = (int)textureView.getRotation();
switch(rotation){
case Surface.ROTATION_0:
rotationDgr = 0;
break;
case Surface.ROTATION_90:
rotationDgr = 90;
break;
case Surface.ROTATION_180:
rotationDgr = 180;
break;
case Surface.ROTATION_270:
rotationDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotationDgr, cX, cY);
textureView.setTransform(mx);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull
int[] grantResults) {
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
}
First of all - what version of CameraX are you using? The latest(at the time of writing) is alpha09(core) in which you should build your preview like this:
Preview preview = new Preview.Builder().build();
You can then easily use whichever set methods in builder for your preview configuration. The google docs are not completely updated to newest version yet so you can use the forum for help.

java.lang.NoClassDefFoundError: rx.subjects.PublishSubject

I've added Adobe creative SDK into my project and now im getting an error when im trying to move to Edit image function.
FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: rx.subjects.PublishSubject
at com.adobe.creativesdk.aviary.internal.account.AdobeAccountConnection.<init>(AdobeAccountConnection.java:45)
at com.adobe.creativesdk.aviary.AdobeImageEditorActivity.onCreate(AdobeImageEditorActivity.java:517)
at android.app.Activity.performCreate(Activity.java:5268)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
at android.app.ActivityThread.access$600(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1259)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:740)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method)
I went through the documentations but i've no idea why im getting this error
i have attached my code
package com.sliit.dailyselfie.Camera;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.adobe.creativesdk.aviary.AdobeImageIntent;
import com.bumptech.glide.Glide;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnMenuTabClickListener;
import com.sliit.dailyselfie.R;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import rebus.bottomdialog.BottomDialog;
public class CameraActivity extends AppCompatActivity {
private static final int ActivityStartCAM=0;
private final static int EDIT_IMAGE=1;
private ImageView IV;
private String ImageFileLoaction="";
BottomBar CamBottomBar;
ImageButton bcan,bsnap,bdesc;
Dialog d;
BottomDialog dialog;
String challenge;
Bundle extras;
boolean picpresent=false;
Uri ImageUri;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
IV = (ImageView)findViewById(R.id.snap1);
IV.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (picpresent) {
dialog = new BottomDialog(CameraActivity.this);
dialog.title("Options");
dialog.canceledOnTouchOutside(true);
dialog.cancelable(true);
dialog.inflateMenu(R.menu.camera_bottomsheet_menu);
dialog.setOnItemSelectedListener(new BottomDialog.OnItemSelectedListener() {
#Override
public boolean onItemSelected(int id) {
switch (id) {
case R.id.addeffects:
image();
return true;
case R.id.crop:
Toast.makeText(getApplicationContext(),"crop",Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
dialog.show();
}
return true;
}
});
extras = getIntent().getExtras();
if (extras != null) {
challenge = extras.getString("Challenge");
}
CamBottomBar = BottomBar.attach(this, savedInstanceState);
CamBottomBar.noNavBarGoodness();
CamBottomBar.setItemsFromMenu(R.menu.camera_bottombar, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.nav_back) {
IV.setImageResource(R.drawable.selfieimage);
IV.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
picpresent = false;
} else if (menuItemId == R.id.nav_takeSnap) {
Intent CAMint= new Intent();
CAMint.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile=null;
try{
photoFile=createImageFile();
}catch(IOException e){
e.printStackTrace();
}
CAMint.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(CAMint, ActivityStartCAM);
} else if (menuItemId == R.id.nav_addDetails) {
if (picpresent) {
switch (challenge) {
case "fitness":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.fitnessdialog);
ImageView fitim = (ImageView) d.findViewById(R.id.fitdialogimg);
TextView fittxt = (TextView) d.findViewById(R.id.fitdialogdesc);
d.show();
break;
case "maternity":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.maternitydialog);
ImageView matimg = (ImageView) d.findViewById(R.id.matdialogimg);
TextView mattxt = (TextView) d.findViewById(R.id.matdialogdesc);
d.show();
break;
case "child":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.childdialog);
ImageView chilimg = (ImageView) d.findViewById(R.id.childialogimg);
TextView chiltxt = (TextView) d.findViewById(R.id.childialogdesc);
d.show();
break;
}
}else{
Toast.makeText(CameraActivity.this, "Please select image", Toast.LENGTH_SHORT).show();
}
}
//
// CamBottomBar.mapColorForTab(0, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(1, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(2, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.nav_back) {
IV.setImageResource(R.drawable.selfieimage);
IV.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
picpresent = false;
} else if (menuItemId == R.id.nav_takeSnap) {
Intent CAMint = new Intent();
CAMint.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
CAMint.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(CAMint, ActivityStartCAM);
} else if (menuItemId == R.id.nav_addDetails) {
if (picpresent) {
switch (challenge) {
case "fitness":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.fitnessdialog);
ImageView fitim = (ImageView) d.findViewById(R.id.fitdialogimg);
TextView fittxt = (TextView) d.findViewById(R.id.fitdialogdesc);
d.show();
break;
case "maternity":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.maternitydialog);
ImageView matimg = (ImageView) d.findViewById(R.id.matdialogimg);
TextView mattxt = (TextView) d.findViewById(R.id.matdialogdesc);
d.show();
break;
case "child":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.childdialog);
ImageView chilimg = (ImageView) d.findViewById(R.id.childialogimg);
TextView chiltxt = (TextView) d.findViewById(R.id.childialogdesc);
d.show();
break;
}
}else{
Toast.makeText(CameraActivity.this, "Please select image", Toast.LENGTH_SHORT).show();
}
}
//
// CamBottomBar.mapColorForTab(0, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(1, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(2, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
rotateImage(setReducedImageSize());
IV.setScaleType(ImageView.ScaleType.CENTER_CROP);
if(!picpresent){
IV.setImageResource(R.drawable.selfieimage);
IV.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
}
public void TakePhoto(View v){
Intent CAMint= new Intent();
CAMint.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile=null;
try{
photoFile=createImageFile();
}catch(IOException e){
e.printStackTrace();
}
CAMint.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(CAMint, ActivityStartCAM);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==ActivityStartCAM && resultCode==RESULT_OK){
rotateImage(setReducedImageSize());
ImageUri = Uri.parse(ImageFileLoaction);
IV.setScaleType(ImageView.ScaleType.CENTER_CROP);
picpresent=true;
}
if (resultCode == RESULT_OK && requestCode==EDIT_IMAGE) {
/* Make a case for the request code we passed to startActivityForResult() */
/* Show the image! */
Uri editedImageUri = data.getData();
ImageUri=data.getData();
Glide.with(this).load(editedImageUri).into(IV);
picpresent=true;
}
}
File createImageFile()throws IOException{
String timestamp= new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFieldname="IMAGE "+timestamp+"_";
File storageDeirectory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image=File.createTempFile(imageFieldname,".jpg",storageDeirectory);
ImageFileLoaction=image.getAbsolutePath();
return image;
}
private Bitmap setReducedImageSize(){
int taretimagevieweidth=IV.getWidth();
int targetimageviewheight=IV.getHeight();
BitmapFactory.Options bmfop= new BitmapFactory.Options();
bmfop.inJustDecodeBounds=true;
BitmapFactory.decodeFile(ImageFileLoaction,bmfop);
int Cameraheight=bmfop.outHeight;
int Camerawidth=bmfop.outWidth;
int scalefactor =Math.min(Camerawidth/taretimagevieweidth,Cameraheight/targetimageviewheight);
bmfop.inSampleSize=scalefactor;
bmfop.inJustDecodeBounds=false;
return BitmapFactory.decodeFile(ImageFileLoaction,bmfop);
}
private void rotateImage(Bitmap bitmap){
ExifInterface exifInterface = null;
try{
exifInterface = new ExifInterface(ImageFileLoaction);
}catch(Exception e){
e.printStackTrace();
}
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
switch (orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
default:
}
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
IV.setImageBitmap(rotatedBitmap);
}
public void image(){
/* 1) Make a new Uri object (Replace this with a real image on your device) */
Uri imageUri = ImageUri;
/* 2) Create a new Intent */
Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
.setData(imageUri)
.build();
/* 3) Start the Image Editor with request code 1 */
startActivityForResult(imageEditorIntent,EDIT_IMAGE);
}
}
This is because you are using a version of Android 4.x, and the MultiDex is not correctly implemented. I solved this problem following the next steps:
Add the following lines in module.gradle
defaultConfig { multiDexEnabled true }
compile 'com.android.support:multidex:1.0.1'
Extend the class application from MultiDexApplication
Example:
public class Globalapplication extends MultiDexApplication implements IAviaryClientCredentials {...}
override attachBaseContext in the previous class
Example:
#Override
protected void attachBaseContext(Context base) {
MultiDex.install(this);
super.attachBaseContext(base);
}
for more information read:
NoClassDefFoundError with Android Studio on Android 4
https://developer.android.com/studio/build/multidex.html
According to Oracle documentation,
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
So, Definition of rx.subjects.PublishSubject is not found...
look at the packages it seems somehow you are not able to access the rx.subjects.PublishSubject package or is missing. make sure you are importing rx.subjects.*;

Problems with drawing on osm

I'm developing a little applicattion for androd to display
gps location witha bitmap. I used some example codes with google mmaps, but i haveto make it with maps forge. unfortunatelly i havent found any example codes or anything about how to write this drawing operation Colud anybody hel me?
My code is:
package hu.uniobuda.nik.k44hvx;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.mapsforge.android.maps.GeoPoint;
import org.mapsforge.android.maps.ItemizedOverlay;
import org.mapsforge.android.maps.MapActivity;
import org.mapsforge.android.maps.MapController;
import org.mapsforge.android.maps.MapView;
import org.mapsforge.android.maps.MapViewMode;
import org.mapsforge.android.maps.Overlay;
import org.mapsforge.android.maps.OverlayItem;
import org.mapsforge.android.maps.Projection;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Geocoder;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import android.widget.Toast;
public class Night_WatchActivity extends MapActivity {
MapView mapview;
public MapController mc;
private LocationManager locman;
private LocationListener loclis;
List<Overlay> mapOverlays;
static Drawable pointDefaultMarker;
MapOverlay pointsOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mapview = new MapView(this);
mapview.setClickable(true);
mapview.setBuiltInZoomControls(true);
mapview.setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
// mapview.setMapViewMode(MapViewMode.CANVAS_RENDERER);
//mapview.setMapFile("/sdcard/budapest.map");
mc = mapview.getController();
mc.setCenter(new GeoPoint(47.499619,19.046406));
mc.setZoom(17);
setContentView(mapview);
locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// loclis = new GPSLocationListener();
if(pointDefaultMarker==null){pointDefaultMarker = getResources().getDrawable(R.drawable.kepont);}
mapOverlays = mapview.getOverlays();
pointsOverlay = new MapOverlay(pointDefaultMarker);
mapOverlays.add(pointsOverlay);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loclis);
}
#Override
protected void onResume() {
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 10, loclis);
super.onResume();
}
#Override
protected void onPause() {
locman.removeUpdates(loclis);
super.onPause();
}
private class GPSLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if(location!=null){
GeoPoint gp = new GeoPoint(
(int)(location.getLatitude()*1E6),
(int)(location.getLongitude()*1E6));
OverlayItem item = new OverlayItem(gp,null,null);
pointsOverlay.justOneOverlay(item);
mc.setZoom(16);
mc.setCenter(gp);
mapview.invalidate();
String address = PointToLocation(gp);
Toast.makeText(getBaseContext(),
address,
Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public String PointToLocation(GeoPoint hely){
String s ="";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> adresses = gcd.getFromLocation(
hely.getLatitudeE6() / 1E6,
hely.getLongitudeE6()/1E6 , 1);
if(adresses.size()>0){
for(int i = 0; i < adresses.get(0).getMaxAddressLineIndex(); i++){
s += adresses.get(0).getAddressLine(i) + " ";
}
}
}catch(IOException exception){ exception.printStackTrace();}
return s;
}
}
class MapOverlay extends ItemizedOverlay<OverlayItem>{
private GeoPoint toDraw;
public GeoPoint getToDraw() {
return toDraw;
}
public void setToDraw(GeoPoint toDraw) {
this.toDraw = toDraw;
}
Paint p = new Paint();
private ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>();
private boolean drawLines = false;
public MapOverlay(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
populate();
}
public void addOverlay(OverlayItem overlay){
overlays.add(overlay);
populate();
}
public void justOneOverlay(OverlayItem newOverlay){
overlays.clear();
addOverlay(newOverlay);
}
#Override
protected OverlayItem createItem(int i) {
return overlays.get(i);
}
#Override
public int size() {
return overlays.size();
}
public boolean isDrawLines() {
return drawLines;
}
public void setDrawLines(boolean drawLines) {
this.drawLines = drawLines;
}
#Override
protected void drawOverlayBitmap(Canvas canvas, Point drawPosition,
Projection projection, byte drawZoomLevel) {
Point ScreenPoint = new Point();
mapview.getProjection().toPixels(toDraw, ScreenPoint);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.kepont);
canvas.drawBitmap(bmp,ScreenPoint.x,ScreenPoint.y-24, null);
}
}
}

Categories