I have the Problem that the Dialog Box with "Take Photo", "Choose from Gallery" and Cancel isn't showing.
Below I have added the code.
Wizard.Java:
public class Wizard extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.btnSelectPhoto);
viewImage=(ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from
Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Wizard.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 intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new
File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
startActivityForResult(intent, 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();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.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));
Log.w("path of image from gallery......******************.........", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
Wizard.xml
<?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:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="284dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:ems="10"
android:singleLine="true"
android:maxLength="10">
<requestFocus />
</EditText>
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Photo" />
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/camera"/>
</LinearLayout>
You can use custom alertdialog.
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialoglayout);builder.show();
before you must create dialog_layout.xml
are you sure that it doesn't work? Your code is correct. It could be perfectly show on Nexus 5.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I want to add an image from my library and then save it.
My application crashes when I click on the setOnClickListener inside my AddImage activity.
I added this code to a new project and then it worked perfectly but I don't know why it is not working in my main project.
I'm using MediaStore.
public class AddImage extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=findViewById(R.id.button);
viewImage=findViewById(R.id.camera);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddImage.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 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 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();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.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));
viewImage.setImageBitmap(thumbnail);
}
}
}
}
Logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.completepractice.AddImage.onCreate(AddImage.java:34)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
please help me as i am new in this field
Please check if b=findViewById(R.id.button); belongs in activity_main.xml.
null object references result when your findViewById references an id value that is not a part of the XML defined in setContentView()
I was trying to upload a profile of the user. In the app, users can choose from a gallery or camera.
While I was capturing the image from the camera, the image is rotating. I tried with exifinterface but the orientation getting as 0, and it works fine on some devices. How to solve this issue can anyone help me out?
xml
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/profile_image"
app:placeholderImage="#drawable/defaultprofile1"
app:placeholderImageScaleType="fitCenter"
app:roundingBorderColor="#color/browser_actions_bg_grey"
fresco:roundAsCircle="true"
android:layout_width="110dp"
android:layout_height="110dp"
android:scaleType="fitCenter" />
Code
draweeView3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View view){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ActivityCompat.requestPermissions(Objects.requireNonNull(getActivity()), new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
selectImage();
}
}
});
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Upload Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 0) {
if (data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
System.out.println("imagebitmap" + selectedImage);
Uri tempUri = getImageUri(Objects.requireNonNull(getContext()), selectedImage);
System.out.println("tempUri" + tempUri);
String picturePath = getRealPathFromURI(tempUri);
System.out.println("paaaaaaaa" + picturePath);
File f = new File(picturePath);
String imageName = f.getName();
System.out.println("file f" + f);
Uri imageUri = Uri.fromFile(new File(picturePath));// For files on device
draweeView3.setImageURI(imageUri);
}
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000, true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getActivity().getContentResolver() != null) {
Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
System.out.println("final path" + path);
cursor.close();
}
}
return path;
}
So i have a SettingsActivity/layout with ImageViews, and can upload images from my phone gallery to these ImageViews which also then upload to firebase. There are currently 3 edit views and everything works fine until i wanted to try the following:
Now i wanted to have the ability to increase the amount of ImageViews upon certain criteria being met. For this i decided to move the ImageViews from this activity to a fragment activity and I created another activity with double the ImageViews. All the code for the upload/download of these ImageViews happen in the SettingsActivity. What's the best way to go about this? I've tried moving all the code over to the fragment activity but I end up with too much issues. What's the best way to go about using these imagesviews in the fragments(I have onclick listeners and other stuff that need the imageviews) in the SettingsActivity:
SettingsActivity.Java
public class SettingsActivity extends AppCompatActivity {
private ImageView mImage1, mImage2, mImage3;
private String image1Url, image2Url, image3Url;
public static FragmentManager fragmentManager;
final int MaxTags = 5;
private int MaxImages = 3;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
fragmentManager = getSupportFragmentManager();
if(findViewById(R.id.profileImageContainer) != null){
if(savedInstanceState!=null)
return;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SettingsDefault settingsDefault = new SettingsDefault();
fragmentTransaction.add(R.id.profileImageContainer, settingsDefault, null);
fragmentTransaction.commit();
}
getUserInfo();
mImage1 = findViewById(R.id.image1);
mImage2 = findViewById(R.id.image2);
mImage3 = findViewById(R.id.image3);
mUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
mImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
});
mImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 3);
}
});
ArrayAdapter<String> values;
private void getUserInfo() {
mUserDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("phone") != null){
phone = map.get("phone").toString();
mPhoneField.setText(phone);
}
if(map.get("sex") != null){
userSex = map.get("sex").toString();
}
Glide.clear(mImage1);
if(map.get("image1Url") != null){
image1Url = map.get("image1Url").toString();
switch(image1Url){
case "default":
mImage1.setImageResource(R.mipmap.ic_launcher);
break;
default:
Glide.with(getApplication()).load(image1Url).into(mImage1);
break;
}
}
if(map.get("image2Url") != null){
image2Url = map.get("image2Url").toString();
switch(image2Url){
case "default":
mImage2.setImageResource(R.mipmap.ic_launcher);
break;
default:
Glide.with(getApplication()).load(image2Url).into(mImage2);
break;
}
}
if(map.get("image3Url") != null){
image3Url = map.get("image3Url").toString();
switch(image3Url){
case "default":
mImage3.setImageResource(R.mipmap.ic_launcher);
break;
default:
Glide.with(getApplication()).load(image3Url).into(mImage3);
break;
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
final Uri resultUri = imageUri;
if(resultUri != null){
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image1");
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] databytes = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(databytes);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("image1Url", uri.toString());
mUserDb.updateChildren(newImage);
mImage1.setImageURI(resultUri);
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
});
}else{
finish();
}
}
if(requestCode == 2 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
final Uri resultUri = imageUri;
if(resultUri != null){
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image2");
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] databytes = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(databytes);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("image2Url", uri.toString());
mUserDb.updateChildren(newImage);
mImage2.setImageURI(resultUri);
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
});
}else{
finish();
}
}
if(requestCode == 3 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
final Uri resultUri = imageUri;
if(resultUri != null){
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image3");
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] databytes = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(databytes);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("image3Url", uri.toString());
mUserDb.updateChildren(newImage);
mImage3.setImageURI(resultUri);
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
});
}else{
finish();
}
}
}
}
SettingsDefault.Java (Fragment)
public class SettingsDefault extends Fragment {
ImageView mImageView1;
ImageView mImageView2;
ImageView mImageView3;
public SettingsDefault() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_settings_default, container, false);
mImageView1 = view.findViewById(R.id.image1);
mImageView2 = view.findViewById(R.id.image2);
mImageView3 = view.findViewById(R.id.image3);
return view;
}
public ImageView getImageView1(){
return mImageView1;
}
public ImageView getImageView2(){
return mImageView2;
}
public ImageView getImageView3(){
return mImageView3;
}
Fragment's Layout(Moved the ImageViews from SettingsActivity to here)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Fragments.ProfileImages.SettingsUpgade1">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10sp"
android:weightSum="3">
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image1"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image2"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image3"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image4"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image5"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image6"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
</LinearLayout>
</FrameLayout>
It is easy!! Just use interface between your activity and fragment!! Like this link below!!
Communicating between a fragment and an activity - best practices
thanks for the info. Had a look at using interfaces which seems useful with simply tasks, but with so much going on in the activity with the imageviews it became really confusing and difficult to understand how to incorporate the interfaces to work with this app. So to simplify my life, I successfully managed to move all of the methods that utilize the ImageViews over to the fragment activity. Now i will do the same for the other fragment(only difference is it has double the imageviews), and will use a bolean or something to flick between the fragments. Not sure if this is the best way, specifically performance wise, but i ran the app and it seemed okay.
Sorry guys, I'm very new to android and now need to create a simple camera in my android studio.
When I choose an image from gallery or take a picture, it will crashed.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.camera_main, container, false);
b=(Button)claims.findViewById(R.id.btnSelectPhoto);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
return claims;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Claims.this.getActivity());
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 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 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();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity. RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().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));
Log.w("path of image ", picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
LogCat Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=2, result=-1, data=Intent { dat=content://com.sec.android.gallery3d.provider/picasa/item/5843197728949359042 (has extras) }} to activity {com.example.project.project/com.example.project.project.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3752)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3795)
Can someone explain to me why would this happen and how to fix it?
Thanks a lot :)
you can using this method
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_REQUEST_CODE = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String IMG_FILE_NAME = "tempImg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// From Gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_REQUEST_CODE);
// Take a Picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(GetOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public static File GetOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory() + "/" + HConstants.IMG_FILE_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ IMG_FILE_NAME + ".jpg");
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == IMAGE_REQUEST_CODE){
fileUri = data.getData();
Log.i(getClass().getName(), "fileUri" + fileUri);
}else{
Log.i(getClass().getName(), fileUri);
}
}
}
}
Getting Image from Gallery.
Try the following code.Hopefully it will work
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
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 imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
Taking Picture
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
Also add the permissions in Manifest File:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I am new to android, I am trying to create an a app to take a photo or upload to the screen (which I have currently working) and then save the image to the SD card by clicking on a button. when I chick on the save button the app stops working, any help will be appreciated. Below is my code
public class Upload extends Fragment {
private Button bt_browse;
private ImageView iv_photo;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String uploadImagePath = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.upload,
container, false);
bt_browse = (Button) rootView.findViewById(R.id.button1);
iv_photo = (ImageView) rootView.findViewById(R.id.iv_photo);
bt_browse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
return rootView;
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select 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);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
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/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv_photo.setImageBitmap(bm);
uploadImagePath = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
iv_photo.setImageBitmap(bm);
uploadImagePath = tempPath;
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
//automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
OnMenuItemClickListener SaveImageClickListener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Bitmap bitmap;
OutputStream output;
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_camera);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Save Image Example");
dir.mkdirs();
File file = new File(dir, "myimage.png");
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
};
}
Have you got the WRITE_EXTERNAL_STORAGE permission on your manifest file? If not, add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>