I am trying to load an image that I picked from the gallery onto Canvas but for some reason it is not showing up on it.
I am using THIS Canvas Library and the method to draw a Bitmap on to the Canvas there is this.canvas.drawBitmap(bitmap); and I am using that but I dont know what is going wrong.
MainActivity.java :
public class MainActivity extends AppCompatActivity {
private CanvasView canvas;
private DrawActivity drawActivity;
//Variables for Selecting Photo from gallery to load onto canvas
private static final int SELECT_PHOTO = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
canvas = (CanvasView) findViewById(R.id.canvas);
}
public void clearCanvas(View v){
this.canvas.clear();
}
public void loadImage(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.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 filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
this.canvas.drawBitmap(yourSelectedImage);
}
}
}
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="tech.arvisapps.thumbnailmaker.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:alpha="0.5">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/draw_activity" />
</android.support.design.widget.CoordinatorLayout>
draw_activity.xml :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DDDDDD"
android:layout_gravity="center"
android:orientation="horizontal" >
<com.android.graphics.CanvasView
android:id="#+id/canvas"
android:layout_width="280dp"
android:layout_height="280dp"
android:layout_gravity="center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/clearCanvas"
android:onClick="clearCanvas"
android:layout_gravity="bottom|center"
android:text="CLEAR"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loadImage"
android:onClick="loadImage"
android:layout_gravity="bottom|left"
android:text="LOAD"/>
</FrameLayout>
Note that I have not tried to position the bitmap properly onto the canvas as nothing of that sort has been mentioned in the API documentation for it. The method that I am using to load an image from the gallery might not be completely correct, if so, please tell me what I have done wrong and what I should do instead. An explanation would be appreciated!
Log :
04-23 14:40:28.698 19671-19671/tech.arvisapps.thumbnailmaker E/BitmapFactory:
Unable to decode stream: java.io.FileNotFoundException:
/storage/emulated/0/Thumbnail Maker/Image-5322.jpg: open failed: EACCES (Permission denied)
I had not set the appropriate permissions in the manifest file. After doing that, everything works fine. If somebody wants to know how to do that, add a comment and I will update the answer.
Related
This question already has answers here:
Select a image from the gallery and show it in another Activity
(3 answers)
Closed 6 months ago.
I am making an mobile app in which i have to select image from gallery by clicking a button and then display it in another activity. The problem is the image wont show to the second activity. Theres no problems running the code. what would be the problem.. PLEASE HELP ME
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonGalleryOpen(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//noinspection deprecation
startActivityForResult(intent, RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null){
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 filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(MainActivity.this,gallery_view.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
}
}
I am making an mobile app in which i have to select image from gallery by clicking a button and then display it in another activity. The problem is the image wont show to the second activity. Theres no problems running the code. what would be the problem.. PLEASE HELP ME
This is an activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera sample"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_below="#+id/textview1"
android:layout_marginTop="3dp">
<Button
android:id="#+id/bottonGalleryOpen"
android:onClick="buttonGalleryOpen"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="pick" />
</RelativeLayout>
</RelativeLayout>
gallery_view.java
public class gallery_view extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_view);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Bitmap selectedImage =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageBitmap(selectedImage);
}
}
gallery_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<RelativeLayout
android:id="#+id/relative_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera sample"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/relative_1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/ImageShow"
android:layout_width="match_parent"
android:layout_height="500dp" />
</RelativeLayout>
</RelativeLayout>
This line in your code does not make sense:
intent.putExtra("data", "selectedphoto");
You are adding here string "selectedphoto" which is in no way connected to selectedphoto variable you initialised earlier. You could put your bitmap to intent extra as byte array but this is in-efficient, especially when the image is large.
Instead of passing bitmap to ShowImage activity, pass your URI and then retrieve actual bitmap in ShowImage activity exactly as you do now in your PictureOptions activity.
intent.setData(passed uri here);
In your ShowImage activity do:
URI imageUri = getIntent().getData();
i want to add picture in an image view with the text veiw in one line. this code is opening the gallery and let me select a picture. but when the picture is selected the picture is then not showed in the image veiw. i took the code from this link
[Image browse button in android activity
here is my code
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
and
#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.image);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
and here is the xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:padding="1dp"
android:background="#color/Black"
android:layout_marginTop="10dp"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/image"
android:layout_weight="0.5"
/>
<TextView
android:layout_marginTop="10dp"
android:text="TextView"
android:layout_width="match_parent"
android:singleLine="true"
android:layout_gravity="right"
android:background="#color/White"
android:layout_height="wrap_content"
android:id="#+id/child"
android:textSize="24sp"/>
</LinearLayout>
I think you forget permission read external storage.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I want create application
Scan Barcode using ZXING Barcode Scanner
Like Blackberry Messenger
This is my code "MainActivity.java"
package com.example.ridwan.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import info.vividcode.android.zxing.CaptureActivity;
import info.vividcode.android.zxing.CaptureActivityIntents;
public class MainActivity extends AppCompatActivity {
private TextView tvScanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent captureIntent = new Intent(MainActivity.this, CaptureActivity.class);
CaptureActivityIntents.setPromptMessage(captureIntent, "Barcode scanning...");
startActivityForResult(captureIntent, 0);
tvScanResult = (TextView) findViewById(R.id.tv_scanresult);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK && data != null) {
String value = data.getStringExtra("SCAN_RESULT");
tvScanResult.setText(value);
} else if (resultCode == Activity.RESULT_CANCELED) {
tvScanResult.setText("Scanning Gagal, mohon coba lagi.");
}
} else {
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Then this is my "activity_main.xml"
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ridwan.myapplication.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_marginTop="50dp"
android:id="#+id/tv_scanresult_title"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result Scan : " />
<TextView
android:layout_below="#id/tv_scanresult_title"
android:id="#+id/tv_scanresult"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:textColor="#ff1493"
android:layout_height="wrap_content"
android:text="_" />
</RelativeLayout>
Can you give me solution ?
i want to barcode in fragment.
I have achieved the same effect/UI you are looking for by using ZXing Android Embedded. Very straightforward to implement - and it also includes a torch functionality.
Step 1:
Add This Libray in Gradle in Dependancy
implementation 'com.google.zxing:core:3.2.1'
implementation 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
Step 2:
BarcodeActivity.java
public class BarcodeActivity extends AppCompatActivity {
private EditText editTextProductId;
private Button buttonGenerate, buttonScan;
private ImageView imageViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
initView();
}
private void initView() {
editTextProductId = findViewById(R.id.editTextProductId);
imageViewResult = findViewById(R.id.imageViewResult);
buttonGenerate = findViewById(R.id.buttonGenerate);
buttonGenerate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonGenerate_onClick(view);
}
});
buttonScan = findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonScan_onClick(view);
}
});
}
private void buttonGenerate_onClick(View view) {
try {
String productId = editTextProductId.getText().toString();
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
Writer codeWriter;
codeWriter = new Code128Writer();
BitMatrix byteMatrix = codeWriter.encode(productId, BarcodeFormat.CODE_128,400, 200, hintMap);
int width = byteMatrix.getWidth();
int height = byteMatrix.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
bitmap.setPixel(i, j, byteMatrix.get(i, j) ? Color.BLACK : Color.WHITE);
}
}
imageViewResult.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private void buttonScan_onClick(View view) {
IntentIntegrator intentIntegrator = new IntentIntegrator(this);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
intentIntegrator.setCameraId(0);
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult != null) {
String productId = intentResult.getContents();
Toast.makeText(getApplicationContext(), productId, Toast.LENGTH_LONG).show();
}
}
}
Step 3:
activity_barcode.xml
<?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:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText">
<EditText
android:id="#+id/editTextProductId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Product Id"
android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/buttonGenerate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Generate Barcode" />
<Button
android:id="#+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Scan Barcode" />
</LinearLayout>
<ImageView
android:id="#+id/imageViewResult"
android:layout_width="match_parent"
android:layout_height="335dp" />
</LinearLayout>
Please Add this code in MainActivity
Add This Libray in Gradle in Dependancy
compile 'com.journeyapps:zxing-android-embedded:3.3.0#aar'
compile 'me.dm7.barcodescanner:zxing:1.9'
Add jar zbar.jar
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QCscanner = (Button) findViewById(R.id.QCscanner);
mScannerView = new ZXingScannerView(this);
QCscanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
/*Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);*/
mScannerView = new ZXingScannerView(MainActivity.this); // Programmatically initialize the scanner view<br />
setContentView(mScannerView);
mScannerView.setResultHandler(MainActivity.this); // Register ourselves as a handler for scan results.<br />
mScannerView.startCamera();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void handleResult(Result result) {
Log.e("", result.getText()); // Prints scan results<br />
Log.e("", result.getBarcodeFormat().toString());
Toast.makeText(MainActivity.this, "" + result.getText() + "\n" + result.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
}
}
ZXING library allows you to launch an intent(activity) to scan barcodes. If you wants to make changes in that you have to make changes in CaptureActivity of ZXING lib.
Also, now since Google has included scanning feature in its playservices you can use Vision api for scanning in a fragment without integration of any third party library. https://github.com/googlesamples/android-vision/tree/master/visionSamples
Please use
https://github.com/journeyapps/zxing-android-embedded
Just include Scanner view and remove scan paddings by adding:
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
attributes.
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/zxing_barcode_scanner"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
app:zxing_preview_scaling_strategy="fitXY"
app:zxing_use_texture_view="false"
/>
try this. (It very simplified example):
First step. Add dependency in build.gradle(module app):
From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:
implementation 'com.google.zxing:core:3.3.0'
Second step. Paste DecoratedBarcodeView view in you layout (activity_main.xml in this example):
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</com.journeyapps.barcodescanner.DecoratedBarcodeView>
<TextView
android:id="#+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/barcode_scanner" />
</androidx.constraintlayout.widget.ConstraintLayout>
Third step. Add this code to MainActivity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val formats: Collection<BarcodeFormat> = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39)
binding.barcodeScanner.decoderFactory = DefaultDecoderFactory(formats)
binding.barcodeScanner.initializeFromIntent(Intent())
binding.barcodeScanner.decodeContinuous(object : BarcodeCallback {
override fun barcodeResult(result: BarcodeResult?) {
binding.resultTextView.text = result?.result?.text
}
})
}
override fun onResume() {
super.onResume()
binding.barcodeScanner.resume()
}
override fun onPause() {
super.onPause()
binding.barcodeScanner.pause()
}
}
Important! Implements onResume/onPause methods for activate DecoratedBarcodeView view. And don't forget grant Camera permissions for you app!
In this example i use this library:
https://github.com/journeyapps/zxing-android-embedded
In my app I need to take a pic from the gallery(I have working code for that, that gives me the Uri of the pic) and place the Uri in an ImageView. The problem I'm running into is that the pic is not covering the whole screen like I want it to, even though I have the height and width of the ImageVIew set to match_parent in the layout. Is there any way I can set every pic from the gallery to display on the whole sceen?
Here's my code:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==btn.getId())
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
}
And here's my layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="30"
android:orientation="vertical" >
<Button
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ImageView
android:id="#+id/pic"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
You can use the following android:scaleType="fitXY"
Can't figure out why, but I have no errors on eclipse, (simple classroom app - button creates new activity, sending in a textView and an imageView to the new activity) but as soon as I run my app and I press my button, the app crashes and I recieve this error on the LogCat
Logcat
02-12 17:13:26.297: E/AndroidRuntime(398): Caused by: java.lang.NullPointerException
02-12 17:13:26.297: E/AndroidRuntime(398): at edu.colum.iam.SecondPage.onCreate(SecondPage.java:38)
When I take that line out (and any other line that would affect it) the app runs fine, and it sends my textView over. Here is the .java I have, and I'll post the xml just incase as well.
IntentsActivity.java
public class IntentsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)this.findViewById(R.id.button1);
btn.setOnClickListener(myListener);
}
// Create an anonymous implementation of OnClickListener
View.OnClickListener myListener = new View.OnClickListener()
{
public void onClick(View v) {
Intent myIntent = new Intent(IntentsActivity.this, SecondPage.class);
String text = ((TextView)findViewById(R.id.textView1)).getText().toString();
ImageView Selection = ((ImageView) findViewById(R.id.imageView1));
myIntent.putExtra("Text", text);
myIntent.putExtra("img", R.drawable.icon);
or an image)
startActivity(myIntent);
//endclass
SecondPage.java
public class SecondPage extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
//get extras
Intent intent = this.getIntent();
Bundle b = intent.getExtras();
String text = b.getString("Text");
//show text
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(text);
//show image
ImageView image = (ImageView) findViewById(R.id.imageView1);
int resource = getIntent().getIntExtra("img", R.drawable.icon);
image.setImageDrawable(getResources().getDrawable(resource));
// ^ this is the line my logcat crashes as an error
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="#string/Button1" android:id="#+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<TextView android:id="#+id/textView1" android:text="#string/FirstLayout"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"></TextView>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon" />
</LinearLayout>
second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="wrap_content" android:id="#+id/textView1"
android:text="#string/SecondLayout"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content"></TextView>
<Button android:text="#string/Button2" android:id="#+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
According to the layout you posted, imageView1 is in your first xml not in second.xml which is the one you inflate in SecondPage.java so naturally it is null when you try to call a method on it.
You will need to add the ImageView to your second.xml.
You can have the same ImageViews in different layout files (I don't know why you would name them the same) and then access them from within your code as long as you have set the right layout inside onCreate or wherever you want to access those components. So, yes, just copy the ImageView to the second.xml and it should work.