Android Studio, Capture FrameLayout View, While Camera is StopPreview() - android-studio

This is my CameraView.java (I got it from http://blog.rhesoft.com/)
public class CameraView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context, Camera camera){
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(90);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try{
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
if(mHolder.getSurface() == null)
return;
try{
mCamera.stopPreview();
} catch (Exception e){
}
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}}
and this is my MainActivity.java.
public class MainActivity extends AppCompatActivity {
private Camera mCamera = null;
private CameraView mCameraView = null;
private FrameLayout camera_view;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mCamera = Camera.open();
//you can use open(int) to use different cameras
} catch (Exception e){
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if(mCamera != null) {
mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
camera_view = (FrameLayout)findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
//btn to close the application
final ImageButton imgClose = (ImageButton)findViewById(R.id.imgClose);
final ImageButton capImg = (ImageButton) findViewById(R.id.imgCapture);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imgClose.setVisibility(View.INVISIBLE);
capImg.setVisibility(View.VISIBLE);
mCamera.startPreview();
}
});
capImg.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mCamera.stopPreview();
imgClose.setVisibility(View.VISIBLE);
capImg.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onBackPressed(){
System.exit(0);
}}
and this my activity_main.xml.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgClose"
android:layout_gravity="right|top"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:padding="20dp"
android:visibility="invisible" />
<ImageButton
android:layout_width="98dp"
android:layout_height="98dp"
android:id="#+id/imgCapture"
android:layout_gravity="center_horizontal|bottom"
android:background="#android:drawable/ic_menu_camera"
android:padding="20dp"/>
Can I capture this FrameLayout preview as image or do some programing with that preview like delete red color? Can you give me some clue?

So if I understand correctly, you wish to get the image data that is shown when you stop the preview? If you so you can mCamera.takePicture() method. It takes 3 parameters, all of which are useful callbacks. Here is something I recently did to show you.
btn_Capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCamera == null)
return;
mCamera.takePicture(null, null, mPicture);
}
});
This is my button click listener which is a floating image button (any button will work just fine). The third parameter is a callback that returns an array of pixels that you can convert into a bitmap.
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
mCamera.stopPreview();
Bitmap bMap = BitmapFactory.decodeByteArray(data, 0, data.length);
preview.removeView(mPreview);
img_Captured.setImageBitmap(bMap);
}
};
This is the callback which I passed in the takePicture() method. byte[] data is the image that you are trying to get. As you can see I converted it into a bitmap and displayed it to an ImageView after removing the surfaceview (which holds the camera preview). Just a note, the takePicture() method stops the preview automatically so don't stop the preview before taking the photo. You can do it how I did it in the callback. Also, if you want to take another photo, you can start the preview again.
I hope this helps!! Let me know if I left anything out! By the way, it is all documented on the Android Developer site.
http://developer.android.com/training/camera/cameradirect.html#TaskTakePicture

Related

My App crashing due to the inMobi Banner Ads can i know where i am wrong in the code

I have written Inmobi Banner code but my app is crashing, please can anyone help what is wrong. MainActivity.java and Activity_main.xml codes are as below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private InMobiBanner mBanner;
private static final String TAG = MainActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InMobiSdk.setLogLevel(InMobiSdk.LogLevel.DEBUG);
mBanner = findViewById(R.id.banner);
setupBannerAd();
JSONObject consentObject = new JSONObject();
try {
// Provide correct consent value to sdk which is obtained by User
consentObject.put(InMobiSdk.IM_GDPR_CONSENT_AVAILABLE, true);
// Provide 0 if GDPR is not applicable and 1 if applicable
consentObject.put("gdpr", "0");
} catch (JSONException e) {
e.printStackTrace();
}
InMobiSdk.init(this, "a4d02aad2f14407782fdd6053fa5988f", consentObject, error -> {
if (null != error) {
Log.e(TAG, "InMobi Init failed -" + error.getMessage());
} else {
Log.d(TAG, "InMobi Init Successful");
}
});
}
private void setupBannerAd() {
mBanner.setListener(new BannerAdEventListener() {
#Override
public void onAdLoadSucceeded(#NonNull InMobiBanner inMobiBanner,
#NonNull AdMetaInfo adMetaInfo) {
Log.d(TAG, "onAdLoadSucceeded with bid " + adMetaInfo.getBid());
}
#Override
public void onAdLoadFailed(#NonNull InMobiBanner inMobiBanner, #NonNull InMobiAdRequestStatus inMobiAdRequestStatus) {
Log.d(TAG, "Banner ad failed to load with error: " +
inMobiAdRequestStatus.getMessage());
}
#Override
public void onAdClicked(#NonNull InMobiBanner inMobiBanner, #NonNull Map<Object, Object> map) {
Log.d(TAG, "onAdClicked");
}
#Override
public void onAdDisplayed(#NonNull InMobiBanner inMobiBanner) {
Log.d(TAG, "onAdDisplayed");
}
#Override
public void onAdDismissed(#NonNull InMobiBanner inMobiBanner) {
Log.d(TAG, "onAdDismissed");
}
#Override
public void onUserLeftApplication(#NonNull InMobiBanner inMobiBanner) {
Log.d(TAG, "onUserLeftApplication");
}
#Override
public void onRewardsUnlocked(#NonNull InMobiBanner inMobiBanner, #NonNull Map<Object, Object> map) {
Log.d(TAG, "onRewardsUnlocked");
}
});
mBanner.load();
}
}
ActivityMain.XML Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/lib/com.inmobi.ads"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<com.inmobi.ads.InMobiBanner
android:id="#+id/banner"
android:layout_width="320dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:placementId="plid-1638544811338"
ads:refreshInterval="60"/>
</RelativeLayout>
The problem is InMobi Banner expects InMobiSDK to be initialized, Now in the code if you see you have added InMobiBanner in xml and when you do setContentView the InMobiBanner will expect InMobiSDK to be initialized but the InMobiSDK code initialization is written after the setContentView. Hence it will throw an exception and your app will crash.
Solution would be to add init code before setContentView or to programmatically add Banner View to your UI

SearchView retrieving wrong data with List View

When searching for an item, I'm able to retrieve the Title, Artist, and Image for the respective Songs. However, the first 2 items displayed in the ListView when clicked on keeps returning the last song in my list instead of the correct song that is being displayed.
E.g, When clicking on "Life is Good" or "Good as hell", the song "First Time" will be displayed instead. However "Perfect", "Lemon", and "Autopilot" are working fine. These are the only codes used to search! SearchByTitle and GetTitle() are taken from the files where the songs are hardcoded in!
My Activity:
ListView listView;
ArrayList<String> stringArrayList = new ArrayList<>();
ArrayAdapter<String> adapter;
private SongCollection songCollection = new SongCollection();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listView = findViewById(R.id.list_view);
stringArrayList.add("Life is Good");
stringArrayList.add("Good As Hell");
stringArrayList.add("Perfect");
stringArrayList.add("Lemon");
stringArrayList.add("Autopilot");
stringArrayList.add("First Time");
adapter = new ArrayAdapter<>(SearchActivity.this, android.R.layout.simple_list_item_1, stringArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),
adapter.getItem(i), Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String value = listView.getItemAtPosition(i).toString();
Song selectedSong = songCollection.searchByTitle(value);
AppUtil.popMessage(view.getContext(), "Streaming song: " + selectedSong.getTitle());
sendDataToActivity(selectedSong);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.my_menu, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
XML to my Activity:
<?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"
android:background="#404040"
tools:context=".SearchActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#404040">
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#FFFFFF"
android:divider="#color/white"
android:dividerHeight="2dp"
tools:listitem="#android:layout/simple_list_item_1">
</ListView>
</LinearLayout>
</RelativeLayout>
It happens because you need to create a new list which would contain the search results, you don't have to do the search operation with your original list which isstringArrayList
Instead create a new list which is mylist in this case, and store the search results and call that list in onQueryTextChange
Create this method, I modified the code according to your code
private void search(String str) {
ArrayList<String> myList = new ArrayList<>();
for (Quote object : stringArrayList) {
if (object.GetTitle().toLowerCase().contains(str.toLowerCase())) {
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(this, myList);//, swiper
recyclerView.setAdapter(adapterClass);
}
Now, call this method under search setOnQueryTextListener, like this
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
OPTIONAL
And one more modification which you can do is you can check setOnQueryTextListener when ever there is some text in it, like this
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(s);
return true;
}
});
}
If my answer solves your problem you can give me an up-vote and mark my answer as correct, by clicking on the gray tick button beside the starting of my answer, which will then turn green!

Android: Selecting an Image from sdcard and displaying it in Fragment

I'm working with fragments (API 4.1) and I want to let the user press a button, access his/her gallery, select an image, and have that image display an imageview on the original fragment where the button appeared. I'm using the following code:
public class FillBox1Frag extends Fragment {
Button addPics, placeBox;
ImageView imgView;
Bitmap b;
Uri photoUri;
LinearLayout fillBoxLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
fillBoxLayout = (LinearLayout) inflater.inflate(R.layout.fillbox1_frag,
container, false);
newBin = new Bin();
addPics = (Button) fillBoxLayout.findViewById(R.id.bPics);
imgView = (ImageView) fillBoxLayout.findViewById(R.id.imageView1);
addPics.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent picChooser = new Intent(Intent.ACTION_GET_CONTENT,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
picChooser.setType("image/*");
startActivityForResult(picChooser, 12345);
}
});
return fillBoxLayout;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 12345:
if (resultCode == 12345) {
photoUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = FillBox1Frag.this.getActivity()
.getContentResolver()
.query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
b = BitmapFactory.decodeFile(filePath);
imgView.setImageBitmap(b);
}
}
}
I access the Gallery, but upon selection, it just returns to the original fragment and doesn't display the image. Here's my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fillbox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="fillbox" >
<Button
android:id="#+id/bPics"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="89dp"
android:background="#drawable/buttonpics" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
I've found plenty of answers dealing with a similar question, but nothing that has been able to help me with how to create this process using fragments. Any ideas on how to get my selected image to appear in the ImageView? Thanks for the help!

opencv implementation with with custom layout (on SurfaceView)

I have an openCV application program working, but need to add buttons etc. to the layout. So basically I want to display the opencv camera view on a surfaceView and the add the other stuff underneath.
I've been searching the internet and forums for a while, only seeing the guy with a opencv facial detection application also wanting to add a custom layout... no solution.
I am really desperate for a solution so would hugely appreciate help. For this purpose I used the OpenCV sample 3 application (as a simple example) and tried to bind to a surfaceview on a simple custom layout. I managed it in a normal Camera application, but struggling quite a bit with the opencv example.
So this is the code that I have for the Sample3Native.java, Sample3View.java and SampleViewBase.java (as in example) files respectively:
public class Sample3Native extends Activity {
private Sample3View mView;
private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
// Load native library after(!) OpenCV initialization
System.loadLibrary("native_sample");
// Create and set View
mView = new Sample3View(mAppContext);
setContentView(R.layout.main);
//setContentView(mView);
// Check native OpenCV camera
mView.openCamera();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
//constructor
public Sample3Native() {}
#Override
protected void onPause() {
super.onPause();
if (null != mView)
mView.releaseCamera();
}
#Override
protected void onResume() {
super.onResume();
if((null != mView) && !mView.openCamera() ) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Fatal error: can't open camera!");
ad.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
ad.show();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mOpenCVCallBack);
}
}
class Sample3View extends SampleViewBase {
private int mFrameSize;
private Bitmap mBitmap;
private int[] mRGBA;
public Sample3View(Context context) {
super(context);
}
#Override
protected void onPreviewStarted(int previewWidtd, int previewHeight) {
mFrameSize = previewWidtd * previewHeight;
mRGBA = new int[mFrameSize];
mBitmap = Bitmap.createBitmap(previewWidtd, previewHeight, Bitmap.Config.ARGB_8888);
}
#Override
protected void onPreviewStopped() {
if(mBitmap != null) {
mBitmap.recycle();
mBitmap = null;
}
mRGBA = null;
}
#Override
protected Bitmap processFrame(byte[] data) {
int[] rgba = mRGBA;
FindFeatures(getFrameWidth(), getFrameHeight(), data, rgba);
Bitmap bmp = mBitmap;
bmp.setPixels(rgba, 0, getFrameWidth(), 0, 0, getFrameWidth(), getFrameHeight());
return bmp;
}
public native void FindFeatures(int width, int height, byte yuv[], int[] rgba);
}
public abstract class SampleViewBase extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private Camera mCamera;
private SurfaceHolder mHolder;
private SurfaceView mViewer;
private int mFrameWidth;
private int mFrameHeight;
private byte[] mFrame;
private boolean mThreadRun;
private byte[] mBuffer;
public SampleViewBase(Context context) {
super(context);
mViewer = (SurfaceView)this.findViewById(R.id.camera_view);
mHolder = mViewer.getHolder();
mHolder.addCallback(this);
}
public int getFrameWidth() {
return mFrameWidth;
}
public int getFrameHeight() {
return mFrameHeight;
}
public boolean openCamera() {
releaseCamera();
mCamera = Camera.open();
if(mCamera == null)
return false;
mCamera.setPreviewCallbackWithBuffer(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
synchronized (SampleViewBase.this) {
System.arraycopy(data, 0, mFrame, 0, data.length);
SampleViewBase.this.notify();
}
camera.addCallbackBuffer(mBuffer);
}
});
return true;
}
public void releaseCamera() {
mThreadRun = false;
synchronized (this) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
onPreviewStopped();
}
public void setupCamera(SurfaceHolder holder,int width, int height) {
synchronized (this) {
if (mCamera != null) {
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
mFrameWidth = width;
mFrameHeight = height;
// selecting optimal camera preview size
{
int minDiff = Integer.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - height) < minDiff) {
mFrameWidth = size.width;
mFrameHeight = size.height;
minDiff = Math.abs(size.height - height);
}
}
}
params.setPreviewSize(getFrameWidth(), getFrameHeight());
List<String> FocusModes = params.getSupportedFocusModes();
if (FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
{
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mCamera.setParameters(params);
/* Now allocate the buffer */
params = mCamera.getParameters();
int size = params.getPreviewSize().width * params.getPreviewSize().height;
size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
mBuffer = new byte[size];
/* The buffer where the current frame will be copied */
mFrame = new byte [size];
mCamera.addCallbackBuffer(mBuffer);
try {
mCamera.setPreviewDisplay(holder);
//mCamera.setPreviewDisplay(null);
} catch (IOException e) {}
/* Notify that the preview is about to be started and deliver preview size */
onPreviewStarted(params.getPreviewSize().width, params.getPreviewSize().height);
/* Now we can start a preview */
mCamera.startPreview();
}
}
}
public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
setupCamera(_holder,width, height);
}
public void surfaceCreated(SurfaceHolder holder) {
(new Thread(this)).start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
//abstract functions used by child class
protected abstract Bitmap processFrame(byte[] data);
protected abstract void onPreviewStarted(int previewWidtd, int previewHeight);
protected abstract void onPreviewStopped();
//================================
public void run() {
mThreadRun = true;
while (mThreadRun) {
Bitmap bmp = null;
synchronized (this) {
try {
this.wait();
bmp = processFrame(mFrame);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (bmp != null) {
Canvas canvas = mHolder.lockCanvas();
if (canvas != null) {
canvas.drawBitmap(bmp, (canvas.getWidth() - getFrameWidth()) / 2, (canvas.getHeight() - getFrameHeight()) / 2, null);
mHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
I know this must be a MAJOR drag to go through my code, but I really need the help. Or even if I could get a link to a working example of this type of implementation. Also, please just don't send me this link (it doesn't help me):openCV in custom applications
This is my acitivity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:opencv="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<org.opencv.android.JavaCameraView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
android:id="#+id/tutorial1_activity_java_surface_view"
opencv:show_fps="true"
opencv:camera_id="any" />
<org.opencv.android.NativeCameraView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
android:id="#+id/tutorial1_activity_native_surface_view"
opencv:show_fps="true"
opencv:camera_id="any" />
<Button
android:id="#+id/btnOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="105dp"
android:layout_marginTop="139dp"
android:onClick="OKClicked"
android:text="#string/OK" />
<TextView
android:id="#+id/txtDisp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnOK"
android:layout_alignBottom="#+id/btnOK"
android:layout_marginLeft="25dp"
android:layout_toRightOf="#+id/btnOK"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
And these code must be edited to MainActivity.java class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mIsJavaCamera){
mOpenCvCameraView = (CameraBridgeViewBase)findViewById(R.id.tutorial1_activity_java_surface_view);
}else{
mOpenCvCameraView = (CameraBridgeViewBase)findViewById(R.id.tutorial1_activity_native_surface_view);
}
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
ArrayList<View> views = new ArrayList<View>();
views.add(findViewById(R.id.btnOK));
views.add(findViewById(R.id.txtDisp));
mOpenCvCameraView.addTouchables(views);
}
public void OKClicked(View view){
TextView disp = (TextView)findViewById(R.id.txtDisp);
disp.setText("OK Clicked");
}
This code is modified to OpenCV Tutorial 1.
You will see a button and a TextView over the surfaceview. When you click OK button TextView will show "OK Clicked". This is working for me on Samsung Galaxy.

ProgressBar while loading ListView (using AsyncTask)

I'm trying to show a progress bar when loading a custom ListView and afterwards - hide it.
I'm using ASync task, but for some reason - The content view is not set and the previous layout view is stuck until all the list view is loaded.
Here is my code:
private ListView listViewGameResults;
protected View dialogLayout;
protected ArrayList<Game> listGames;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adresults);
GameResultsLoader gameResultsLoader = new GameResultsLoader();
gameResultsLoader.execute();
}
private class GameResultsLoader extends AsyncTask<Void, Void, Void> {
private GameResultsAdapter adapter;
public GameResultsLoader() {
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
listGames = GameResultsCache.getInstance().getGameResults();
adapter = new GameResultsAdapter(getBaseContext(), listGames);
listViewGameResults = (ListView)findViewById(R.id.listViewGameResults);
}
catch (Exception e) {
// TODO Auto-generated catch block
finish();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
listViewGameResults.setAdapter(adapter);
listViewGameResults.setDivider(null);
listViewGameResults.setDividerHeight(0);
ProgressBar pb = (ProgressBar)findViewById(R.id.progressbar_loading);
pb.setVisibility(View.GONE);
}
}
ProgressBar and ListView in my layout:
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_centerInParent="true"
android:id="#+id/progressbar_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listViewGameResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="1dip"
android:layout_below="#+id/upperstrip"
android:layout_above="#+id/ivDownStrip" />
You need to set default visibility of progressBar gone.and onPreExecute()set Visible and onPostExecute()set gone.
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_centerInParent="true"
android:id="#+id/progressbar_loading"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listViewGameResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="1dip"
android:layout_below="#+id/upperstrip"
android:layout_above="#+id/ivDownStrip" />
your Activity should look like this
public class demo extends Activity{
private ListView listViewGameResults;
protected View dialogLayout;
protected ArrayList<Game> listGames;
progressBar progress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adresults);
progress=(ProgressBar)findViewByid(R.id.progressbar_loading);
GameResultsLoader gameResultsLoader = new GameResultsLoader(this);
gameResultsLoader.execute();
}
}
Use one separate class for AsyncTask
public class GameResultsLoader extends AsyncTask<Void, Void, Void> {
private GameResultsAdapter adapter;
Demo demo;
public GameResultsLoader(Demo demo) {
this.demo=demo;
}
#Override
protected void onPreExecute() {
demo.progress.setvisibility(View.Visible);
}
#Override
protected Void doInBackground(Void... params) {
try {
listGames = GameResultsCache.getInstance().getGameResults();
adapter = new GameResultsAdapter(getBaseContext(), listGames);
listViewGameResults = (ListView)findViewById(R.id.listViewGameResults);
}
catch (Exception e) {
// TODO Auto-generated catch block
finish();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
listViewGameResults.setAdapter(adapter);
listViewGameResults.setDivider(null);
listViewGameResults.setDividerHeight(0);
ProgressBar pb = (ProgressBar)findViewById(R.id.progressbar_loading);
demo.progress.setVisibility(View.GONE);
}
}
if your using asnkTask that is work on main Thread so application is much more load.so better solution is using Service.class.
downlaod this example Check this link all are solution are there and download it:
you have to also get list from relaunch this application.
https://github.com/PankajSavaliyaGit/Upload-List
you have to write code to start progressDialog in preExecute method and at the postExecute dismiss it.
#Override
protected void onPreExecute() {
proDialog = new ProgressDialog(context);
proDialog.setTitle("App name");
proDialog.setMessage("Loding...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//proDialog.setIcon(R.drawable.)
proDialog.setCancelable(true);
proDialog.show();
}
#Override
protected void onPostExecute(Void res) {
proDialog.dismiss();
}
The first thing you can do is put Progress bar code after OnCreate method. But the best thing is to create a simple method for Progress bar and only call it in OnCreate method.
The following code worked fine for me:
private void showDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Have a nice time");
progressDialog.setMessage("Please wait while showing Titles :) ");
progressDialog.setCancelable(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
And then call this method in OnCreate
showDialog();
You can stop Progress when the data is ready to view using:
progressDialog.dismiss();
I hope this is helpful.

Resources