Set image as wallpaper from url (Glide + json) - java

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();
}
}
});
}

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.

Why is my PDFRenderer so small?

I have a workking PDF downloader and PDFRenderer. I am using openFileInput method to keep the file secure from scanners. My problem is the Bitmap generated is so small it cannot be read. I tried to use like every example recommended but I cannot get it to load the APK too many logcats to list. There are none with this version. Device is Galaxy S6 I only have AMD computers so no emulators here and NO SDCard recommendations for security reasons I am using APP Specific storage
Screenshot of PDFRenderer Bitmap:
XML code:
<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"
android:orientation="vertical"
tools:context="net.madjobber.pdfdemo.PDFRender">
<ImageView
android:id="#+id/image"
android:layout_width="371dp"
android:layout_height="437dp"
android:layout_weight="1"
android:scaleType="fitCenter"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintHorizontal_bias="0.0" />
<Button
android:id="#+id/previous"
android:layout_width="160dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="previous"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/image"
app:layout_constraintRight_toLeftOf="#+id/next"
android:layout_marginRight="8dp"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintHorizontal_bias="0.0" />
<Button
android:id="#+id/next"
android:layout_width="160dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="next"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="0dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/image"
app:layout_constraintVertical_bias="0.0" />
Downloader Java:
public class MainActivity extends AppCompatActivity {
Button btn;
String fileDownloadPath = "https://www.ets.org/Media/Tests/GRE/pdf/gre_research_validity_data.pdf";
String saveFilePath = "";
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this,"","File is Being Downloaded",true);
new Thread(new Runnable() {
#Override
public void run() {
downloadFile(fileDownloadPath,saveFilePath);
}
}).start();
}
});
}
public void downloadFile(String fileDownloadPath,String saveFilePath)
{
try {
URL u = new URL(fileDownloadPath);
URLConnection con = u.openConnection();
int lengthofContent=con.getContentLength();
DataInputStream DIStream=new DataInputStream(u.openStream());
byte[] buffer=new byte[lengthofContent];
DIStream.readFully(buffer);
DIStream.close();
DataOutputStream DOStream=new DataOutputStream(new FileOutputStream(getApplicationContext().getFilesDir() + "/" + "PDF.pdf"));
DOStream.write(buffer);
DOStream.flush();
DOStream.close();
hideProgressIndicator();
}
catch (FileNotFoundException e){
hideProgressIndicator();
}
catch (IOException e) {
}
catch (Exception e){
}
}
private void hideProgressIndicator() {
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
});
}
public void PDFRenderer (View view) {
Intent intent = new Intent(MainActivity.this, PDFRender.class);
startActivity(intent);
}
}
PDFRenderer JAVA:
public class PDFRender extends AppCompatActivity {
private ImageView imageView;
private int currentPage = 0;
private Button next,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfrender);
next =(Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage++;
render();
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage--;
render();
}
});
render();
}
private void render() {
//open PDF from internal storage and pass the variable to renderer
String Path = getApplicationContext().getFilesDir().getPath();
File file = new File( Path +"/PDF.pdf");
try{
imageView = (ImageView) findViewById(R.id.image);
int REQ_WIDTH = imageView.getWidth();
int REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if (currentPage < 0){
currentPage = 0;
}else if (currentPage > renderer.getPageCount()) {
currentPage = renderer.getPageCount() - 1;
}
Matrix m = imageView.getImageMatrix();
Rect rect =new Rect(0, 0, REQ_WIDTH, REQ_HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(m);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
}catch (Exception e) {
e.printStackTrace();
}
}
Any Help will be greatly appreciated as even with cheater glasses I cannot read the PDF. Thank you in advance!!

On screen rotate only video should be displayed

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.

Error on Camera application on Android Studio

Hi
I created a custom camera app with SurfaceView and when running the app, it just freezes the whole phone and shows black screen. When running on AVD, gives this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Camera$Parameters android.hardware.Camera.getParameters()' on a null object reference
It's referencing the line where parameters = camera.getParameters(); is called
Here's the code:
CameraActivity.java
public class CameraActivity extends Activity implements SurfaceHolder.Callback{
android.hardware.Camera camera;
#InjectView(R.id.s)
SurfaceView surfaceView;
#InjectView(R.id.takeaphoto)
ImageView imageView;
SurfaceHolder surfaceHolder;
android.hardware.Camera.PictureCallback callback;
android.hardware.Camera.ShutterCallback shutterCallback;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera_activity);
ButterKnife.inject(this);
surfaceHolder=surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cameraImage();
}
});
callback = new android.hardware.Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes, android.hardware.Camera camera) {
FileOutputStream outputStream=null;
File file_image = getDirc();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyymmddhhmms");
String date = simpleDateFormat.format(new Date());
String photo_file="PI_"+date+".jpg";
String file_name = file_image.getAbsolutePath()+"/"+photo_file;
File picfile=new File(file_name);
try {
outputStream=new FileOutputStream(picfile);
outputStream.write(bytes);
outputStream.close();
}catch (FileNotFoundException e){}
catch (IOException ex){}
finally {
}
refreshCamera();
refreshGallery(picfile);
try {
camera.stopPreview();
}catch (Exception e){}
try{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){}
}
};
}
private void refreshGallery(File file){
Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
}
public void refreshCamera(){
if (surfaceHolder.getSurface() == null){
return;
}
}
private File getDirc(){
File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(dics ,"Camera");
}
public void cameraImage(){
camera.takePicture(null , null ,callback);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try{
camera = android.hardware.Camera.open();
}catch (RuntimeException ex){
}
android.hardware.Camera.Parameters parameters;
parameters = camera.getParameters();
parameters.setPreviewFrameRate(30);
parameters.setPreviewSize(353 , 288);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
camera.release();
camera=null;
}
}
camera_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/s">
</SurfaceView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/rel2"
android:background="#color/colorPrimaryDark"
android:layout_alignParentBottom="true">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/images"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:layout_alignParentEnd="true"
android:src="#drawable/menu"
/>
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/takeaphoto"
android:src="#drawable/button"
android:layout_alignTop="#+id/images"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/rel1"
android:background="#color/colorPrimaryDark"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="30dp"
android:layout_marginEnd="10dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/switchcamera"
android:id="#+id/imageView" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>

Categories

Resources