How to make a RecylerView like WhatsApp Chat activity? - java

I building an app which should have a layout almost identical to the one used in WhatsApp in the chat activity. it should have a text input, camera & video recording option. Items should be centered inside the recycler and when the dataset is changed the recycler should scroll to the last item added. when the user clicks on the Editext keyboard should resize the view moving recycler up and focus on the last item in the Dataset.
For the scrolling part, I have used SmoothScrollToPosiotion but when an item, which contains an image or a video, the view gets chopped, auto scroll also stops working. a weird bug is when I open the keyboard by clicking on editText the recycler scrolls almost to the last item but not completely, only if reopen the keyboard multiple times it shows the item completely.
already tried solutions found on google, and here with not expected results :(
EDIT: almost solved, I have just moved SmoothScrollToposition inside the onClickListener of every button. Now it does not scroll to the last item it just scrolls to the item before the last but completely :D
here some code:
(if needed full code at https://github.com/MikeSys/ChatApp)
MainActivity Layout
<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=".MainActivity">
<android.support.v7.widget.RecyclerView
android:background="#drawable/sfondo"
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintTop_toTopOf="parent"
/>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="55dp"
app:layout_constraintBottom_toBottomOf="parent"
android:orientation="horizontal">
<EditText
android:layout_gravity="center_vertical"
android:id="#+id/editText"
android:layout_width="255dp"
android:layout_height="55dp"
android:background="#0003A9F4"
android:hint="Scrivi"
android:padding="10dp" />
<Button
android:layout_gravity="center_vertical"
android:id="#+id/camera"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/camera"
/>
<Button
android:layout_gravity="center_vertical"
android:id="#+id/video"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/video"
/>
<Button
android:id="#+id/send"
android:layout_width="55dp"
android:layout_height="55dp"
android:background="#drawable/send" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
MainActivity Code
public class MainActivity extends AppCompatActivity {
private ArrayList<ModelloDati> dati = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private static final String VIDEO_DIRECTORY = "/Chat";
private myAdapter adapter;
public Uri passUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Variables-----------------------------------------
final RecyclerView recyclerView = findViewById(R.id.recyclerView);
Button video = findViewById(R.id.video);
Button camera = findViewById(R.id.camera);
Button send = findViewById(R.id.send);
final EditText editText = findViewById(R.id.editText);
// Layout Manager------------------------------------------------
linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(linearLayoutManager);
// Adapter-----------------------------------------
if(dati.size()> 1){
adapter = new myAdapter(dati, this);
//Removed SmoothScroll form here
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
else{
Collections.reverse(dati);
adapter = new myAdapter(dati,this);
recyclerView.setAdapter(adapter);
}
// Click Listener Video button---------------------------------------------
video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent,0);
//Added here SmotthScroll
recyclerView.smoothScrollToPosition(dati.size());
}
});
// Click Listener Camera button--------------------------------------------
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,1);
//Added here SmotthScroll
recyclerView.smoothScrollToPosition(dati.size());
}
});
// Click Listener Send button----------------------------------------------
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = editText.getText().toString();
dati.add(new ModelloDati(0,string));
editText.getText().clear();
//Added here SmotthScroll
recyclerView.smoothScrollToPosition(dati.size());
closeKeyboard();
}
});
}
private void closeKeyboard() {
View view = getCurrentFocus();
if(view != null){
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 0:
try {
Uri contentURI = data.getData();
passUri = contentURI;
String recordedVideoPath = getPath(contentURI);
Log.d("frrr", recordedVideoPath);
saveVideoToInternalStorage(recordedVideoPath);
dati.add(new ModelloDati(2, contentURI));
}catch (Throwable o){Log.i("CAM","User aborted action");}
case 1:
try {
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
dati.add(new ModelloDati(1,bitmap));
}catch(Throwable o){
Log.i("CAM","User aborted action");
}
}
}
private void saveVideoToInternalStorage (String filePath) {
File new file;
try {
File currentFile = new File(filePath);
File wallpaperDirectory = new
File(Environment.getExternalStorageDirectory() + VIDEO_DIRECTORY);
newfile = new File(wallpaperDirectory,
Calendar.getInstance().getTimeInMillis() + ".mp4");
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v("vii", "Video file saved successfully.");
}else{
Log.v("vii", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}

Solved by Moving smoothScrollToPosition inside onClickListerner (video/camera button I had to move it inside onActivityResult).
Updated Main
public class MainActivity extends AppCompatActivity {
private ArrayList<ModelloDati> dati = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private static final String VIDEO_DIRECTORY = "/Chat";
private myAdapter adapter;
private RecyclerView recyclerView;
private VideoView videoView;
public Uri passUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Variables-----------------------------------------
recyclerView = findViewById(R.id.recyclerView);
Button video = findViewById(R.id.video);
Button camera = findViewById(R.id.camera);
Button send = findViewById(R.id.send);
final EditText editText = findViewById(R.id.editText);
// Layout Manager------------------------------------------------
linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setStackFromEnd(true);
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(itemAnimator);
// Adapter-----------------------------------------
//adapter.notifyDataSetChanged();
adapter = new myAdapter(dati, this);
recyclerView.setAdapter(adapter);
// Click Listener Video button----------------------------------------------
video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent,0);
}
});
// Click Listener Camera button----------------------------------------------
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,1);
}
});
// Click Listener Send button------------------------------------------------
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = editText.getText().toString();
dati.add(new ModelloDati(0,string));
adapter.notifyItemInserted(dati.size());
editText.getText().clear();
recyclerView.smoothScrollToPosition(dati.size());
closeKeyboard();
}
});
}
private void closeKeyboard() {
View view = getCurrentFocus();
if(view != null){
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 0:
try {
Uri contentURI = data.getData();
passUri = contentURI;
String recordedVideoPath = getPath(contentURI);
saveVideoToInternalStorage(recordedVideoPath);
dati.add(new ModelloDati(2, contentURI));
adapter.notifyItemInserted(dati.size());
recyclerView.smoothScrollToPosition(dati.size());
}catch (Throwable o){Log.i("CAM","User aborted action");}
case 1:
try {
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
dati.add(new ModelloDati(1,bitmap));
adapter.notifyItemInserted(dati.size());
recyclerView.smoothScrollToPosition(dati.size());
}catch(Throwable o){
Log.i("CAM","User aborted action");
}
}
}
private void saveVideoToInternalStorage (String filePath) {
File newfile;
try {
File currentFile = new File(filePath);
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() +
VIDEO_DIRECTORY);
newfile = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis()
+ ".mp4");
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v("vii", "Video file saved successfully.");
}else{
Log.v("vii", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}

Related

Image not save in the device when click the button

Currently, I am using the Picasso library to download images and save it in the device when I press the button. the problem is when I press the button the image not download and just shown the message "Image Downloaded" , so how can i fix it? Here is my code
PicassoDisplayImageAdapter.java
/*
* This class for display the image when clicking on it
* It gets the data from the class have the images "Images in ArrayList"
* Also It is for download images
*/
public class PicassoDisplayImageAdapter extends AppCompatActivity {
public static final int PERMISSION_WRITE = 0;
String fileUri;
Button download_image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_image);
/* Display the data in the ImageView with Picasso "ImageView that insert in he activity" */
final ImageView imageView = findViewById(R.id.image_display);
final Intent intent = getIntent();
if (intent.hasExtra("imageUrl")){
String url = intent.getStringExtra("imageUrl");
Picasso.with(this)
.load(url)
.fit() // to resize the image to imageView
.placeholder(R.drawable.progress_animation)
.error(R.drawable.error)
.into(imageView);
}
/* button to download the image */
download_image = findViewById(R.id.button_download);
checkPermission();
download_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
});
}
/* method to save image*/
private void SaveImage(String url) {
Picasso.with(getApplicationContext()).load(url).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File mydir = new File(Environment.getExternalStorageDirectory() + "/11zon");
if (!mydir.exists()) {
mydir.mkdirs();
}
fileUri = mydir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
FileOutputStream outputStream = new FileOutputStream(fileUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Image Downloaded", Toast.LENGTH_LONG).show();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
/* runtime storage permission */
public boolean checkPermission() {
int READ_EXTERNAL_PERMISSION = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if((READ_EXTERNAL_PERMISSION != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_WRITE);
return false;
}
return true;
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==PERMISSION_WRITE && grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//do somethings
}
}
}
ImagesRamadanActivity.java That has the data
/*
* This Activity for display the ramadan images
* This class has the data of images
*/
public class ImagesRamadanActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ramadan_images);
/* ArrayList for RamadanImages */
final String[] RamadanImages = {
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
};
/* make new object and find the view "GridView" */
GridView gridView2 = findViewById(R.id.gridview_image_ramadan);
// display all the images from Array on it
gridView2.setAdapter(new PicassoImagesAdapter(ImagesRamadanActivity.this, RamadanImages));
/* display the image when click on it */
// we made a class for this method "the class called PicassoDisplayImageAdapter"
gridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the image
String image = RamadanImages[position];
Intent intent = new Intent(ImagesRamadanActivity.this, PicassoDisplayImageAdapter.class);
intent.putExtra("imageUrl", image);
ImagesRamadanActivity.this.startActivity(intent);
}
});
activity_image_display.xml activity to display the photo and has the button to download the image
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image_display"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageView>
<Button
android:id="#+id/button_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="download the image"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0dp" />
</RelativeLayout>
Inside,
onCreate(){
setContentView(..);
// requestPermission. ask for permission when app starts.
}
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
// kind of this, add this block to your existing code.
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to save files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
// make sure Manifest has all the permission defined

How to retrieve a photo from the camera for gridview?

I'm developing an app that, in the first activity, it takes a photo saved, and it is shown in an imageview, but at the same time I want a gridview to be created in another activity, which will recover each captured image, showing in order.
So far I can take a picture, save it in the gallery, and show it on the imageview, but when I go to the other activity, it shows the gridview retrieving all the photos from the gallery, could someone help me? This is my schedule:
Activity in which you take the photo and save it:
public class Main2Activity extends AppCompatActivity {
private Uri uri;
private static final int CAMERA = 1;
private String caminhoDaImagem;
ImageView imageViewFoto;
private EditText etCliente;
private EditText etPostes;
private EditText etObservacao;
String mCurrentPhotoPath;
String imgSaved;
private Button botao;
#Override
public void onBackPressed() { //Botão BACK padrão do android
startActivity(new Intent(this, MainActivity.class)); //O efeito ao ser pressionado do botão (no caso abre a activity)
//finishAffinity(); //Método para matar a activity e não deixa-lá indexada na pilhagem
return;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final Button btnSalvarRelatorio = (Button) findViewById(R.id.btnAvancar);
Button btnAvancar = (Button) findViewById(R.id.btnAvancar);
//CÓDIGO NECESSÁRIO PARA A PERMISSÃO A MEMÓRIA INTERNA
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
}
//PERMISSÃO DE ACESSO Á CAEMRA
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
}
findViewById(R.id.btnTirarFotos).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tirarFoto();
}
});
findViewById(R.id.btnAvancar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chamar3Activity();
}
});
}
/*public void onRequestPermissionResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResult) {
switch (requestCode) {
case 1000:
if (grantResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permissão Concedida!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permissão não Concedida!", Toast.LENGTH_SHORT).show();
finish();
}
}
}*/
private void chamar3Activity() {
Intent novaintent = new Intent();
novaintent.setClass(Main2Activity.this, Main3Activity.class);
startActivity(novaintent);
finish();
}
//DANDO A FUNÇÃO AO BOTÃO DE TIRAR FOTO
public void tirarFoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
//SALVANDO IMAGEM DA CAMERA E DIRECIONANDO ELA A UM IMAGEVIEW
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
File file = null;
try {
file = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
}
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.imageView2);
imageview.setImageBitmap(image);
// Chame este método pra obter a URI da imagem
Uri uri = getImageUri(getApplicationContext(), image);
// Em seguida chame este método para obter o caminho do arquivo
File file = new File(getRealPathFromURI(uri));
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "CANCELADO", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_LONG).show();
return image;
}
** Activity where the Grid View will be shown: **
public class MainActivity extends AppCompatActivity {
GridView gv;
ArrayList<File> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = imageRead(Environment.getExternalStorageDirectory());
gv = (GridView) findViewById(R.id.gv);
gv.setAdapter(new GridAdapter());
}
class GridAdapter extends BaseAdapter{
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.single_grid, parent, false);
ImageView imageView = convertView.findViewById(R.id.imageView);
imageView.setImageURI(Uri.parse( getItem(position) . toString()));
return convertView;
}
}
ArrayList<File> imageRead(File root){
ArrayList<File> a = new ArrayList<>();
File[] files = root.listFiles();
for(int i =0; i< files.length; i++){
if(files[i].isDirectory()){
a.addAll(imageRead(files[i]));
}
else{
if( files[i].getName().endsWith(".jpg")){
a.add(files[i]);
}
}
}
return a;
}

Take image from camera or gallery and show in activity

I want to write a module where on a click of a button, the camera opens and I can click and capture an image. If I don't like the image, I can delete it and click one more image, and then select the image and it should return back and display that image in the activity.
The problem comes when I took a picture the camera application gets crashed and when I took a picture from the gallery the pic doesn't show in image view.
This is the script I wrote:
public class MainpageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
Toolbar toolbar = findViewById(R.id.toolbar);
imageView = (ImageView)this.findViewById(R.id.imageView1);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_camera_alt_black_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ RxPermissions rxPermissions = new RxPermissions(MainpageActivity.this);
rxPermissions
.request(Manifest.permission.CAMERA) // ask single or multiple permission once
.subscribe(granted -> {
if (granted) {
selectImage();
} else {
Toast.makeText(MainpageActivity.this, "Permission of camera is denied", Toast.LENGTH_SHORT).show();
}
});
}
});
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainpageActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
imageView.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable=new BitmapDrawable(thumbnail);
imageView.setBackgroundDrawable(drawable);
}
}
}
}
#Uma : Please follow this steps and change your code.
Step 1 - add both two line in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And also add this properties in application tag in manifest file:
android:largeHeap="true"
android:hardwareAccelerated="false"
Step - 2 - import lib in build.gradle file
implementation 'com.karumi:dexter:4.2.0' // for handling runtime permissions
Step - 3 - In your MainpageActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
this.fab = (FloatingActionButton) this.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CheckPermission();
}
});
}
private void CheckPermission(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
selectImage();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// permission is denied permenantly, navigate user to app settings
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
})
.onSameThread()
.check();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}}
Hope it helps you.
I think you should try to add this "android:required="true".
<uses-feature android:name="android.hardware.camera"
android:required="true" />
First of all, you need to handle with permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
After this, you can use this for opening gallery with button
//opening image chooser option
choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
And with this function, you can show the image on UI
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//getting image from gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
image.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Also, you can convert image to bitmap64:
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

set wallpaper button of image from firebase database

I'm trying to add a set wallpaper button to my app that will set the wallpaper when I pull my image from firebase database. This is what I have so far. I've set the button up to automatically show up on every wallpaper snap shot. I've set a wallpaper in the past when the picture was stored on the phone but cant seem to figure out how to set it when pulling an image from firebase.
public class WallpapersAdapter extends RecyclerView.Adapter<WallpapersAdapter.WallpaperViewHolder> {
private Context mCtx;
private List<Wallpaper> wallpaperList;
public WallpapersAdapter(Context mCtx, List<Wallpaper> wallpaperList) {
this.mCtx = mCtx;
this.wallpaperList = wallpaperList;
}
#NonNull
#Override
public WallpaperViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_wallpapers, parent, false);
return new WallpaperViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WallpaperViewHolder holder, int position) {
Wallpaper w = wallpaperList.get(position);
holder.textView.setText(w.title);
Glide.with(mCtx)
.load(w.url)
.into(holder.imageView);
if(w.isFavorite){
holder.checkBoxFav.setChecked(true);
}
}
#Override
public int getItemCount() {
return wallpaperList.size();
}
class WallpaperViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, CompoundButton.OnCheckedChangeListener{
TextView textView;
ImageView imageView;
CheckBox checkBoxFav;
ImageButton buttonShare, buttonDownload;
Button setWallpaper;
public WallpaperViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view_title);
imageView = itemView.findViewById(R.id.image_view);
checkBoxFav = itemView.findViewById(R.id.checkbox_favorite);
buttonShare = itemView.findViewById(R.id.button_share);
buttonDownload = itemView.findViewById(R.id.button_download);
setWallpaper = itemView.findViewById(R.id.set_wallpaper);
setWallpaper.setOnClickListener(this);
checkBoxFav.setOnCheckedChangeListener(this);
/*buttonShare.setOnClickListener(this);*/
/*buttonDownload.setOnClickListener(this);*/
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_share:
shareWallpaper(wallpaperList.get(getAdapterPosition()));
break;
case R.id.button_download:
downloadWallpaper(wallpaperList.get(getAdapterPosition()));
break;
case R.id.set_wallpaper:
setWallpaper(wallpaperList.get(getAdapterPosition()));
break;
}
}
private void shareWallpaper(Wallpaper w){
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
Glide.with(mCtx)
.asBitmap()
.load(w.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(resource));
mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
}
});
}
private Uri getLocalBitmapUri(Bitmap bmp){
Uri bmpUri = null;
try {
File file = new File(mCtx.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"the_wallpaper_app_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
private void downloadWallpaper(final Wallpaper wallpaper){
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
Glide.with(mCtx)
.asBitmap()
.load(wallpaper.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = saveWallpaperAndGetUri(resource, wallpaper.id);
if(uri != null){
intent.setDataAndType(uri, "image/*");
mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
}
}
});
}
private Uri saveWallpaperAndGetUri(Bitmap bitmap, String id){
if(ContextCompat.checkSelfPermission(mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", mCtx.getPackageName(), null);
intent.setData(uri);
mCtx.startActivity(intent);
}else{
ActivityCompat.requestPermissions((Activity) mCtx, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100 );
}
return null;
}
File folder = new File(Environment.getExternalStorageDirectory().toString() + "/the_wallpaper_app" );
folder.mkdirs();
File file = new File(folder, id + ".jpg" );
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
return Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(FirebaseAuth.getInstance().getCurrentUser() == null){
Toast.makeText(mCtx, "Please login first", Toast.LENGTH_LONG).show();
compoundButton.setChecked(false);
return;
}
int position = getAdapterPosition();
Wallpaper w = wallpaperList.get(position);
DatabaseReference dbFavs = FirebaseDatabase.getInstance().getReference("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child("favorites")
.child(w.category);
if(b){
dbFavs.child(w.id).setValue(w);
}else{
dbFavs.child(w.id).setValue(null);
}
}
}
private void setWallpaper(Wallpaper set) {
};
}
}
You can not directly set the image from database as wallpaper on your android device, for that first you have to download the image to your device and then you can set it as the background wallpaper.
You can use createTempFile(String prefix, String suffix) which creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
Read more about this here.
If you'd rather want to store the file in your app directory, you can use a code like this:
File dir = new File(Environment.getExternalStorageDirectory(), "dir_name");
// Create dir if not exists
if(!dir.exists()) dir.mkdirs();
File mFile = new File(dir, "file_name");
Also to get bitmap from the file and use it to set as wallpaper, you may use a code similar to this:
Bitmap bitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath());
//after converting it to bitmapDrawable you can set it as background using this
getWindow().setBackgroundDrawable
You may also use WallpaperManager for this like:
WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);

Layout doesn't show up when I run the app

When I run the app it doesn't show up any layout just a blank page
This is my Java code:
public class MainActivity extends AppCompatActivity {
private boolean zoomOut = false;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
Button btnSelect;
LinearLayout root ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
Point point = null;
getWindowManager().getDefaultDisplay().getSize(point);
int width = point.x;
int height = point.y;
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.getLayoutParams().width = 20;
ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.MATCH_PARENT,
GridLayout.LayoutParams.WRAP_CONTENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut =false;
}else{
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
}
This is my xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp" >
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/SelectPhoto" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I've been advised that is was because onCreate wasn't placed properly but the I resolved that it's still not showing anything at all.
Please check your .Xml file name is matches with
setContentView(R.layout.activity_main);

Categories