Adding button(Imageview) to viewpager within sliding image activity - android-layout

I am relatively new to Android development, my background being more php, html5 and the likes. I've studied, continue to take tutorials and am working on my first application which I've practically got the way I want it to be, save one particular item. I hope that you can help me, and to some, it is likely a simple response. But, I've tried and tried and cannot get things to work out without errors.
Basically, the application uses ViewPager, and has SlidingImageActivity as a class, so when images are loaded in full size (clicked from thumbnail) the images can be swiped from screen to screen.
I have action bar items, which rather than show in the overflow bar, I've created Image Button and placed in the xml below for the viewpager. It is the file - fullimageslider.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/grid_back_color"
tools:ignore="RtlHardcoded" >
<android.support.v4.view.ViewPager
android:id="#+id/image_slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/menu_zoom"
android:background="#color/grid_back_color" >
</android.support.v4.view.ViewPager>
<ImageButton
android:id="#+id/menu_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/save"
android:title="#string/menu_save" />
<ImageButton
android:id="#+id/menu_setaswallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/set"
android:title="#string/menu_setaswallpaper" />
<ImageButton
android:id="#+id/menu_zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="43dp"
android:layout_toRightOf="#+id/menu_share"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/zoom"
android:title="#string/menu_zoom" />
<ImageButton
android:id="#+id/menu_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#+id/menu_setaswallpaper"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/share"
android:title="#string/menu_share" />
</RelativeLayout>
I've added the buttons as you can see, below the viewpager. So that they remain on the bottom of the layout as the screen swipes.
My problem is, getting the buttons to function in the SlideImageActivity class. I'm not sure where to change the overflow menu tasks to the button tasks. I have removed the items I've created buttons for from the menu. And changed them into the above.
The following is the current SlideImageActivity class.
public class SlideImageActivity extends SherlockActivity
implements sensorEventListener {
int position;
String[] mAllImages,mAllImageCatName;
public DatabaseHandler db;
ImageView vp_imageview;
ViewPager viewpager;
int TOTAL_IMAGE;
private SensorManager sensorManager;
private boolean checkImage = false;
private long lastUpdate;
Handler handler;
Runnable Update;
boolean Play_Flag=false;
private Menu menu;
private DatabaseManager dbManager;
String Image_catName,Image_Url;
Bitmap bgr;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fullimageslider);
db = new DatabaseHandler(this);
dbManager = DatabaseManager.INSTANCE;
dbManager.init(getApplicationContext());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.resetViewBeforeLoading(true)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
setTitle(Constant.CATEGORY_TITLE);
// Look up the AdView as a resource and load a request.
Intent i=getIntent();
position=i.getIntExtra("POSITION_ID", 0);
mAllImages=i.getStringArrayExtra("IMAGE_ARRAY");
mAllImageCatName=i.getStringArrayExtra("IMAGE_CATNAME");
TOTAL_IMAGE=mAllImages.length-1;
viewpager=(ViewPager)findViewById(R.id.image_slider);
handler=new Handler();
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(position);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
viewpager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
position=viewpager.getCurrentItem();
Image_Url=mAllImages[position];
List<Pojo> pojolist=db.getFavRow(Image_Url);
if(pojolist.size()==0)
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_Url))
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int position) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int position) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.photo_menu, menu);
this.menu = menu;
//for when 1st item of view pager is favorite mode
FirstFav();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case android.R.id.home:
onBackPressed();
return true;
case R.id.menu_back:
position=viewpager.getCurrentItem();
position--;
if (position < 0) {
position = 0;
}
viewpager.setCurrentItem(position);
return true;
case R.id.menu_next:
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
}
viewpager.setCurrentItem(position);
return true;
case R.id.menu_play:
if(Play_Flag)
{
handler.removeCallbacks(Update);
menuItem.setIcon(getResources().getDrawable(R.drawable.play));
Play_Flag=false;
ShowMenu();
}
else
{
/*
* when Play_Flag false then Play
* but when image is last not start auto play
* now hide all menu when auto play start
*/
if(viewpager.getCurrentItem()==TOTAL_IMAGE)
{
Toast.LENGTH_SHORT).show();
}
else
{
AutoPlay();
menuItem.setIcon(getResources().getDrawable(R.drawable.stop));
Play_Flag=true;
HideMenu();
}
}
return true;
case R.id.menu_fav:
position=viewpager.getCurrentItem();
Image_Url=mAllImages[position];
List<Pojo> pojolist=db.getFavRow(Image_Url);
if(pojolist.size()==0)
{
AddtoFav(position);//if size is zero i.e means that record not in database show
add to favorite
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_Url))
{
RemoveFav(position);
}
}
return true;
case R.id.menu_overflow:
//just override click
return true;
case R.id.menu_share:
position=viewpager.getCurrentItem();
(new ShareTask(SlideImageActivity.this)).execute
(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY+mAllImageCatName[position]
+"/"+mAllImages[position]);
return true;
case R.id.menu_save:
position=viewpager.getCurrentItem();
(new SaveTask(SlideImageActivity.this)).execute
(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY+mAllImageCatName[position]
+"/"+mAllImages[position]);
return true;
case R.id.menu_setaswallaper:
position=viewpager.getCurrentItem();
Intent intwall=new intent(getApplicationContext(), SetAsWallpaperActivity.class);
intwall.putExtra("WALLPAPER_IMAGE_URL", mAllImages);
intwall.putExtra("WALLPAPER_IMAGE_CATEGORY", mAllImageCatName);
intwall.putExtra("POSITION_ID", position);
startActivity(intwall);
return true;
case R.id.menu_zoom:
position=viewpager.getCurrentItem();
Intent intzoom=new Intent(getApplicationContext(),PinchZoom.class);
intzoom.putExtra("ZOOM_IMAGE_URL", mAllImages);
intzoom.putExtra("ZOOM_IMAGE_CATEGORY", mAllImageCatName);
intzoom.putExtra("POSITION_ID", position);
startActivity(intzoom);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
//add to favorite
public void AddtoFav(int position)
{
Image_catName=mAllImageCatName[position];
Image_Url=mAllImages[position];
db.AddtoFavorite(new Pojo(Image_catName, Image_Url));
Toast.makeText(getApplicationContext(),
"Added to Favorite", Toast.LENGTH_SHORT).show();
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
//remove from favorite
public void RemoveFav(int position)
{
Image_Url=mAllImages[position];
db.RemoveFav(new Pojo(Image_Url));
Toast.makeText(getApplicationContext(), "Removed from
Favorite",Toast.LENGTH_SHORT).show();
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
//auto play slide show
public void AutoPlay()
{
Update=new Runnable() {
#Override
public void run() {
AutoPlay();
// TODO Auto-generated method stub
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
handler.removeCallbacks(Update);//when last image play mode goes to Stop
Toast.makeText(getApplicationContext(), "Last Image Auto Play Stoped",
Toast.LENGTH_SHORT).show();
menu.getItem(1).setIcon(getResources().getDrawable(R.drawable.play));
Play_Flag=false;
//Show All Menu when Auto Play Stop
ShowMenu();
}
viewpager.setCurrentItem(position);
}
};
handler.postDelayed(Update, 1500);
}
public void ShowMenu()
{
menu.getItem(0).setVisible(true);
menu.getItem(2).setVisible(true);
menu.getItem(3).setVisible(true);
menu.getItem(4).setVisible(true);
}
public void HideMenu()
{
menu.getItem(0).setVisible(false);
menu.getItem(2).setVisible(false);
menu.getItem(3).setVisible(false);
menu.getItem(4).setVisible(false);
}
public void FirstFav()
{
int first=viewpager.getCurrentItem();
String Image_id=mAllImages[first];
List<Pojo> pojolist=db.getFavRow(Image_id);
if(pojolist.size()==0)
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_id))
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = getLayoutInflater();
}
#Override
public int getCount() {
return mAllImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_item, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner =(ProgressBar)imageLayout.findViewById(R.id.loading);
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault
(getApplicationContext()));
ImageLoader.getInstance().displayImage(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY
+mAllImageCatName[position]+"/"+mAllImages[position], imageView, options, new
SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason
failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(SlideImageActivity.this, message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
// Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
// .show();
if (checkImage) {
position=viewpager.getCurrentItem();
viewpager.setCurrentItem(position);
} else {
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
}
viewpager.setCurrentItem(position);
}
checkImage = !checkImage;
}
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
if(dbManager == null){
dbManager = DatabaseManager.INSTANCE;
dbManager.init(getApplicationContext());
}else if(dbManager.isDatabaseClosed()){
dbManager.init(getApplicationContext());
}
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// unregister listener
super.onPause();
if(!dbManager.isDatabaseClosed())
dbManager.closeDatabase();
sensorManager.unregisterListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(Update);
sensorManager.unregisterListener(this);
if(dbManager != null)dbManager.closeDatabase();
}
public class SaveTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public SaveTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection)
myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/EC Images/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Toast.makeText(SlideImageActivity.this, "Image Saved Succesfully /",
Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
public class ShareTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public ShareTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please Wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/HD Wallpaper/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
startActivity(Intent.createChooser(share, "Share Image"));
pDialog.dismiss();
}
}
}
As you can see the code implements the menu items, Share, Set as Wallpaper, Save and Zoom. These are the Imagebuttons I -want- to use and have set up on the above xml layout.
This is what I have for the buttons. But I have no idea where or how to add this, implement it into the ImageSliderActivity class.
Button clickButton = (Button) findViewById(R.id.menu_share);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position=viewpager.getCurrentItem();
(new shareTask(SlideImageActivity.this)).execute(Constant.
SERVER_IMAGE_UPFOLDER_CATEGORY+
mAllImageCatName[position]+"/"+mAllImages[position]);
return true;
Button clickButton = (Button) findViewById(R.id.menu_save);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {position=viewpager.getCurrentItem();
newSaveTask(SlideImageActivity.this)).execute(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY
+mAllImageCatName[position]+"/"+mAllImages[position]);
return true;
Button clickButton = (Button) findViewById(R.id.menu_setaswallpaper);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {position=viewpager.getCurrentItem();
Intent intwall=new Intent(getApplicationContext(),SetAsWallpaperActivity.class);
intwall.putExtra("WALLPAPER_IMAGE_URL", mAllImages);
intwall.putExtra("WALLPAPER_IMAGE_CATEGORY", mAllImageCatName);
intwall.putExtra("POSITION_ID", position);
startActivity(intwall);
return true;
Button clickButton = (Button) findViewById(R.id.menu_zoom);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position=viewpager.getCurrentItem();
Intent intzoom=new Intent(getApplicationContext(),PinchZoom.class);
intzoom.putExtra("ZOOM_IMAGE_URL", mAllImages);
intzoom.putExtra("ZOOM_IMAGE_CATEGORY", mAllImageCatName);
intzoom.putExtra("POSITION_ID", position);
startActivity(intzoom);
return true;`
I hope I've made sense.If some one could please guide me in the right direction, I would greatly appreciate the help. Basically, I want to remove the overflow menu during the slidingimage activity, and use buttons at the bottom of the layout instead to implement those items. The layout works in the emulator and causes no error, but obviously when the buttons are clicked, nothing happens because I don't know where to add the button portion to the sliding activity class, without causing multiple errors.
Thanks so much for your time in advance!

Related

Change ImageView after choosing photo from Gallery

I am trying to change my imageview when its on click and then choose image from gallery then change it. But I don't think its working since when I tried running my project, it just crashes out of the app.
Navigation Drawer
ActivityResult
ActivityResultLauncher<String> mGetContent = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
});
ImageView
profileImage = (ImageView) findViewById(R.id.profilepic);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
p.s. The ImageView is inside my navigation drawer. what I wanted to do is that whenever I click or press the ImageView which is the Hamburger Icon, it will redirect to gallery to choose image and then change it once the user chose one.
MapsActivity.java
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private static final String TAG = "";
private DrawerLayout drawer;
LatLng carWash1 = new LatLng(6.106535, 125.187230);
LatLng carWash2 = new LatLng(6.106123, 125.189280);
private ArrayList<LatLng> locationArrayList;
private ImageView profileImage;
final static int Gallery_Pick = 1;
private GoogleMap mMap;
private ActivityMapsBinding binding;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location recentLocation;
private Marker currentMark;
private static final int Request_User_Location = 1234;
private List<Polyline> polylines = null;
protected LatLng start = null;
protected LatLng end = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
locationArrayList = new ArrayList<>();
locationArrayList.add(carWash1);
locationArrayList.add(carWash2);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
super.onBackPressed();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Request_User_Location:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
for (int i = 0; i < locationArrayList.size(); i++) {
mMap.addMarker(new MarkerOptions().position(locationArrayList.get(0)).title("Purok 5 Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));
mMap.addMarker(new MarkerOptions().position(locationArrayList.get(1)).title("Stratford Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(locationArrayList.get(i), 15));
mMap.moveCamera(CameraUpdateFactory.newLatLng(locationArrayList.get(i)));
}
boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
.getString(R.string.style_json)));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
}
private BitmapDescriptor BitMapFromVector(Context context, int vectorResId) {
// below line is use to generate a drawable.
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
// below line is use to set bounds to our vector drawable.
vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
// below line is use to create a bitmap for our
// drawable which we have added.
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
// below line is use to add bitmap in our canvas.
Canvas canvas = new Canvas(bitmap);
// below line is use to draw our
// vector drawable in canvas.
vectorDrawable.draw(canvas);
// after generating our bitmap we are returning our bitmap.
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(#NonNull Location location) {
recentLocation = location;
if (currentMark != null) {
currentMark.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
currentMark = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(12));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

How to save the content of custom array class and adapter in list view save into text in android

I need your help I am new in android programming. How can I save all the content in the list view save into text file this is my code of try to save the file but the problem is how can i put the listview array list to get the data i don't know how to put it where to put it please help how to do it to save the content of my listview
Button code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
for (int i = 0; i < ChatBubbles.length; i++) {
myOutWriter.append(ChatBubbles[i] +"\n");
}
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Chatbubble class:
package com.example.ezminute;
public class ChatBubble {
private String content;
private boolean myMessage;
public ChatBubble(String content, boolean myMessage) {
this.content = content;
this.myMessage = myMessage;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
}
MessageAdapter:
package com.example.ezminute;
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.left_chat_bubble;
} else {
layoutResource = R.layout.right_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime. Value 2 is returned because of left and right views.
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
}
}
}

Android Contextual Action Bar not appearing after item selection

In my android application, I am trying to show contextual action bar (CAB) in listview for item delete. The problem is that whenever an item is pressed for long, the item gets selected, but CAB doesn't appear. I have verified with so many tutorials, can't figure out what am I missing. Any help would be appreciated.
Adapter Class
public class DuasListAdapter extends ArrayAdapter<String>{
// class variables
private final Context context;// to save context
private final List<String> duas;// to save list of stores
LayoutInflater inflater;//
private SparseBooleanArray selectedItemsIds;
public DuasListAdapter(Context ctx,int resourceId, List<String> duasList) {
super(ctx, resourceId, duasList);
selectedItemsIds = new SparseBooleanArray();
context = ctx;// save context
duas = duasList;// save list of stores
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);// save inflater layout
}
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.adapter_list_duas, null);
convertView.setTag(holder);
holder.duaIndex = position;
holder.background = (LinearLayout) convertView.findViewById(R.id.ll_duas_list);
holder.iv_duatype = (ImageView) convertView.findViewById(R.id.iv_duatype);
holder.tv_dua_arabic = (TextView) convertView.findViewById(R.id.tv_dua_arabic);
holder.tv_dua_no = (TextView) convertView.findViewById(R.id.dua_no);
}
else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
static class ViewHolder {
int duaIndex;
LinearLayout background;// background to display color for read and unread messages
ImageView iv_duatype;
TextView tv_dua_arabic;// title of message
TextView tv_dua_ref;// message by and message created on
TextView tv_dua_no;
/**
* #description constructor to save context and list of stores views
* #param v to refer the view
* #return
*/
}
public void remove(List<String> object){
duas.remove(object);
notifyDataSetChanged();
}
public List<String> getDuas(){
return duas;
}
public void toggleSelection(int position) {
selectView(position, !selectedItemsIds.get(position));
}
public void removeSelection() {
selectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
selectedItemsIds.put(position, value);
else
selectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return selectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return selectedItemsIds;
}
}
Fragment Class
Context context;
LinearLayout ll_back_duas_list_header;
TextView ll_back_duas_list_header_title;
ListView lvDuaas;
public static DuasListAdapter duasAdapter;
ActionMode mAction;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = inflater.getContext();
View view = inflater.inflate(R.layout.fragment_list_duas, container, false);
ll_back_duas_list_header = (LinearLayout) view.findViewById(R.id.ll_back_duas_list_header);
ll_back_duas_list_header_title = (TextView) view.findViewById(R.id.ll_back_duas_list_header_title);
lvDuaas = (ListView) view.findViewById(R.id.lv_duas);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
final ArrayList<String> duas = new ArrayList<String>();
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].length() > 0)
duas.add(versesList[i]);
}
duasAdapter = new DuasListAdapter(context,R.layout.adapter_list_duas,duas);
lvDuaas.setAdapter(duasAdapter);
lvDuaas.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
lvDuaas.setChoiceMode(lvDuaas.CHOICE_MODE_MULTIPLE);
lvDuaas.setItemChecked(position, true);
mAction = getActivity().startActionMode(modeCallBack);
view.setSelected(true);
return true;
}
});
super.onActivityCreated(savedInstanceState);
}
ActionMode.Callback modeCallBack = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
mode.getMenuInflater().inflate(R.menu.activity_main, menu);
return false;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = duasAdapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
String selecteditem = duasAdapter.getItem(selected.keyAt(i));
// Remove selected items following the ids
duasAdapter.remove(selecteditem);
}
}
// Close CAB
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
duasAdapter.removeSelection();
}
};
}
XML file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:id="#+id/delete"
android:title="#string/delete"
/>
</menu>
From looking at your code I can see the onCreateActionMode callback function returns false.
onCreateActionMode should return true if the action mode should be created, false if entering this mode should be aborted.
So when the user long clicks on the ListItem and the event is triggered it reaches onCreateActionMode and returns false. Telling it to abort. Hence no CAB menu appears. Try changing it to true and also adding in some logs to see if it ever makes it into the callback function.
This would be the change below:
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
Log.d("Test","In onCreateActionMode");
mode.getMenuInflater().inflate(R.menu.activity_main, menu);
return true;//code updated here
}
Android Link to reference : http://developer.android.com/reference/android/view/ActionMode.Callback.html#onCreateActionMode(android.view.ActionMode, android.view.Menu)

how to set a onclicklistener for button inside the listview in android?

I have a listView having a button and a textView. How can I set onclicklistener for the button inside the listView?
Code Given below:
ListView.xml:
ListView lv1 = (ListView)popupView.findViewById(R.id.listView1);
listviewAdapter adapter = new listviewAdapter(Order_page.this, alist);
lv1.setAdapter(adapter);
ListviewAdapter Class is as follows:
public class listviewAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
public listviewAdapter(Activity activity,
ArrayList<HashMap<String, String>> list) {
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
Button btn_fav, btn_plus, btn_minus;
TextView item_name;
TextView item_price;
TextView item_total;
EditText et_quantity;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.order_list_texts, null);
holder = new ViewHolder();
holder.btn_fav = (Button) convertView.findViewById(R.id.fav_btn_orderlist);
holder.btn_plus = (Button) convertView.findViewById(R.id.order_pg_plus);
holder.btn_minus = (Button) convertView.findViewById(R.id.order_pg_minus);
holder.item_name = (TextView) convertView.findViewById(R.id.item_name);
holder.item_price = (TextView) convertView.findViewById(R.id.itm_price);
holder.item_total = (TextView) convertView.findViewById(R.id.Item_total);
holder.et_quantity = (EditText) convertView.findViewById(R.id.et_quantity_order_list);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.item_name.setText(map.get(ITEM_NAME_COLUMN));
holder.item_price.setText(map.get(ITEM_PRICE_COLUMN));
holder.item_total.setText(map.get(TOTAL_COLUMN));
holder.et_quantity.setText(map.get(ITEM_QUANTITY_COLUMN));
return convertView;
}
}
Please help to set onClick event of the button
You just have to add a listener with myButton.setOnClickListener(mBuyButtonClickListener)
This will be done in getView() of you ListView
you can know position of the button by using myListView.getPositionForView(myButton)
Below solution can help you:
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = getListView().getPositionForView(v);
if (position != ListView.INVALID_POSITION) {
//DO THE STUFF YOU WANT TO DO WITH THE position
}
}
};
For further help you can go to this article .. Hope answer helps you..
completed code am listed below its too simple.
public class listviewAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
public listviewAdapter(Activity activity,
ArrayList<HashMap<String, String>> list) {
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
Button btn_fav, btn_plus, btn_minus, btn_delete;
TextView item_name;
TextView item_price;
TextView item_total;
EditText et_quantity;
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.order_list_texts, null);
holder = new ViewHolder();
holder.btn_fav = (Button) convertView.findViewById(R.id.fav_btn_orderlist);
holder.btn_plus = (Button) convertView.findViewById(R.id.orderlist_plus);
holder.btn_minus = (Button) convertView.findViewById(R.id.orderlist_minus);
holder.item_name = (TextView) convertView.findViewById(R.id.item_name);
holder.item_price = (TextView) convertView.findViewById(R.id.itm_price);
holder.item_total = (TextView) convertView.findViewById(R.id.Item_total);
holder.et_quantity = (EditText) convertView.findViewById(R.id.et_quantity_order_list);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_order_list_delete);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
final HashMap<String, String> map = list.get(position);
holder.item_name.setText(map.get(ITEM_NAME_COLUMN));
holder.item_price.setText(map.get(ITEM_PRICE_COLUMN));
holder.item_total.setText(map.get(TOTAL_COLUMN));
holder.et_quantity.setText(map.get(ITEM_QUANTITY_COLUMN));
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list.remove(position);
notifyDataSetChanged();
//Log.v("sd", "" + alist);
}
});
holder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//to get a specific item
Toast.makeText(activity,"" + holder.item_name.getText().toString(),Toast.LENGTH_LONG).show();
}
});
/*
* holder.et_quantity.addTextChangedListener(new TextWatcher() {
*
* #Override public void onTextChanged(CharSequence arg0, int arg1, int
* arg2, int arg3) { // TODO Auto-generated method stub
*
* }
*
* #Override public void beforeTextChanged(CharSequence arg0, int arg1,
* int arg2, int arg3) { // TODO Auto-generated method stub
*
* }
*
* #Override public void afterTextChanged(Editable arg0) { // TODO
* Auto-generated method stub Toast.makeText(activity,
* ""+getItem(position), 1000).show(); } });
*/
return convertView;
}
}

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.

Resources