Augmented reality android studio - java

I want to display some 3D models (.obj files) in android app using android studio.
The user enters some data from the storage and it should be placed relative to each other according to the user input.
So all I need is to display some 3D models from android storage which are placed relative to each other and the user will be able to see the models from any direction while swiping on the screen.
I don't know how to achieve this. I tried using the file chooser and various ways.
Any help or suggestions are welcome.
i have the java code below. where is wrong?
Thank you in advance.
public class add_booth extends AppCompatActivity {
ImageView image;
ViewRenderable name_booth;
private ModelRenderable renderable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_booth);
image = (ImageView)findViewById(R.id.Image2);
ArFragment arFragment = (ArFragment) getSupportFragmentManager()
.findFragmentById(R.id.scenefragment);
arFragment.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {
AnchorNode anchorNode = new AnchorNode(hitResult.createAnchor());
anchorNode.setRenderable(renderable);
arFragment.getArSceneView().getScene().addChild(anchorNode);
});
}
int requestcode = 1;
public void onActivityResult( int requestcode, int resulCode, Intent data)
{
super.onActivityResult(requestcode,resulCode,data);
Context context = getApplicationContext();
if (requestcode == requestcode && resulCode == Activity.RESULT_OK)
{
if (data == null)
{
return;
}
Uri uri = data.getData();
buildModel(uri);
}
}
private void buildModel(Uri uri) {
RenderableSource renderableSource = RenderableSource
.builder()
.setSource(this, Uri.parse(uri.getPath()), RenderableSource.SourceType.GLB)
.setRecenterMode(RenderableSource.RecenterMode.ROOT)
.build();
ModelRenderable
.builder()
.setSource(this, renderableSource)
.setRegistryId(uri.getPath())
.build()
.thenAccept(modelRenderable -> {
Toast.makeText(this, "Model built", Toast.LENGTH_SHORT).show();;
renderable = modelRenderable;
});
}
public void openFilechooser( View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent,requestcode);
}
}

Related

Uploading an image using activityResultLauncher , convert URI into bitmap

I am very new to this, and I am trying to put the pieces together so I will get the result I want. I don't really understand what I am doing wrong. The problem is when I am trying to put a profile photo, by the time I am pressing the selected photo to show on image view, the app crashes and I got a message like "URI cannot be null".
public class Profile extends AppCompatActivity {
private ImageView ProfileImg;
private String Tag;
private Uri imagePath = null;
private Uri imageUriPath;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
progressBar = findViewById(R.id.progressBar);
Button btnUpload = findViewById(R.id.btnUploadPhoto);
Button btnLogOut = findViewById(R.id.btnLogOut);
ProfileImg = findViewById(R.id.profile_img);
/* START ACTIVITY FOR RESULT*/
btnLogOut.setOnClickListener(view -> {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(Profile.this,MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
});
ProfileImg.setOnClickListener(view -> {
Intent photoIntent = new Intent(Intent.ACTION_PICK);
photoIntent.setType("image/*");
NewStartActivityForResult.launch(photoIntent);
});
btnUpload.setOnClickListener(view -> {
uploadImage();
});
/*Select photo from device*/
}
private ActivityResultLauncher<Intent> NewStartActivityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK){
Intent GotResults = result.getData();
if(GotResults == null)
{
Log.d(Tag,"InitializedActivityLaunchers: intent data is null");
return;
}
Uri imageUriPath = GotResults.getData();
GetImageInView();
}
});
private void uploadImage() {
FirebaseStorage.getInstance().getReference("images/" + UUID.randomUUID().toString()).putFile(imagePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful())
{
Toast.makeText(Profile.this, "Image Uploaded!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(Profile.this, "Something went Wrong!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void GetImageInView(){
Bitmap bitmap = null;
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUriPath);
}catch (IOException e){
e.printStackTrace();
}
}
I first had a problem with startOnActivityResult in which I had a line through the command saying that is deprecated and MediaStore.Images.Media.getBitmap in which I had the same "error", deprecated on getBitmap, and I tried to use the new methods watching tutorials and other forums, but I think I cannot connect the activityResultLauncher with Bitmap because the output of activityResultLauncher is Intent and Bitmap needs URI.
In NewStartActivityForResult , just manage code as mentioned below
From
Uri imageUriPath = GotResults.getData();
To
imageUriPath = GotResults.getData();
You are declaring and initalising variable instead of only initalising

How to pass data from a alertDialog to ActivityResultLauncher

I am creating an android app with a activity of showing an alertDialog to let user take a photo of a item.
// Inside AlertDialog on a Button Onclick function:
Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camIntent.putExtra("GET_PRODUCT_ID", product_id);
activityResultLauncherStartCamera.launch(camIntent);
On activityResultLauncher, how can i get the "product_id" ?
ActivityResultLauncher<Intent> activityResultLauncherStartCamera = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>(){
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK){
Intent data = result.getData();
// Both Return a null
String product_id = data.getStringExtra("GET_PRODUCT_ID")
String product_id = getIntent().getStringExtra("GET_PRODUCT_ID")
// Check if old image file exist...
}
}
}
);
I need to check if there is a same image file created before and delete it after the user complete to take a new images.
Can you try like following reference?
https://developer.android.com/training/basics/intents/result#custom
https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContracts.TakePicture
public class PickRingtone extends ActivityResultContract<Integer, Uri> {
#NonNull
#Override
public Intent createIntent(#NonNull Context context, #NonNull Integer ringtoneType) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, ringtoneType.intValue());
return intent;
}
#Override
public Uri parseResult(int resultCode, #Nullable Intent result) {
if (resultCode != Activity.RESULT_OK || result == null) {
return null;
}
return result.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
}
}

Problems with Simple OCR app using Firebase ML Kit

I am new to Android development but I have been learning on the way as I create my first OCR app using Firebase in Java. I essentially followed a youtube video to create the app but I had the following problems that I needed help with:
1) If I take the picture in landscape, the app can detect the text. However, when I take the picture in portrait, the captured image is rotated 90 degrees and the app cannot detect the text in the image. Whats the simplest way for me to resolve this?
2) Currently I take the picture with the phone's camera and this image is displayed in the app. I click my detect text button and the text appears. But I would like to see some bounding boxes on the images that shows what Firebase ML kit is seeing.
3) Also when I take a simple screenshot of a smartphone pin screen, the app can detect most of the numbers, but it always seems to miss one. I assume this is because I am using the local on phone version of Firebase ML kit, but is it possible to make it more accurate without running on cloud. I am currently using:
implementation 'com.google.firebase:firebase-core:15.0.2'
implementation 'com.google.firebase:firebase-ml-vision:16.0.0'
Thanks
The following is the code in my main activity (It pretty much the same thing on Firebase):
'''public class MainActivity extends AppCompatActivity {
Button captureImageBtn, detectTextBtn;
ImageView imageView;
TextView textView, outputText;
Bitmap imageBitmap;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Image Reader");
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
captureImageBtn = findViewById(R.id.capture_image_btn);
detectTextBtn = findViewById(R.id.detect_text_image_btn);
imageView = findViewById(R.id.image_view);
textView = findViewById(R.id.text_display);
outputText = findViewById(R.id.outputText);
outputText.setVisibility(View.INVISIBLE);
imageView.setImageResource(R.mipmap.mi2_foreground);
captureImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
textView.setText("");
}
});
detectTextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detectTextFromImage();
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
private void detectTextFromImage()
{
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionTextDetector firebaseVisionTextDetector = FirebaseVision.getInstance().getVisionTextDetector();
firebaseVisionTextDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
displayTextFromImage(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void displayTextFromImage(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.Block> blockList = firebaseVisionText.getBlocks();
if (blockList.size() == 0) {
Toast.makeText(MainActivity.this, "No Text Found in Image.", Toast.LENGTH_SHORT).show();
} else {
int i = 0;
String complete ="";
for (FirebaseVisionText.Block block : firebaseVisionText.getBlocks()) {
String text = block.getText();
complete = complete.concat(text+" ");
outputText.setVisibility(View.VISIBLE);
outputText.setText(complete);
}
}
}

Converting a video to a GIF

I am trying to make my app to accept videos from the phone's library to be uploaded and converted into GIF format. My code is giving out this build error though:-
error: <anonymous com.example.bim.Video2gif$2> is not abstract and does not override abstract method onReschedule(String,ErrorInfo) in UploadCallback
and also this warning on my onActivityResult method:-
Overriding method should call super.onActivityResult
The code is as below : -
public class Video2gif extends AppCompatActivity {
private Button uploadBtn;
private ProgressBar progressBar;
private int SELECT_VIDEO = 2;
private ImageView img1;
private DownloadManager downloadManager;
private Button download_btn;
private String gifUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video2gif);
MediaManager.init(this);
progressBar = findViewById(R.id.progress_bar);
MediaManager.init(this);
img1 = findViewById(R.id.img1);
uploadBtn = findViewById(R.id.uploadBtn);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickVideoFromGallery();
}
private void pickVideoFromGallery() {
Intent GalleryIntent = new Intent();
GalleryIntent.setType("video/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(GalleryIntent,
"select video"), SELECT_VIDEO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode == SELECT_VIDEO && resultCode == RESULT_OK) {
Uri selectedVideo = data.getData();
MediaManager.get()
.upload(selectedVideo)
.unsigned("myid")
.option("resource_type", "video")
.callback(new UploadCallback(){
#Override
public void onStart(String requestId) {
progressBar.setVisibility(View.VISIBLE);
Toast.makeText(Video2gif.this,
"Upload Started...", Toast.LENGTH_SHORT).show();
}
public void onProgress() {
}
public void onSuccess(String requestId, Map resultData) {
Toast.makeText(Video2gif.this, "Uploaded Succesfully",
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
uploadBtn.setVisibility(View.INVISIBLE);
String publicId = resultData.get("public_id").toString();
gifUrl = MediaManager.get().url().resourceType("video")
.transformation(new Transformation().videoSampling("25")
.delay("200").height(200).effect("loop:10").crop("scale"))
.resourceType("video").generate(publicId+".gif");
Glide.with(getApplicationContext()).asGif().load(gifUrl).into(img1);
download_btn.setVisibility(View.VISIBLE);
}
public void onError(String requestId, ErrorInfo error) {
Toast.makeText(Video2gif.this,
"Upload Error", Toast.LENGTH_SHORT).show();
Log.v("ERROR!!", error.getDescription());
}
});
}
}
}
I am also using Cloudinary to help process the video to GIF. Any help would be appreciated, many thanks!
When you’re using interfaces in android you need to include in your activity/fragment (override) the callback methods that they include. Also overriding some of the system methods requires you calling their super which means that many activities might be listening for the same callback when they inherit from one another. By adding the super in those callbacks you allow the result to travel through all of them. So in the case of the OnActivityResult just add the following line in your method:
super.onActivityResult(requestCode, resultCode, data);
For onReschedule you can let Android Studio generate that for you. Just go to Code->Generate-Override Methods and select the onReschedule

How to Retrieve videos from Firebase in app?

I want to add videos in firebase storage and retrieve all upload videos in-app through recycler view with card view.
Please give some reference or source code for this.
I am trying this for uploading video in firebase it is successfully uploaded but I am unable to retrieve it.
Thanks in advance.
public class VideoUplod extends AppCompatActivity
{
private static final int RC_PDF_PICKER = 2;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPDFStorageReference;
public static final int RC_SIGN_IN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_uplod);
VideoView videoView =(VideoView)findViewById(R.id.image);
//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
//specify the location of media file
Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.mp4");
//Setting MediaController and URI, then starting the videoView
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
mFirebaseStorage =FirebaseStorage.getInstance();
mChatPDFStorageReference = mFirebaseStorage.getReference().child("Video");
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PDF_PICKER);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
//for photo storage check
} else if (requestCode == RC_PDF_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPDFStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
#SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box so that the user can send it to the database
}
});
}
}
}
I'd take a look at:
Zero to App (video, source)
How to get an array with all pictures?
Firebase SDK for Cloud Storage docs
From the docs, it's pretty simple to download a file:
StorageReference videoRef = storageRef.child("videos/myvideo.mp4");
final long ONE_MEGABYTE = 1024 * 1024;
videoRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Transform bytes to a video, play
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

Categories

Resources