I have developed a basic camera and am trying to get it working.
Here is the camera code
package com.example.camera;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
Object size;
public CameraView(Context context) {
super(context);
holder = this.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.addCallback(this);
}
public Camera getCamera(){
return camera;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters params = camera.getParameters();//Getting paramaters.
if(size!=null){ //make sure we don't pull a NullException.
params.setPreviewSize(width, height);//gotta set the size, since we know it.
}
camera.setParameters(params);//gotta set the paramaters now.
camera.startPreview();//starting the preview.
}
public void surfaceCreated(SurfaceHolder arg0) {
try{
camera = Camera.open();//setting the camera up.
camera.setPreviewDisplay(holder);//making the display our current SurfaceHolder
} catch (IOException e){
e.printStackTrace();//printing out the error message if it happens.
}
}
public void surfaceDestroyed(SurfaceHolder arg0) {
camera.stopPreview();
camera.release();
camera = null;
}
}
Now Im trying to call the camera from my main method and I just cant seem to make it work
package com.example.camera;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class main {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cam = cv.getCamera(); //notice how we used that method? ;)
cam.takePicture(null,null,PictureCallback_);
}
});
}
Camera.PictureCallback PictureCallback_ = new Camera.PictureCallback() {
public void onPictureTaken(byte[] imageData, Camera c) {
InputStream is = new ByteArrayInputStream(imageData);
Bitmap bmp = BitmapFactory.decodeStream(is);
}
} ;
Any help is appreciated. Trying to call the original camera activity getCamera and then get the picture taken and put it into imageView1 any help is appreciated.
Try to do this in your onClick() method:
cam.autoFocus(new AutoFocusCallback(){
Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() {
public void onShutter() {
// If you want to play your own sound (otherwise, it plays the sound by default)
}
};
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
cam.takePicture(shutterCallback, null, PictureCallback_);
}
});
I have created a camera library project here you can use this library to call the camera and take pictures and save it or read code on how to use the camera. Sample is given you can check it out
Related
I have a code that show camera with SurfaceView and capture image from that camera.
Now i want to show 4 camera with SurfaceView together and capture image when touch each one of them.
Camera ids are 2, 3, 4, 5.
I read and use these links:
Capture screen of SurfaceView
how to create and save a screenshot from a surfaceview?
This is my code:
package com.example.foosurface;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity implements SurfaceHolder.Callback {
protected static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
private SurfaceView SurView;
private SurfaceHolder camHolder;
private boolean previewRunning;
public static Camera camera = null;
private RelativeLayout CamView;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CamView = (RelativeLayout) findViewById(R.id.camview);//RELATIVELAYOUT OR
//ANY LAYOUT OF YOUR XML
SurView = (SurfaceView)findViewById(R.id.sview);//SURFACEVIEW FOR THE PREVIEW
//OF THE CAMERA FEED
camHolder = SurView.getHolder(); //NEEDED FOR THE PREVIEW
camHolder.addCallback(this); //NEEDED FOR THE PREVIEW
camHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//NEEDED FOR THE PREVIEW
Button btn = (Button) findViewById(R.id.button1); //THE BUTTON FOR TAKING PICTURE
btn.setOnClickListener(new View.OnClickListener() { //THE BUTTON CODE
public void onClick(View v) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);//TAKING THE PICTURE
//THE mPicture IS CALLED
//WHICH IS THE LAST METHOD(SEE BELOW)
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,//NEEDED FOR THE PREVIEW
int height) {
if(previewRunning) {
camera.stopPreview();
}
Camera.Parameters camParams = camera.getParameters();
Camera.Size size = camParams.getSupportedPreviewSizes().get(0);
camParams.setPreviewSize(size.width, size.height);
camera.setParameters(camParams);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning=true;
} catch(IOException e) {
e.printStackTrace();
}
}
public void surfaceCreated(SurfaceHolder holder) { //NEEDED FOR THE PREVIEW
try {
camera=Camera.open();
} catch(Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
finish();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) { //NEEDED FOR THE PREVIEW
camera.stopPreview();
camera.release();
camera=null;
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d("TAG", "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("TAG", "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File myExternalFile = new File(Environment.getExternalStorageDirectory()+
File.separator+"Ultimate Entity Detector");
File tmpFile = new File(myExternalFile,"TempGhost.jpg");
try {
tmpFile.delete();
tmpFile.createNewFile();
FileOutputStream output = new FileOutputStream(tmpFile);
output.write(data);
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
My xml code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="#+id/camview">
<SurfaceView
android:id="#+id/sview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
My question:
How to show 4 camera preview together with surfaceview and capture image from them?
I found my answer,
i used holder.addCallback for each holder.
it's one holder callback:
sHolder[0].addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(#NonNull SurfaceHolder holder) {
try {
mCamera[0] =Camera.open(2);
} catch(Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Error",Toast.LENGTH_LONG).show();
getActivity().finish();
}
openAndStartCamera(0);
}
#Override
public void surfaceChanged(#NonNull SurfaceHolder holder, int format, int width, int height) {
if(previewRunning[0]) {
mCamera[0].stopPreview();
}
Camera.Parameters camParams0 = mCamera[0].getParameters();
Camera.Size size0 = camParams0.getSupportedPreviewSizes().get(0);
camParams0.setPreviewSize(size0.width, size0.height);
mCamera[0].setParameters(camParams0);
try {
mCamera[0].setPreviewDisplay(sHolder[0]);
mCamera[0].startPreview();
previewRunning[0]=true;
} catch(IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(#NonNull SurfaceHolder holder) {
mCamera[0].stopPreview();
mCamera[0].release();
mCamera[0]=null;
previewRunning[0]=false;
Log.e(TAG,"release camera");
}
});
I used that example to get preview from camera:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.TextureView;
import android.widget.FrameLayout;
import android.view.TextureView;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
public class MainActivity extends Activity implements
TextureView.SurfaceTextureListener, Camera.PreviewCallback {
static {
System.loadLibrary("JNIProcessor");
}
private final String TAG="LiveFeature";
private Camera mCamera;
private byte[] mVideoSource;
private TextureView mTextureView;
private String[] ResolutionList;
private Menu AppMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_feature);
mTextureView.setSurfaceTextureListener(this);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture pSurface,
int pWidth, int pHeight) {
// Ignored
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture pSurface) {
// Ignored
}
#Override
public void onPreviewFrame(byte[] pData, Camera pCamera) {
}
}
It seems the Camera.PreviewCallback is deprecated and I should use android.hardware.camera2. The problem is I don't find preview callback function to get the raw data bytes.
I just want to grabe frame from camera without render it into a surface and to put it into a JNI function.
These steps to get a preview:
Add camera permission in manifest file (Manifest.permission.CAMERA)
Get camera instance with this method:
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
Log.e(TAG, e.getMessage());
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
Create a class that extends SurfaceView and let the class implement SurfaceHolder.Callback and pass your Camera instance in its constructor. Get the holder in the constructor with getHolder()
In method "surfaceCreated", set preview display and start preview
public void surfaceCreated(SurfaceHolder holder) {
try {
mCameraSource.start(holder);
mCamera.setPreviewDisplay(mHolder);
setWillNotDraw(false);
} catch (Exception e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
Stop preview and release camera when you don't need it anymore
mCamera.stopPreview();
mCamera.release();
I want to run some OpenCv Filters over images inside of an Android App.
I've hit an Error, of which I cant seem to find the origin.
Stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:452)
at org.opencv.android.BaseLoaderCallback.onPackageInstall(BaseLoaderCallback.java:90)
at org.opencv.android.AsyncServiceHelper.InstallService(AsyncServiceHelper.java:117)
at org.opencv.android.AsyncServiceHelper.initOpenCV(AsyncServiceHelper.java:33)
at org.opencv.android.OpenCVLoader.initAsync(OpenCVLoader.java:100)
at project.fragment.OpenCvTestFragment.onCreateView(OpenCvTestFragment.java:94)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My Code: ( OpenCvTestFragment.java )
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;
import java.io.IOException;
import team_excellence.growup.R;
public class OpenCvTestFragment extends Fragment implements CameraBridgeViewBase.CvCameraViewListener2, View.OnTouchListener {
private OnOpenCvTestInteractionListener mListener;
private View view;
private ImageView imgView1;
private ImageView imgView2;
public OpenCvTestFragment() {
}
public static OpenCvTestFragment newInstance(String param1, String param2) {
OpenCvTestFragment fragment = new OpenCvTestFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
private static final String TAG = "OCVSample::Activity";
private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(getActivity()) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
view = inflater.inflate(R.layout.fragment_open_cv_test, container, false);
final ImageView imgView1 = (ImageView) view.findViewById(R.id.ocvImage1);
imgView1.setImageResource(R.drawable.img1);
ImageView imgView2 = (ImageView) view.findViewById(R.id.ocvImage2);
imgView1.setImageResource(R.drawable.img2);
final Button contoursButton = (Button) view.findViewById(R.id.contoursButton);
contoursButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
applyContoursFilter("img1");
} catch (IOException e) {
e.printStackTrace();
}
}
});
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, getContext(),
mOpenCVCallBack);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onOpenCvTestInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnOpenCvTestInteractionListener) {
mListener = (OnOpenCvTestInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnOpenCvTestInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onCameraViewStarted(int width, int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
return null;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
public interface OnOpenCvTestInteractionListener {
void onOpenCvTestInteraction(Uri uri);
}
public void applyContoursFilter(String resName) throws IOException {
Mat matImg = convertImageToMat(resName);
Mat matResult = findContours(matImg);
Bitmap bm = Bitmap.createBitmap(matResult.cols(), matResult.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(matResult, bm);
imgView1.setImageBitmap(bm);
}
private Mat convertImageToMat(String resName) throws IOException {
int drawableResourceId = this.getResources().getIdentifier(resName, "drawable", getActivity().getPackageName());
Mat img = Utils.loadResource(getContext() , drawableResourceId , Imgcodecs.CV_LOAD_IMAGE_COLOR);
return img;
}
private Mat findContours (Mat image){
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(19,19));
Mat closed = new Mat(); // closed will have type CV_32F
Imgproc.morphologyEx(image, closed, Imgproc.MORPH_CLOSE, kernel);
Core.divide(image, closed, closed, 1, CvType.CV_32F);
Core.normalize(closed, image, 0, 255, Core.NORM_MINMAX, CvType.CV_8U);
Imgproc.threshold(image, image, -1, 255, Imgproc.THRESH_BINARY_INV
+ Imgproc.THRESH_OTSU);
return closed;
}
}
For clarification when the corresponding Button is pressed, the "applyContoursFilter" Method is called, which then converts the image from drawables ( shown in imgView1 ), into a Mat object.
After that the "findContours" Method is called and the Mat-object then converted back into bmp format and set into the imgView1 again.
Well that's how it should work. But the nullpointer error posted above gets thrown and I cant figure out where its coming from or how to fix it.
I'm relatively new to Android and would be grateful for your Help.
I got it solved now, by initializing OpenCV in the MainActivity of my App and only calling it in the Fragments.
I moved the BaseLoaderCallBack Code from the Fragment's OnCreateView , to the MainActivity's OnCreate.
Seems to be working fine now.
Before I used GPSTracker.this in AlertDialog.So I got an exception 'android.content.res.Resources$Theme android.content.Context.getTheme()'
I solved this exception by adding context like this:
private final Context mContext;
public GPSTracker(Context context) {
this.mContext = context;
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
...........
}
i was doing ImageSwitcher, it was working perfect tried to send ImageSwitcher Image to another activity.. ImageSwitcher works perfect but after clicking button for going to next activity, Error: Null Pointer Exception in (imageview) in Views.java
MainEvent.java
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import java.io.ByteArrayOutputStream;
public class MainEvent extends Activity {
private ImageSwitcher imageSwitcher;
Button btnNext,back,select,refresh;
ImageView imageView;
// Array of Image IDs to Show In ImageSwitcher
int imageIds[]={R.drawable.frame3,R.drawable.frame7,
R.drawable.curtain,R.drawable.potraitimage
};
int messageCount=imageIds.length;
// to keep current Index of ImageID array
int currentIndex=0;
Animation in,out;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_event);
// get The references
btnNext=(Button)findViewById(R.id.button2);
back=(Button)findViewById(R.id.button);
select=(Button)findViewById(R.id.select);
refresh=(Button)findViewById(R.id.refresh);
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
// Set the ViewFactory of the ImageSwitcher that will create
ImageView object when asked
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
// TODO Auto-generated method stub
// Create a new ImageView set it's properties
imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(R.drawable.potraitimage);
return imageView;
}
});
// Declare the animations and initialize them
in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
// set the animation type to imageSwitcher
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
// ClickListener for NEXT button
// When clicked on Button ImageSwitcher will switch between Images
// The current Image will go OUT and next Image will come
in with specified animation
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
imageView.setImageResource(0);
Log.d("index", String.valueOf(currentIndex));
currentIndex++;
Log.d("index", String.valueOf(currentIndex));
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// set the animation type to imageSwitcher
// TODO Auto-generated method stub
Log.d("index", String.valueOf(currentIndex));
currentIndex--;
Log.d("index", String.valueOf(currentIndex));
// If index reaches maximum reset it
if (currentIndex < 0)
currentIndex = 2;
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageView.setImageResource(imageIds[currentIndex]);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Intent in=new Intent(MainEvent.this,Camera.class);
/* in.putExtra("image",bitmap);*/
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bundle bu=new Bundle();
bu.putByteArray("ImageByte",byteArray );
in.putExtras(bu);
startActivity(in);
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRestart();
}
});
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Intent i = new Intent(MainEvent.this, MainEvent.class); //your class
startActivity(i);
finish();
}
}
Views.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
public class Views extends AppCompatActivity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
image = (ImageView) findViewById(R.id.image);
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("ImageByte");
/* Intent i=getIntent();*/
/* Bitmap bitmap=i.getExtras().getParcelable("image");
image.setImageBitmap(bitmap);*/
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
image.setImageBitmap(bmp);//here null pointer exception
}
}
I don't know how to pass image from imageswitcher to next activity.. Please help me guys..
Instead of passing in the bytes of the image, can't you just pass in the index (int) it is on?
That would be more efficient.
(Extended answer from the chain below)
Share the array in both activities.
Simple way on static properties:
public class StaticModelManager {
public static int imageIds[];
}
Then get or set it anywhere in your application:
StaticModelManager.imageIds = {
R.drawable.frame3,
R.drawable.frame7,
R.drawable.curtain,
R.drawable.potraitimage
};
Use them:
StaticModelManager.imageIds[currentIndex];
Multiple activities or fragments can easily access this one instance. Just make sure to clean things up when not needed or it sits in memory.
I need some suggestions as to how I can update a Textview located in the XML with a value generated through my code.
The program draws a straight line through the canvas, I want the textView to reflect the line's tip x-value.
My code as follows:
package com.example.threadexperiment1;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
lineDrawing InfiniteLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InfiniteLine = new lineDrawing (this);
setContentView(R.layout.activity_main);
Thread thread = new Thread(InfiniteLine);
thread.start();
RelativeLayout RL1 = (RelativeLayout)findViewById(R.id.RelativeLayout1);
RL1.addView(InfiniteLine);
}
public class lineDrawing extends View implements Runnable {
float x=100, y=100;
Paint lineColour = new Paint ();
TextView TV1 = (TextView)findViewById(R.id.textView1);
//Constructor
public lineDrawing(Context context) {
super(context);
lineColour.setColor(Color.BLACK);
}
//ondraw codes
#Override
public void onDraw (Canvas canvas){
canvas.drawLine(0,0,x,y,lineColour);
if (x==500){
x=0;
y=0;
}
invalidate();
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(250);
}
catch (Exception e) {}
x+=10;
y+=10;
}
}
}
}
Try textView.setText(string) within the thread.