`Hello everyone, I'm here again.
I was given a task to load an image in .tif file format in android studio and then do a method of image tranformation (python code to handle image tranformation, such as gabor filter/transformation).
My problem: The android studio phone first has to load the .tif image from the real phone one imageview to display it in the app.
I have a question,
do .tif images really show up properly on the phone screen, because I can't see the .tif images on the screen?
what I used
Image transformation libry:
https://github.com/Beyka/Android-TiffBitmapFactory
python code run in Android Studio:
https://github.com/chaquo/chaquopy
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import org.beyka.tiffbitmapfactory.TiffBitmapFactory;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
TextView textView8;
//private static final int Read_Permission= 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button gallery = findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,3);
}
});
/*if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Read_Permission);
}
*/
textView8 = (TextView) findViewById(R.id.textView8);
if(!Python.isStarted()){
Python.start(new AndroidPlatform(this));
}
Python py = Python.getInstance();
PyObject pyobj = py.getModule("hello");
// give python script name
// now call this function
PyObject obj = pyobj.callAttr("main");
// now set return text to textview
textView8.setText(obj.toString());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && data != null){
try {
// from the Beyla original code
ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(data.getData(), "r");
Bitmap bmp = TiffBitmapFactory.decodeFileDescriptor(parcelFileDescriptor.getFd());
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Uri selectedImage = data.getData();
// ImageView imageView = findViewById(R.id.imageView);
// imageView.setImageURI(selectedImage);
}
}
}
And the 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"
tools:ignore="MissingClass">
<ImageView
android:id="#+id/imageView"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
tools:layout_editor_absoluteX="80dp"
tools:layout_editor_absoluteY="194dp"
tools:ignore="MissingConstraints" />
<Button
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Pick Image"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="125dp"
tools:layout_editor_absoluteY="556dp" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="33dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.436"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pick"
app:layout_constraintVertical_bias="0.2"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
`
Related
I wanted to to ask how could i store an image, that will take from gallery and store it to a specific folder.
the location i want to store is Shortcut/Images
i'm posting my code and i want solution after this how to store this image into the location above (The location is not yet created)..
Please keep in mind i want to store image in internal storage so that my app could run in hybrid phone as well
package com.example.mohitgupta.shortcut;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
public class GetImage extends AppCompatActivity {
EditText imageName;
private ImageButton img;
private String name;
private Uri selectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
imageName = (EditText) findViewById(R.id.ImageName);
name = imageName.getText().toString().trim();
}
public void GetImageIntent(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
selectedImage = data.getData();
img = (ImageButton) findViewById(R.id.imageSelected);
img.setImageURI(selectedImage);
}
}
public void SaveButtonClicked(View view){
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
Bitmap bitmap = drawable.getBitmap();
//Toast.makeText(GetImage.this,"Image Saved",Toast.LENGTH_SHORT).show();
}
}
layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.example.mohitgupta.shortcut.GetImage">
<ImageButton
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_margin="15dp"
android:layout_gravity="center"
android:id="#+id/imageSelected"
android:onClick="GetImageIntent"
android:scaleType="fitCenter"
android:backgroundTint="#000000"
android:src="#drawable/ic_add_a_photo_white_24dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_margin="15dp"
android:hint="Enter Name of Image"
android:id="#+id/ImageName"
android:padding="10dp"
android:background="#drawable/shapes"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Save"
android:onClick="SaveButtonClicked"/>
</LinearLayout>
It is an weird issue of firebase. I am posting data to firebase and sometimes it posted at the same time and some time it is not posting data on firebase. It is really weird and I am unable to understand why this is happening.
When I running app from android studio it posting data at the same time when i posting in app but after some time it behaves weird I am unable to post data.
package com.example.hp.heartful;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
public class NewsPost extends AppCompatActivity {
private ImageButton userImage;
private EditText title,userDesc;
private Button submitbtn;
private DatabaseReference mdatabase;
private Uri imageUri=null;
private ProgressDialog progress;
private StorageReference newsPhotos;
private FirebaseStorage mstorage;
private final static int GALLERY_REQUEST=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_post);
// FirebaseDatabase.getInstance().setPersistenceEnabled(true);
mstorage=FirebaseStorage.getInstance();
mdatabase= FirebaseDatabase.getInstance().getReference().child("News");
newsPhotos=mstorage.getReference().child("NewsImages");
submitbtn=(Button)findViewById(R.id.submit_button);
title=(EditText)findViewById(R.id.title);
userDesc=(EditText)findViewById(R.id.user_des);
progress=new ProgressDialog(this);
userImage=(ImageButton)findViewById(R.id.user_image);
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery=new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/jpeg");
gallery.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(gallery, "Complete action using"),GALLERY_REQUEST);
}
});
submitbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress.setMessage("News Posting, please wait...");
userPost();
}
});
}
private void userPost(){
final String postTitle=title.getText().toString();
final String postDes= userDesc.getText().toString();
if (!TextUtils.isEmpty(postTitle)&&!TextUtils.isEmpty(postDes)&&imageUri!=null){
progress.show();
StorageReference filePath=newsPhotos.child(imageUri.getLastPathSegment());
filePath.putFile(imageUri).addOnSuccessListener(this,new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost=mdatabase.push();
newPost.child("Title").setValue(postTitle);
newPost.child("Description").setValue(postDes);
newPost.child("Image").setValue(downloadUrl.toString());
progress.dismiss();
startActivity(new Intent(NewsPost.this,FragmentTwo.class));
}
});
}
else{
Toast.makeText(NewsPost.this,"Please fill all the blanks",Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GALLERY_REQUEST&&resultCode==RESULT_OK){
imageUri=data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
imageUri=resultUri;
userImage.setImageURI(imageUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(NewsPost.this, (CharSequence) error,Toast.LENGTH_LONG).show();
}
}
}
}
And this is newpost activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout 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="wrap_content"
android:orientation="vertical"
tools:context="com.example.hp.heartful.NewsPost">
<ImageButton
android:layout_width="wrap_content"
android:id="#+id/user_image"
android:layout_margin="16dp"
android:layout_height="wrap_content"
android:src="#mipmap/add_btn"/>
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="Title..."
android:inputType="textMultiLine"
android:paddingLeft="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/text_field_design"
android:id="#+id/title"
android:layout_marginBottom="16dp"
android:layout_below="#+id/user_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="8dp"
android:hint="Descriptions..."
android:inputType="textMultiLine"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:paddingLeft="16dp"
android:background="#drawable/text_field_design"
android:id="#+id/user_des"
android:layout_below="#+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<android.support.v7.widget.AppCompatButton
android:layout_width="match_parent"
android:text="Submit"
android:textColor="#FFF"
android:textSize="24dp"
android:layout_height="wrap_content"
android:background="#drawable/custom_button1"
android:id="#+id/submit_button"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true" />
</LinearLayout>
</ScrollView>
his is my first question in this web. I want to know if in the method onMarkerClick it if possible to change the visibility elements of a linearlayout.
This is my activity, if you use an event click of a button you can change the visibility of the elements. But if you use onMarkerClick I can not change it. I do not know if it's by the context. Is there any possibility of doing this? Sorry by my english.
package com.example.ivan.myapplicationmaps;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.io.UnsupportedEncodingException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import android.os.AsyncTask;
import org.json.JSONObject;
import android.view.Menu;
public class MainActivityDos extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener, View.OnClickListener {
private GoogleMap mMap;
// variables nuevas
private Button url_ruta;
//hasta aquí variables nuevas
private String origin;
private String destination;
private String point1;
private String point2;
//array de coordenadas
private String coordiantes;
private int n_points;
private String query;
private LinearLayout layoutBar, layoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_dos);
// 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);
layoutBar = (LinearLayout)findViewById(R.id.progressBarLayout);
layoutButton = (LinearLayout)findViewById(R.id.buttonsAudio);
url_ruta = (Button) findViewById(R.id.urlRuta);
url_ruta.setOnClickListener(this);
//coger lo que se envía en el intent;
Intent intent = getIntent();
Bundle bundle = intent.getExtras(); // estoy puede estar vacío
if(bundle != null){
//String rutaUrl = bundle.get("URL_RUTA").toString();
coordiantes = (bundle.get("COORDINATES").toString());
query = (bundle.get("QUERY").toString());
n_points = Integer.parseInt(bundle.get("POINTS").toString());
url_ruta.setText(query);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng OriginPoint = new LatLng(40.408272, -3.694506);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(OriginPoint, 16));
googleMap.setOnMarkerClickListener(this);
//mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
sendRequest();
}
#Override
public boolean onMarkerClick(Marker marker) {
if(marker.getTitle().equals("punto1")){
Toast.makeText(getApplicationContext(), "hola" , Toast.LENGTH_LONG).show();
//layoutButton.setVisibility(View.VISIBLE); //this is no working.
//cambiarLayout();
//layoutBar.setVisibility(View.VISIBLE);
}
return false;
}
public void sendRequest(){
try{
//String url = createUrl();
DownloadTask downloadTask = new DownloadTask(mMap,coordiantes);
downloadTask.execute(query);
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
layoutButton.setVisibility(View.VISIBLE); // this is working
layoutBar.setVisibility(View.VISIBLE);
}
}
//--------------------XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main_dos"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.ivan.myapplicationmaps.MainActivityDos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<Button
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter destination address"
android:id="#+id/urlRuta" />
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/progressBarLayout"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:weightSum="1"
android:layout_above="#+id/buttonsAudio"
android:layout_alignParentStart="true"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:background="#color/wallet_bright_foreground_disabled_holo_light"
android:visibility="invisible">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progressBar"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:max="100"
android:progress="0"/>
</LinearLayout>
<LinearLayout
android:id="#+id/buttonsAudio"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="1"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="#color/wallet_bright_foreground_disabled_holo_light"
android:visibility="invisible">
<Button
android:text="Play"
android:id="#+id/buttonFragment"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:text="Museo reina sofia y atocha refe"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/textView"
android:textSize="20sp"
android:layout_weight="1"
android:layout_marginLeft="5dp" />
</LinearLayout>
</RelativeLayout>
Here's the code I'm using to render a PDF called "answerkey.pdf" that's stored in "Download/Adobe Reader/answerkey.pdf"
package com.practice.pdftest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends Activity {
private ImageView imageView;
private Button next, previous;
private TextView tv;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage++;
render();
}
});
previous = (Button)findViewById(R.id.previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage--;
render();
}
});
// tv = (TextView)findViewById(R.id.testText);
// tv.setText(Environment.getExternalStorageDirectory().getAbsolutePath());
//
// Toast toast = Toast.makeText(getApplicationContext(),Environment.getExternalStorageDirectory().getAbsolutePath(),Toast.LENGTH_LONG);
// toast.show();
}
private void render() {
try {
imageView = (ImageView)findViewById(R.id.imageView);
int REQ_WIDTH = 1;
int REQ_HEIGHT = 1;
REQ_WIDTH = imageView.getWidth();
REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
PdfRenderer pdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0) {
currentPage=0;
}
else if (currentPage > pdfRenderer.getPageCount()) {
currentPage = pdfRenderer.getPageCount()-1;
}
Matrix matrix = imageView.getImageMatrix();
Rect rect = new Rect(0,0,REQ_HEIGHT,REQ_WIDTH);
pdfRenderer.openPage(currentPage).render(bitmap,rect,matrix,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(matrix);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's the layout.xml file I've made -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.practice.pdftest.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"
android:layout_weight="4"
android:background="#android:color/white"
android:layout_marginBottom="20dp"
/>
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:id="#+id/testText"-->
<!--android:text="Test"-->
<!--/>-->
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="2"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_marginTop="-100dp">
<Button
android:id="#+id/previous"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Previous"
/>
<Button
android:id="#+id/next"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
</LinearLayout>
For some reason, the PDF just isn't being displayed on screen, I keep getting a white, blank background. What am I doing wrong? Is the path incorrect? I have no SD card on my device. Or am I doing something wrong with the bitmap?
Is the path incorrect?
Yes.
I have no SD card on my device
That is fine. That would be removable storage. I am interpreting "Download/Adobe Reader/answerkey.pdf" as referring to something on external storage.
The recommended way to get this location would be to replace:
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
with:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Adobe Reader/answerkey.pdf");
Note that your app will need to request the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission, and that will involve runtime permissions on Android 6.0+ (if your targetSdkVersion is 23 or higher).
This is the content of the file: MainActivity.xml
package com.example.camera_test;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener()
{
#SuppressLint("NewApi") #Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
int i = Camera.getNumberOfCameras();
TextView age = (TextView) findViewById(R.id.textView1);
age.setText(i);
startActivityForResult( intent, 0 );
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
It was working good I clicked the button and it opened the camera application on my device !
But as soon as I added this lines:
int i = Camera.getNumberOfCameras();
TextView age = (TextView) findViewById(R.id.textView1);
age.setText(i);
Im getting the error on my device say nned to force close.
I tried also instead age.setText(I); this:
age.setText(Integer.toString(i));
I tried instead of id.textView1 also id.button1 but not working.
This is the content of activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="45dp"
android:layout_marginTop="62dp"
android:text="Activate The Camera" />
</RelativeLayout>
This is the only two files I did changes.
Solution. Now when I click the button I see the camera then take a photo click on Done then I see the image I took on a small window in my device !
This is the MainActivity.Java fileL:
package com.example.camera_test;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int CAMERA_PIC_REQUEST = 1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener()
{
#SuppressLint("NewApi") #Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
startActivityForResult( intent, CAMERA_PIC_REQUEST );
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
// do something
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(thumbnail);
}
}
}
And added to the activity_main.xml file imageView1 in the bottom:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="45dp"
android:layout_marginTop="62dp"
android:text="Activate The Camera" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Now it's all working ! Thanks.