I am working on a QR decoder app in which i have created a SurfaceView to display camera output and a ImageButton to select an image from gallery.
I am using google play services to decode the QR code which requires to use surface view to scan the QR using camera. But it is not focusing on its own.
Below is the code for the same.
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
public class Scanner extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
final SurfaceView cameraView = (SurfaceView) findViewById(R.id.camera_view);
BarcodeDetector barcodeDectector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
final CameraSource cameraSource = new CameraSource.Builder(this,barcodeDectector).setRequestedPreviewSize(1920,1080).build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDectector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
//QRcode found hence move to intent action.
if( barcodes.size() != 0){
Intent i = new Intent(Scanner.this,Verify.class);
i.putExtra("xml",barcodes.valueAt(0).displayValue);
startActivity(i);
}
}
});
ImageButton scanImage = (ImageButton) findViewById(R.id.scanImage);
scanImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//button action to be added
}
});
}
}
The activity_scanner.xml is as follows.
<?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"">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="400dip"
android:layout_weight="70"
android:id="#+id/camera_view"
android:layout_alignParentLeft="true"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/scanImage"
android:layout_below="#+id/camera_view"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:src="#drawable/ic_image_black_48dp"
android:layout_alignRight="#+id/camera_view"
android:layout_alignEnd="#+id/camera_view" />
</RelativeLayout>
Try extending Surface view like this, and setFocusable(true).
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
public CameraView(Context context) {
super(context);
getHolder().addCallback(this);
setFocusable(true);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
EDIT 1:
Then in layout you can use this class like this,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://s...content-available-to-author-only...d.com/apk/res/android"
xmlns:tools="http://s...content-available-to-author-only...d.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">
<com.abhayjatindoshi.encryptorcode.qrlogin.javaclass.CameraView
android:layout_width="match_parent"
android:layout_height="400dip"
android:layout_weight="70"
android:id="#+id/camera_view"
android:layout_alignParentLeft="true"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/scanImage"
android:layout_below="#+id/camera_view"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:src="#drawable/ic_image_black_48dp"
android:layout_alignRight="#+id/camera_view"
android:layout_alignEnd="#+id/camera_view" />
</RelativeLayout>
Use Layout like above.
try this:
cameraView.requestFocus();
cameraView.setFocusableInTouchMode(true);
cameraView.setFocusable(true);
cameraView.requestFocus();
Above did not solved mine "focus" problem but i come a cross other solution which helped me:
private void setCamFocusMode(){
if(null == mCamera) {
return;
}
/* Set Auto focus */
Parameters parameters = mCamera.getParameters();
List<String> focusModes = parameters.getSupportedFocusModes();
if(focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else
if(focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
mCamera.setParameters(parameters);
}
oryginally posted here:
https://stackoverflow.com/a/27092999/6225516
If somebody still looking for this yet, I've solved it by adding .setAutoFocusEnabled(true) before .build, in the line:
BarcodeDetector barcodeDectector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();*
Related
I am trying to click only a rectangular portion of the screen from camera using this code:
Java code:
package com.example.cameraapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
public class CameraActivity extends Activity implements Camera.PictureCallback, SurfaceHolder.Callback {
public static final String EXTRA_CAMERA_DATA = "camera_data";
private static final String KEY_IS_CAPTURING = "is_capturing";
private Camera mCamera, dummyCamera;
private ImageView mCameraImage;
private SurfaceView mCameraPreview,s1;
private Button mCaptureImageButton;
private byte[] mCameraData;
private boolean mIsCapturing;
private View v1;
private View.OnClickListener mCaptureImageButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
// mCamera.release();
// mCamera = Camera.open();
// mCamera.setPreviewDisplay(mCameraPreview.getHolder());
// mCamera.startPreview();
// final SurfaceHolder surfaceHolder = mCameraPreview.getHolder();
// surfaceHolder.addCallback(CameraActivity.this);
// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
captureImage();
}catch (Exception e){
e.printStackTrace();
}
}
};
private View.OnClickListener mRecaptureImageButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
setupImageCapture();
}
};
private View.OnClickListener mDoneButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCameraData != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_CAMERA_DATA, mCameraData);
setResult(RESULT_OK, intent);
} else {
setResult(RESULT_CANCELED);
}
finish();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mCameraImage = (ImageView) findViewById(R.id.camera_image_view);
mCameraImage.setVisibility(View.INVISIBLE);
v1 = findViewById(R.id.v1);
mCameraPreview = (SurfaceView) findViewById(R.id.preview_view);
s1 = (SurfaceView) findViewById(R.id.preview_view_1);
// final SurfaceHolder surfaceHolder = mCameraPreview.getHolder();
// surfaceHolder.addCallback(this);
// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
final SurfaceHolder surfaceHolder2 = s1.getHolder();
surfaceHolder2.addCallback(this);
surfaceHolder2.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCaptureImageButton = (Button) findViewById(R.id.capture_image_button);
mCaptureImageButton.setOnClickListener(mCaptureImageButtonClickListener);
final Button doneButton = (Button) findViewById(R.id.done_button);
doneButton.setOnClickListener(mDoneButtonClickListener);
mIsCapturing = true;
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(KEY_IS_CAPTURING, mIsCapturing);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mIsCapturing = savedInstanceState.getBoolean(KEY_IS_CAPTURING, mCameraData == null);
if (mCameraData != null) {
setupImageDisplay();
} else {
setupImageCapture();
}
}
#Override
protected void onResume() {
super.onResume();
if (mCamera == null) {
try {
mCamera = Camera.open();
// dummyCamera = mCamera;
mCamera.setPreviewDisplay(s1.getHolder());
// dummyCamera.setPreviewDisplay(s1.getHolder());
if (mIsCapturing) {
// dummyCamera.startPreview();
mCamera.startPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(CameraActivity.this, "Unable to open camera.", Toast.LENGTH_LONG)
.show();
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
mCameraData = data;
setupImageDisplay();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mCamera != null) {
try {
// mCamera.stopPreview();
mCamera.setPreviewDisplay(holder);
// dummyCamera.setPreviewDisplay(s1.getHolder());
if (mIsCapturing) {
mCamera.startPreview();
// dummyCamera.startPreview();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(CameraActivity.this, "Unable to start camera preview.", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private void captureImage() {
mCamera.takePicture(null, null, this);
}
private void setupImageCapture() {
try {
mCameraImage.setVisibility(View.INVISIBLE);
mCameraPreview.setVisibility(View.VISIBLE);
s1.setVisibility(View.VISIBLE);
v1.setVisibility(View.VISIBLE);
mCamera.setPreviewDisplay(s1.getHolder());
mCamera.startPreview();
mCaptureImageButton.setText(R.string.capture_image);
mCaptureImageButton.setOnClickListener(mCaptureImageButtonClickListener);
}catch (Exception e){
e.printStackTrace();
}
}
private void setupImageDisplay() {
Bitmap bitmap = BitmapFactory.decodeByteArray(mCameraData, 0, mCameraData.length);
Bitmap resizedbitmap1=Bitmap.createBitmap(bitmap, 0,0,mCameraPreview.getWidth(), mCameraPreview.getHeight());
mCameraImage.setImageBitmap(resizedbitmap1);
mCamera.stopPreview();
mCameraPreview.setVisibility(View.INVISIBLE);
s1.setVisibility(View.INVISIBLE);
v1.setVisibility(View.INVISIBLE);
mCameraImage.setVisibility(View.VISIBLE);
mCaptureImageButton.setText(R.string.recapture_image);
mCaptureImageButton.setOnClickListener(mRecaptureImageButtonClickListener);
}
}
Layout:
<?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:background="#android:color/transparent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/capturing_image" />
<FrameLayout
android:id="#+id/camera_frame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ImageView
android:id="#+id/camera_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<SurfaceView
android:id="#+id/preview_view_1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="#+id/v1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCFFFFFF"/>
<SurfaceView
android:id="#+id/preview_view"
android:layout_margin="80dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- <LinearLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:background="#android:color/transparent"-->
<!-- android:layout_height="match_parent">-->
<!-- -->
<!-- </LinearLayout>-->
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/capture_image_button"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/capture_image" />
<Button
android:id="#+id/done_button"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/done" />
</LinearLayout>
</LinearLayout>
Here seems to be 2 workarounds:
Either i dynamically set the surface view "camera_image_view" at the time user try to capture screen. But i tried that in onClick and it is not working. Please suggest me some changes if you found any bug in that.
Clicking a full screen image and then cropping it to whatever fits inside the length and width of "camera_image_view". I tried this also but i think there is some flaw in this line:
Bitmap resizedbitmap1=Bitmap.createBitmap(bitmap, 0,0,mCameraPreview.getWidth(), mCameraPreview.getHeight());
as it is generating some broken colors instead of the cropped image.
So please help me with any of the two ways as both will work for me.
I'm new to Android Application Development, I was trying to build a basic Flashlight app but seems like most of the libraries are deprecated. I have tried doing Camera.Parameters camera; but still not working. Log shows the Exception : Caused by: java.lang.RuntimeException: Fail to connect to camera service.AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
MainActivity.java
package com.thenewboston.flashlight;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.hardware.Camera.Parameters;
public class MainActivity extends AppCompatActivity {
private android.hardware.Camera camera = null;
Parameters params;
Boolean isOn;
ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.imageButton);
Boolean isCameraFlash = getApplication().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if(!isCameraFlash)
showNoCameraAlert();
else{
camera = android.hardware.Camera.open();
params = camera.getParameters();
}
}
private void showNoCameraAlert() {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("Sorry, your device doesn't support flash light!")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
public void myButton(View view){
if (isOn){
setFlashOff();
}
else {
setFlashOn();
}
}
private void setFlashOn() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isOn = true;
}
private void setFlashOff() {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isOn = false;
}
#Override
protected void onStop() {
super.onStop();
if(camera != null){
camera.release();
camera = null;
}
}
}
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.thenewboston.flashlight.MainActivity"
android:background="#000000">
<ImageButton
android:layout_width="150dp"
android:layout_height="150dp"
android:id="#+id/imageButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="#drawable/mytoggle"
android:scaleType="fitCenter"
android:background="#null"
android:onClick="myButton" />
</RelativeLayout>
I know, I'm using outdated stuff in my code, but that's probably because I have not seen anyone building flashlight app for Marshmallow. If anyone can suggest new code it will be helpful or correct my code(given above) will be thankful.
I am developing my own custom camera app,while running the application if I click the capture button my camera will capture the current position.what I actually need is retaking a photo whenever I need.But if I click the retake(take photo) button the app will crash.Here I attached my code below.So any one please help me to resolve the error.
MainActivity.java
package com.example.camera1;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Camera cameraObject;
private ShowCamera showCamera;
private ImageView pic;
private Button takePhotoButton;
public static Camera isCameraAvailiable(){
Camera object = null;
try {
object = Camera.open();
}
catch (Exception e){
}
return object;
}
private PictureCallback capturedIt = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
if(bitmap==null){
Toast.makeText(getApplicationContext(), "not taken", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "taken", Toast.LENGTH_SHORT).show();
}
cameraObject.release();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhotoButton = (Button)findViewById(R.id.button_takephoto);
cameraObject = isCameraAvailiable();
showCamera = new ShowCamera(this, cameraObject);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(showCamera);
takePhotoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cameraObject = isCameraAvailiable();
cameraObject.stopPreview();
showCamera = new ShowCamera(getApplicationContext(), cameraObject);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(showCamera);
}
});
}
public void snapIt(View view){
cameraObject.takePicture(null, null, capturedIt);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
ShowCamera.java
package com.example.camera1;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holdMe;
private Camera theCamera;
public ShowCamera(Context context,Camera camera) {
super(context);
theCamera = camera;
holdMe = getHolder();
holdMe.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
theCamera.setDisplayOrientation(90);
theCamera.setPreviewDisplay(holder);
theCamera.startPreview();
} catch (IOException e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
theCamera.stopPreview();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.30"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="350dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button_capture"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="snapIt"
android:text="#string/Capture" />
<Button
android:id="#+id/button_takephoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button_capture"
android:text="Take Photo" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
I think the reason is you called cameraObject.release(); in onPictureTaken. You can remove it. And, don't forget to call startPreview() again.
Because:
This method is only valid when preview is active (after
startPreview()). Preview will be stopped after the image is taken;
callers must call startPreview() again if they want to re-start
preview or take more pictures. This should not be called between
start() and stop().
After calling this method, you must not call startPreview() or take
another picture until the JPEG callback has returned.
cameraObject.release();
Remove this line from tour PictureCallback. Now you know reason your app crash is quite straight to me , you are not start camera and preview also after you capture image. Preview is something stop after you call PictureCallback ,you have resume it manually.
IF you dont want to manage this thing then i can advise you to use cwac-camera library which is simply awesome. All you need to do is extend your Fragment by CameraFragment and it will take your responsibility to manage this stuff .
Enjoy !
I have to call multiple services in background for a project in android app.
In each services i have to call separate web service and get some data and process it with local sqlite database. I am able to call each service separately and can manipulate its result with local database.
But not able to call all services in a sequence.
my code is as below:
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Timer timer = new Timer();
final SyncTableUsers syncUserObj = new SyncTableUsers(LocalService.this);
final SyncTableVehicles syncVehicleObj = new SyncTableVehicles(this);
final SyncTableLicenses syncLicenseObj = new SyncTableLicenses(this);
final SyncTableTags syncTagObj = new SyncTableTags(this);
final SyncTableTagMappings syncTagMapObj = new SyncTableTagMappings(this);
final SyncTableAddresses syncAddressObj = new SyncTableAddresses(this);
final SyncTableDispatches syncDispatchObj = new SyncTableDispatches(this);
final SyncEditCompany syncCompanyObj = new SyncEditCompany(LocalService.this);
final SyncEditVehicle syncEditVehicleObj = new SyncEditVehicle(LocalService.this);
final SyncEditUser syncEditUserObj = new SyncEditUser(this);
final SyncVehicleLog vLogObj = new SyncVehicleLog(LocalService.this);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
syncUserObj.syncUserData();
syncVehicleObj.syncVehicleData();
syncLicenseObj.syncLicensesData();
syncTagObj.syncTagData();
syncTagMapObj.syncTagMappingData();
syncAddressObj.syncAddressData();
syncDispatchObj.syncDispatchData();
syncCompanyObj.syncCompanyData();
syncEditVehicleObj.syncVehicleData();
syncEditUserObj.syncUserData();
Log.i("TAG", "LogId After insert values ");
}
}
};
timer.scheduleAtFixedRate(timerTask, 10000, 180000); call after every
3 minute
super.onStart(intent, startid);
syncUserData is a method, which call web service.
I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks and calling web services using devices having latest OS virsion you must need to use AsyncTask.
It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.
private class YourTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//call your methods from here
//publish yor progress here..
publishProgress((int) ((i / (float) count) * 100));
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//action after execution success or not
}
}
Use Intent Service to execute your tasks in sequence.
Check out the below link for details
https://developer.android.com/reference/android/app/IntentService.html
<uses-sdk
android:minSdkVersion="8"
tools:ignore="GradleOverrides" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Videocapture Activity - activitymain
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="#+id/CameraView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical">
<LinearLayout
android:gravity="center_vertical"
android:background="#color/color_transparent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txt_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_weight="1"
android:textSize="30dp"
android:textColor="#color/color_white" />
<CheckBox
android:button="#drawable/checkbox"
android:id="#+id/chk_videorecord"
android:layout_width="100dp"
android:layout_height="100dp"
android:textColor="#color/color_white"
android:textOff="#null"
android:textOn="#null" />
<TextView
android:id="#+id/txt_submit"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="30dp"
android:textColor="#color/color_white" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.VideoView;
public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
public static final String LOGTAG = "VIDEOCAPTURE";
private MediaRecorder recorder;
private SurfaceHolder holder;
private CamcorderProfile camcorderProfile;
private Camera camera;
boolean recording = false;
boolean usecamera = true;
boolean previewRunning = false;
TextView txt_cancel, txt_submit;
CheckBox chk_videorecord;
private String str_record_file;
private Uri uri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
setContentView(R.layout.activity_main);
chk_videorecord = findViewById(R.id.chk_videorecord);
final SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
txt_cancel = findViewById(R.id.txt_cancel);
txt_submit = findViewById(R.id.txt_submit);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
chk_videorecord.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chk_videorecord.isChecked())
{
chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_stop_record));
recording = true;
recorder.start();
Toast.makeText(VideoCapture.this, "Recording Started", Toast.LENGTH_SHORT).show();
} else {
chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_start_record));
recorder.stop();
Toast.makeText(VideoCapture.this, "Recording Stop", Toast.LENGTH_SHORT).show();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
Log.v(LOGTAG, "Recording Stopped");
// Let's prepareRecorder so we can record again
prepareRecorder();
}
}
});
txt_cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
txt_submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if(str_record_file!=null) {
Intent intent = new Intent(VideoCapture.this, HomeActivity.class);
intent.putExtra("str_record_file", str_record_file);
startActivity(intent);
}
}
});
}
private void prepareRecorder() {
recorder = new MediaRecorder();
recorder.setPreviewDisplay(holder.getSurface());
if (usecamera) {
camera.unlock();
recorder.setCamera(camera);
}
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setProfile(camcorderProfile);
// This is all very sloppy
if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.THREE_GPP)
{
try {
File newFile = File.createTempFile("videocapture", ".3gp", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
} else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
try {
File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
} else {
try {
File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
}
//recorder.setMaxDuration(50000); // 50 seconds
//recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
Log.v(LOGTAG, "Recording Stopped");
// Let's prepareRecorder so we can record again
prepareRecorder();
} else {
recording = true;
recorder.start();
Log.v(LOGTAG, "Recording Started");
}
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceCreated");
if (usecamera) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
Log.e(LOGTAG, e.getMessage());
e.printStackTrace();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(LOGTAG, "surfaceChanged");
if (!recording && usecamera) {
if (previewRunning) {
camera.stopPreview();
}
try {
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
p.setPreviewFrameRate(camcorderProfile.videoFrameRate);
camera.setParameters(p);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
Log.e(LOGTAG, e.getMessage());
e.printStackTrace();
}
prepareRecorder();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed");
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
if (usecamera) {
previewRunning = false;
//camera.lock();
camera.release();
}
finish();
}
}
Custom Tinder
implementation 'com.mindorks:placeholderview:0.7.1'
implementation 'com.android.support:cardview-v7:25.3.1'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.google.code.gson:gson:2.7'
<string-array name="arry_card">
<item>Sofia</item>
<item>Roma</item>
<item>Zoya</item>
</string-array>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="white">#FFFFFF</color>
<color name="grey">#757171</color>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/rejectBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/ic_cancel"/>
<ImageButton
android:id="#+id/acceptBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="30dp"
android:background="#drawable/ic_heart"/>
</LinearLayout>
<com.mindorks.placeholderview.SwipePlaceHolderView
android:id="#+id/swipeView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
tinder_card_view
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="350dp"
android:layout_height="425dp"
android:layout_marginBottom="50dp"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:orientation="vertical"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
app:cardCornerRadius="7dp"
app:cardElevation="4dp">
<ImageView
android:id="#+id/profileImageView"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="75dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="75dp"
android:orientation="vertical"
android:layout_gravity="bottom"
android:gravity="center|left"
android:paddingLeft="20dp">
<TextView
android:id="#+id/nameAgeTxt"
android:layout_width="wrap_content"
android:textColor="#color/colorPrimaryDark"
android:textSize="18dp"
android:textStyle="bold"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/locationNameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimaryDark"
android:textSize="14dp"
android:textStyle="normal"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
tinder_swipe_in_msg_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="425dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:textStyle="bold"
android:layout_margin="40dp"
android:textColor="#android:color/holo_green_light"
android:text="Accept"/>
</LinearLayout>
tinder_swipe_out_msg_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:gravity="right"
android:layout_height="425dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:textStyle="bold"
android:layout_margin="40dp"
android:textColor="#android:color/holo_red_light"
android:text="Reject"/>
</LinearLayout>
Profile
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Profile {
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String imageUrl;
#SerializedName("age")
#Expose
private Integer age;
#SerializedName("location")
#Expose
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
TinderCard
import android.content.Context;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import com.mindorks.placeholderview.annotations.Layout;
import com.mindorks.placeholderview.annotations.Resolve;
import com.mindorks.placeholderview.annotations.View;
import com.mindorks.placeholderview.annotations.swipe.SwipeCancelState;
import com.mindorks.placeholderview.annotations.swipe.SwipeIn;
import com.mindorks.placeholderview.annotations.swipe.SwipeInState;
import com.mindorks.placeholderview.annotations.swipe.SwipeOut;
import com.mindorks.placeholderview.annotations.swipe.SwipeOutState;
#Layout(R.layout.tinder_card_view)
public class TinderCard {
#View(R.id.profileImageView)
private ImageView profileImageView;
#View(R.id.nameAgeTxt)
private TextView nameAgeTxt;
#View(R.id.locationNameTxt)
private TextView locationNameTxt;
private Profile mProfile;
private Context mContext;
private SwipePlaceHolderView mSwipeView;
public TinderCard(Context context, Profile profile, SwipePlaceHolderView swipeView) {
mContext = context;
mProfile = profile;
mSwipeView = swipeView;
}
#Resolve
private void onResolved(){
Glide.with(mContext).load(mProfile.getImageUrl()).into(profileImageView);
nameAgeTxt.setText(mProfile.getName() + ", " + mProfile.getAge());
locationNameTxt.setText(mProfile.getLocation());
}
#SwipeOut
private void onSwipedOut(){
Log.d("EVENT", "onSwipedOut");
mSwipeView.addView(this);
}
#SwipeCancelState
private void onSwipeCancelState(){
Log.d("EVENT", "onSwipeCancelState");
}
#SwipeIn
private void onSwipeIn(){
Log.d("EVENT", "onSwipedIn");
}
#SwipeInState
private void onSwipeInState(){
Log.d("EVENT", "onSwipeInState");
}
#SwipeOutState
private void onSwipeOutState(){
Log.d("EVENT", "onSwipeOutState");
}
}
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.gson.Gson;
import com.mindorks.placeholderview.SwipeDecor;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private SwipePlaceHolderView mSwipeView;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeView = (SwipePlaceHolderView) findViewById(R.id.swipeView);
mContext = getApplicationContext();
mSwipeView.getBuilder()
.setDisplayViewCount(3)
.setSwipeDecor(new SwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
.setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
List<Profile> profileList = new ArrayList<>();
List<String> arrayList = Arrays.asList(getResources().getStringArray(R.array.arry_card));
for (int i = 0; i < arrayList.size(); i++) {
//Profile profile = Gson.fromJson(arrayList.get(i), Profile.class);
Profile profile = new Profile();
profile.setName(arrayList.get(i));
profile.setAge(2);
profile.setImageUrl("");
profile.setLocation("");
profileList.add(profile);
}
for (Profile profile : profileList) {
mSwipeView.addView(new TinderCard(mContext, profile, mSwipeView));
}
findViewById(R.id.rejectBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(false);
}
});
findViewById(R.id.acceptBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(true);
}
});
}
}
I am trying to implement an activity which shows a camera preview and contains two buttons. Getting the camera preview is no problem but when I try findViewById for the button objects the app will crash. Not sure why that's happening.
package com.capstone.parking.nyc;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.graphics.PixelFormat ;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorManager;
public class MainScreen extends Activity implements SurfaceHolder.Callback
{
Camera theCamera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean preview = false;
private SensorManager mSensorManager;
private ShakeListener mSensorListener;
#Override
public void onCreate(Bundle savedInstanceState)
{
final Button TagBttn;
final Button ParkBttn;
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFormat(PixelFormat.UNKNOWN);
setContentView(R.layout.mainscreen);
/*
*
* This line causes the crash
*/
TagBttn = (Button) findViewById(R.id.tag);
// ParkBttn = (Button)findViewById(R.id.park);
surfaceView = (SurfaceView) findViewById(R.id.camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mSensorListener = new ShakeListener();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
Log.d("TAG", "onCreate MainScreen");
mSensorListener.setOnShakeListener(new ShakeListener.OnShakeListener()
{
public void onShake()
{
Log.d("SHAKE CHECK", "YUSSSSSS");
// if shaken, go to the search screen
startActivity(new Intent("com.capstone.parking.SEARCH"));
}
});
/* Tag.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
/*
*
* ENTER TAG CODE HERE
*
*
Log.d("TAG", "tag button pressed");
}
});
/*
/* Park.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
/*
*
* ENTER PARK CODE HERE
*
*
Log.e("TAG", "park button pressed");
}
});
*/
}
#Override
public void onResume()
{
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onStop()
{
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
public void surfaceCreated(SurfaceHolder holder)
{
Log.e("TAG", "surfaceCreated");
theCamera = Camera.open();
try
{
theCamera.setPreviewDisplay(holder);
}
catch (IOException e)
{
Log.e("TAG", "surfaceCreated FAIL");
}
theCamera.startPreview();
preview = true;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
Log.e("TAG", "surfaceChanged");
if(preview)
{
theCamera.stopPreview();
}
Camera.Parameters parameters = theCamera.getParameters();
parameters.setPreviewSize(width, height);
// parameters.set("orientation", "portrait");
// parameters.set("rotation", "90");
theCamera.setParameters(parameters);
theCamera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
if(preview)
{
Log.e("TAG", "surfaceDestroyed");
theCamera.stopPreview();
theCamera.release();
theCamera = null;
preview = false;
}
}
}
If anyone could guide me in the right direction I would greatly appreciate it. Thanks!
mainscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/background"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#006699" >
<TextView
android:id="#+id/scroll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="#string/shake"
android:textColor="#ffff66"
android:textStyle="bold" />
<SurfaceView
android:id="#+id/camera"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginBottom="125dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" >
</SurfaceView>
<ImageButton
android:id="#+id/tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="25dp"
android:layout_marginBottom="50dp"
android:contentDescription="#string/desc"
android:background="#drawable/tagbuttonselect"
android:clickable="true" />
<ImageButton
android:id="#+id/park"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="25dp"
android:layout_marginBottom="50dp"
android:contentDescription="#string/desc"
android:background="#drawable/parkbuttonselect"
android:clickable="true" />
</RelativeLayout>
Edit**
Oh wow. I'm retarded. I just figured it out. I was using Button instead of ImageButton. SMH Sorry, guys. lol
Try changing TagBttn = (Button) findViewById(R.id.tag); to TagBttn = (ImageButton) findViewById(R.id.tag);
may be you are trying to find id is not in mainscreen.xml
here tag is an ImageButton no simole Button
try this
TagBttn = (ImageButton) findViewById(R.id.tag);
Your tag item is an ImageButton and you are casting it to a Button. Change it. ImageButton and Button are very different classes.
No matter how confusing it may sound, it turns out that ImageButton is not a subclass of Button. So you'd want to replace your code with:
final ImageButton TagBttn;
final ImageButton ParkBttn;
and then use:
TagBttn = (ImageButton) findViewById(R.id.tag);
ParkBttn = (ImageButton) findViewById(R.id.park);