On screen rotate only video should be displayed - java

I have used exoPlayer Library what i am trying to do is i pass data from recyclerview to next activity that works fine video is been played and title as well as desc is been fetched but when i rotate the phone i only want simpleexovideoview to displayed and video is playing but the activity name is still there.
I have used < android:configChanges="orientation|screenSize" > that handles the orientation change following is snapshot of activity
Portrait view
Landscape view
and code is as follows
videoplayer.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.kaushal.myapplication.MainActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<android.support.constraint.Guideline
android:id="#+id/horizontalHalf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="256dp" />
<TextView
android:id="#+id/VideoTitle"
android:textSize="22sp"
android:text="video title"
android:textStyle="bold"
android:layout_margin="12dp"
android:textColor="#016699"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="#+id/horizontalHalf" />
<com.google.android.exoplayer2.ui.SimpleExoPlayerView
android:id="#+id/videoplayer"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:adjustViewBounds="true"
app:layout_constraintBottom_toTopOf="#+id/horizontalHalf"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="#+id/VideoDesc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:text="Video Desc"
app:layout_constraintLeft_toLeftOf="parent"
android:textSize="18sp"
android:layout_margin="12dp"
app:layout_constraintTop_toBottomOf="#+id/VideoTitle"
tools:layout_editor_absoluteY="477dp"
android:layout_marginLeft="12dp" />
</android.support.constraint.ConstraintLayout>
videoActivity
package com.example.kaushal.myapplication;
/**
* Created by kaushal on 06-09-2017.
*/
public class videoplay extends AppCompatActivity implements
ExoPlayer.EventListener {
TextView vidtitle, videodesc;
String videpath;
SimpleExoPlayer exoplayer;
SimpleExoPlayerView exoPlayerView;
PlaybackStateCompat.Builder videosessionBuilder;
final static String TAG = videoplay.class.getName();
private RelativeLayout.LayoutParams paramsNotFullscreen;
RelativeLayout rl;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videoplayer);
vidtitle = (TextView) findViewById(R.id.VideoTitle);
videodesc = (TextView) findViewById(R.id.VideoDesc);
exoPlayerView = (SimpleExoPlayerView)
findViewById(R.id.videoplayer);
vidtitle.setText(getIntent().getStringExtra("videotitle"));
videodesc.setText(getIntent().getStringExtra("videodesc"));
videpath = getIntent().getStringExtra("videourl");
mediaSession();
Uri uri = Uri.parse(videpath);
intializePlayer(uri);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
paramsnotfullscreen= (RelativeLayout.LayoutParams)exoPlayerView.getLayoutParams();
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(paramsnotfullscreen);
params.setMargins(0, 0, 0, 0);
params.height= ViewGroup.LayoutParams.MATCH_PARENT;
params.width=ViewGroup.LayoutParams.MATCH_PARENT;
params.addRule(RelativeLayout.CENTER_IN_PARENT);
exoPlayerView.setLayoutParams(params);
}else if (newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
exoPlayerView.setLayoutParams(paramsnotfullscreen);
}
} //refrence = https://stackoverflow.com/questions/13011891/make-a-fullscreen-in-only-layout-land-android-when-play-videoview
public void intializePlayer(Uri uri) {
DefaultTrackSelector dfs = new DefaultTrackSelector();
DefaultLoadControl dfc = new DefaultLoadControl();
exoplayer = ExoPlayerFactory.newSimpleInstance(this, dfs, dfc);
exoPlayerView.setPlayer(exoplayer);
//Prepare Media source
String useragent = Util.getUserAgent(this, "MyApplication");
MediaSource mediaSource = new ExtractorMediaSource(uri, new DefaultDataSourceFactory(this, useragent),
new DefaultExtractorsFactory(), null, null);
exoplayer.prepare(mediaSource);
exoplayer.setPlayWhenReady(true);
}
public void releasePlayer() {
exoplayer.stop();
exoplayer.release();
exoplayer = null;
}
public void mediaSession() {
MediaSessionCompat mediaSessionCompat = new MediaSessionCompat(this, TAG);
mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSessionCompat.setMediaButtonReceiver(null);
videosessionBuilder = new PlaybackStateCompat.Builder().setActions(PlaybackStateCompat.ACTION_PLAY |
PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE);
mediaSessionCompat.setPlaybackState(videosessionBuilder.build());
mediaSessionCompat.setCallback(new mediaSessionCallback());
mediaSessionCompat.setActive(true);
}
public class mediaSessionCallback extends MediaSessionCompat.Callback {
#Override
public void onPlay() {
exoplayer.setPlayWhenReady(true);
}
#Override
public void onPause() {
exoplayer.setPlayWhenReady(false);
}
#Override
public void onSkipToPrevious() {
exoplayer.seekTo(0);
}
}
//Exo player methods
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if ((playbackState == exoplayer.STATE_READY) && playWhenReady) {
Log.d(TAG, "Player running");
} else if (playbackState == exoplayer.STATE_READY) {
Log.d(TAG, "paused");
}
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
//When Activity is been destroyed
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
}
}

Here is an option called same-name-layout-land.xml layout that you can handle your landscape situation and Android will take it and inflate automatically when your device rotated, with this you can manage how your Activity should be shown to the user, as long as this cool option exist, you just have to put your VideoPlayer xml tag with "match_parent" for height and width in landscape version of your xml layout.
UPDATE:
Of course, if you want to your video player to take whole of screen, you have to delete the default margin of it, and for making toolbar disappear you have to create two different styles.xml. Put one into res/values-port and the other into res/values-land, and in the landscape version you have to choose a *.NoActionBar version of your themes for it.

Related

seekbar not working with video view when handle and move it

I am building a simple video player Ui and I have a : seekbar and two buttons to controle the video view, when I click on any point of seekbar every thing is ok and video view progress will be the same with seekbar and the buttons is working too ! but,when I handle the seekbar thumb and move it ,then leave it, every thing messing up and the seekbar and the buttons will never work again, so I am not getting an Exception error it's just will not work again. why that happening?
Activity
public class Player extends AppCompatActivity {
View controller;
Handler handler;
SeekBar seekBar;
VideoView videoView;
ImageButton play_btn, pause_btn;
ImageButton forward_btn, replay_btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
handler = new Handler();
videoView = (VideoView) findViewById(R.id.videoView);
controller = findViewById(R.id.player_controller); // the controller View
hideController(controller);
forward_btn = (ImageButton) findViewById(R.id.playerController_forward_10_Button);
replay_btn = (ImageButton) findViewById(R.id.playerController_replay_10_Button);
forward_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
forward_10_sec();
}
});
replay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reply_10_sec();
}
});
play_btn = (ImageButton) findViewById(R.id.playerController_playButton);
pause_btn = (ImageButton) findViewById(R.id.playerController_pauseButton);
play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play();
}
});
pause_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pause();
}
});
seekBar = findViewById(R.id.playerController_seekBar); // video seekBar
seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
videoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (controller.getVisibility() == View.INVISIBLE)
showController(controller);
else
hideController(controller);
}
});
Intent intent = getIntent();
if (intent != null)
setVideoSource(intent);
}
private void play() {
if(!videoView.isPlaying()) {
videoView.start();
play_btn.setVisibility(View.INVISIBLE);
pause_btn.setVisibility(View.VISIBLE);
}
}
private void pause() {
if(videoView.isPlaying()) {
videoView.pause();
pause_btn.setVisibility(View.INVISIBLE);
play_btn.setVisibility(View.VISIBLE);
}
}
private void forward_10_sec() {
if (videoView.canSeekForward())
videoView.seekTo(videoView.getCurrentPosition() + 1000);
}
private void reply_10_sec() {
if (videoView.canSeekBackward())
videoView.seekTo(videoView.getCurrentPosition() - 1000);
}
// to show the controllers
private void showController(View controller) {
controller.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
hideController(controller);
}
}, 6000);
}
// to hide the controllers
private void hideController(View controller) {
controller.setVisibility(View.INVISIBLE);
}
// to set video source from the main app or file manager
private void setVideoSource(Intent intent) {
... some codes to set path ...
play();
showController(controller);
updateSeekBarProgress();
}
// to move seekBar to real video progress
private void updateSeekBarProgress() {
Player.this.runOnUiThread(updateSeekBar);
}
private Runnable updateSeekBar = new Runnable() {
#Override
public void run() {
seekBar.setMax(videoView.getDuration() / 1000);
seekBar.setProgress(videoView.getCurrentPosition() / 1000);
seekBar.postDelayed(this,500);
}
};
SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
videoView.seekTo(i*1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
}
activity_player
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".Player">
<VideoView
android:id="#+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
android:id="#+id/player_controller"
layout="#layout/player_controller" />
</androidx.constraintlayout.widget.ConstraintLayout>
player_controller
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparent_black">
<ImageButton
android:id="#+id/playerController_playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/play_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/pause_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_replay_10_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/replay_10_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#id/playerController_playButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_forward_10_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/forward_10_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/playerController_playButton"
app:layout_constraintTop_toTopOf="parent" />
<SeekBar
android:id="#+id/playerController_seekBar"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:progressBackgroundTint="#color/white"
android:progressTint="#color/white"
android:secondaryProgressTint="#color/light_purple"
android:thumbTint="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/playerController_playButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
so, in a simple way : I want to set video view progress like seekbar progress with any way that I move the seek bar with.
(now it's just works when click on it and when handle and move it , nothing works again).
thanks...
It's finally has been done with that :
SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
videoView.seekTo(i * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(updateSeekBar);
pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
videoView.seekTo(seekBar.getProgress()*1000);
play();
updateSeekBarProgress();
}
};

ML Kit Firebase textDetection does not detect clearly

The project that show in textView after taked photo from camera. Using Firebase ML kit for text detection. That's not detect text clearly. It detect some of words but not detect all clearly. Using bitmap for it I don't if this bitmap make this problem. Should I use SurfaceView for camera? Or whats solution to solve that?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageButton
android:id="#+id/cameraButton"
android:layout_width="108dp"
android:layout_height="72dp"
android:layout_marginStart="44dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="32dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_camera_alt_24"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.427" />
<ImageButton
android:id="#+id/detectButton"
android:layout_width="108dp"
android:layout_height="72dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="44dp"
android:layout_marginBottom="41dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_done_outline_24"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.445" />
<ImageView
android:id="#+id/mImageView"
android:layout_width="0dp"
android:layout_height="346dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:scaleType="fitXY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_image_24" />
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:fontFamily="#font/segoeui"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mImageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageView mImageView;
ImageButton cameraBtn;
ImageButton detectBtn;
Bitmap imageBitmap;
TextView textView;
String log = "error";
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.mImageView);
cameraBtn = findViewById(R.id.cameraButton);
detectBtn = findViewById(R.id.detectButton);
textView = findViewById(R.id.textView);
textView.setTypeface(ResourcesCompat.getFont(this, R.font.segoeui));
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
textView.setText("");
}
});
detectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
detectTextFromImage();
}
});
}
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");
mImageView.setImageBitmap(imageBitmap);
}
}
private void detectTextFromImage() {
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionCloudTextRecognizerOptions options = new FirebaseVisionCloudTextRecognizerOptions.Builder()
.setLanguageHints(Arrays.asList("eng","hi"))
.build();
FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance()
.getCloudTextRecognizer(options);
Task<FirebaseVisionText> result =
detector.processImage(firebaseVisionImage)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
// Task completed successfully
// ...
displayTextFromImage(firebaseVisionText);
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
}
});
}
private void displayTextFromImage(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.TextBlock> blockList = firebaseVisionText.getTextBlocks();
if (blockList.size() == 0){
Toast.makeText(this,"No Text Found in image!",Toast.LENGTH_SHORT).show();
}
else{
for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) {
String text = block.getText();
textView.setText(text);
}
}
}
There's a sample app of text recognition on both iOS and Android platform at https://developers.google.com/ml-kit/samples (vision quickstart), and seems like both can detect the text within given image successfully?
private void displayTextFromImage(FirebaseVisionText firebaseVisionText) { List<FirebaseVisionText.TextBlock> blockList = firebaseVisionText.getTextBlocks(); if (blockList.size() == 0){ Toast.makeText(this,"No Text Found in image!",Toast.LENGTH_SHORT).show(); } else{ String text = ""; for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) { text = text + "\n" + block.getText(); textView.setText(text); } } }
By declaring and initializing String text inside for loop, will cause you lost the text of previous block. Actually, it takes each line as one block. Loop executes so fast, then you see only last line or last block of text set as your textview. Replace that code with this one, to resolve that issue.

Android RecyclerView item click not working - MVVM

The RecyclerView is showing all data, but the item click is not working. Here I am attaching what I have done so far. For better understanding I am removing all the unnecessary code.
This is my recyclerview item xml.
<data>
<variable
name="model"
type="com.xyz.abc.pojo.EmployeeListWithDesignationSetGet" />
<variable
name="viewModel"
type="com.xyz.abc.viewmodels.EmpListWithDesigViewModel" />
</data>
<LinearLayout
android:id="#+id/ll_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:onClick="#{() -> viewModel.itemClick(model)}">
<TextView
android:id="#+id/tv_show_details"
android:layout_width="70dp"
android:layout_height="30dp"
android:text="Show"
android:textColor="#FFFFFF" />
</LinearLayout>
The ViewModel class where I have written the click method.
public class EmpListWithDesigViewModel extends ViewModel {
private MutableLiveData<List<EmployeeListWithDesignationSetGet>> mutableLiveData;
private EmpListWithDesigClickListener listener;
private EmpListWithDesigRepository empListWithDesigRepository;
public void setListener(EmpListWithDesigClickListener listener) {
this.listener = listener;
}
public void init() {
if (mutableLiveData != null) {
return;
}
empListWithDesigRepository = EmpListWithDesigRepository.getInstance();
mutableLiveData = empListWithDesigRepository.getEmpList();
}
public MutableLiveData<List<EmployeeListWithDesignationSetGet>> getEmpList() {
return mutableLiveData;
}
public void itemClick(EmployeeListWithDesignationSetGet employeeListWithDesignationSetGet) {
listener.onItemClick(employeeListWithDesignationSetGet);
}
}
Now in activity I am implementing the click interface.
public class EmployeeDesignationActivity extends AppCompatActivity implements EmpListWithDesigClickListener {
private RecyclerView mRv_recyclerView;
private List<EmployeeListWithDesignationSetGet> arrayList;
private EmployeeListWithDesigAdapter employeeListWithDesigAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_designation);
setViewReferences();
arrayList = new ArrayList<>();
employeeListWithDesigAdapter = new EmployeeListWithDesigAdapter(this,arrayList);
mRv_recyclerView.setAdapter(employeeListWithDesigAdapter);
EmpListWithDesigViewModel empListWithDesigViewModel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(EmpListWithDesigViewModel.class);
empListWithDesigViewModel.setListener(this);
empListWithDesigViewModel.init();
empListWithDesigViewModel.getEmpList().observe(this, new Observer<List<EmployeeListWithDesignationSetGet>>() {
#Override
public void onChanged(List<EmployeeListWithDesignationSetGet> employeeListWithDesignationSetGets) {
arrayList.addAll(employeeListWithDesignationSetGets);
employeeListWithDesigAdapter.notifyDataSetChanged();
}
});
}
private void setViewReferences(){
mRv_recyclerView = findViewById(R.id.rv_activity_employee_designation);
}
#Override
public void onItemClick(EmployeeListWithDesignationSetGet employeeListWithDesignationSetGet) {
String phone = employeeListWithDesignationSetGet.getEmpPhone();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
startActivity(intent);
}
}
Pardon me if I have not provided enough info, this is my first SO post. Thanks
You should remove the android:onClick="#{() -viewModel.itemClick(model)}" from Linearlayout. Also add the below properties.
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
Then your item layout will be as below:
<LinearLayout
android:id="#+id/ll_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
>
<TextView
android:id="#+id/tv_show_details"
android:layout_width="70dp"
android:layout_height="30dp"
android:text="Show"
android:textColor="#FFFFFF" />
</LinearLayout>
Problem fixed. I forgot to bind the viewmodel in recyclerview adapter.

Set image as wallpaper from url (Glide + json)

app
app
Hi, thanks in advance to those who guide me.
I have a problem with the Set Wallpaper, that when I clicked on the button, I get the following error:
2018-12-28 22: 36: 02.801 13030-13030 /? E / AndroidRuntime: FATAL EXCEPTION: main
     java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress (android.graphics.Bitmap $ CompressFormat, int, java.io.OutputStream)' on a null object reference
I leave the files used.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:id="#+id/thumbnail2"
android:padding="5dp">
<TextView
android:id="#+id/txtclose"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:background="#drawable/circulo"
android:gravity="center"
android:text="#string/equis"
android:textColor="#android:color/background_light"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="end">
<Button
android:id="#+id/btn"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_marginBottom="25dp"
android:background="#drawable/borde_redondo"
android:text="Establecer como Fondo de Pantalla"
android:textColor="#ffffff" />
</FrameLayout>
</LinearLayout>
</LinearLayout>
public class infoanimales extends AppCompatActivity {
private RequestOptions options;
TextView txtclose;
LinearLayout img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_infoanimales);
Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWallpaper();
}
});
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
this.options = new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
String image_url = getIntent().getExtras().getString("img2");
img = findViewById(R.id.thumbnail2);
Glide.with(this).load(image_url).into(new SimpleTarget<Drawable>() {
#Override
public void onResourceReady(#NonNull Drawable fondoreceta, Transition<? super Drawable> transition) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
img.setBackground(fondoreceta);
}
}
});
TextView txtclose = findViewById(R.id.txtclose);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setWallpaper() {
Bitmap bitmap = BitmapFactory.decodeFile("img2");
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toast.makeText(this, "Listo", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
}
}
}
With this function, it works perfect, but that is having the images in the drawable folder, and what you want or what it is that you take the image of the json url, traide with glide
private void setWallpaper() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cochinito);
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toast.makeText(this, "Listo", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
}
}
In conclusion, what I need is that when you click on the button, the displayed image is set as wallpaper
As I can see, you are not using full path for decoding bitmap. You need to obtain full path name like:
String uri = Environment.getExternalStorageDirectory().toString() + "/" + PHOTO_DIR + "/test.jpg";
After that:
Bitmap bitmap = BitmapFactory.decodeFile(uri);
Reference
Set wallpaper with Glide4+ I did like this:
public void setAsWallpaper() {
Glide.with(requireContext())
.asBitmap()
.load(listItem.get(position).getWallpaperImage())
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
try {
WallpaperManager.getInstance(requireContext()).setBitmap(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}

Continuous Scanning QR using Zxing library, failed to open camera

I am creating a qr code scanning app, which continuously scan the qr code and show the result on the same screen without closing the camera.
I am using ZXing library but when I trigger the continuous scanning activity it fails to open the camera. I can't figure out the issue. Please check, I already added camera permission in my manifest.
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_above="#+id/buttonsLayout"
android:layout_alignParentTop="true">
</com.journeyapps.barcodescanner.DecoratedBarcodeView>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/buttonsLayout"
android:layout_toLeftOf="#+id/centerHorizont">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pause"
android:onClick="pause" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resume"
android:onClick="resume" />
</LinearLayout>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:id="#+id/centerHorizont" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/centerHorizont"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/buttonsLayout"
android:id="#+id/barcodePreview" />
</RelativeLayout>
Java Code:
public class ContinuousCaptureActivity extends Activity {
private static final String TAG = ContinuousCaptureActivity.class.getSimpleName();
private DecoratedBarcodeView barcodeView;
private BeepManager beepManager;
private String lastText;
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if(result.getText() == null || result.getText().equals(lastText)) {
// Prevent duplicate scans
return;
}
lastText = result.getText();
barcodeView.setStatusText(result.getText());
beepManager.playBeepSoundAndVibrate();
//Added preview of scanned barcode
ImageView imageView = (ImageView) findViewById(R.id.barcodePreview);
imageView.setImageBitmap(result.getBitmapWithResultPoints(Color.YELLOW));
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.continuous_scan);
barcodeView = (DecoratedBarcodeView) findViewById(R.id.barcode_scanner);
Collection<BarcodeFormat> formats = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39);
barcodeView.getBarcodeView().setDecoderFactory(new DefaultDecoderFactory(formats));
barcodeView.decodeContinuous(callback);
beepManager = new BeepManager(this);
}
#Override
protected void onResume() {
super.onResume();
barcodeView.resume();
}
#Override
protected void onPause() {
super.onPause();
barcodeView.pause();
}
public void pause(View view) {
barcodeView.pause();
}
public void resume(View view) {
barcodeView.resume();
}
public void triggerScan(View view) {
barcodeView.decodeSingle(callback);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
Here is the error message, I am getting!
The problem occur because of the permission. I have added code to request permission manually, Now problem is solved.
Thanks to #Roberto Manfreda

Categories

Resources