Android setAdapter not working extend fragment - android-layout

I have an issue while working with a tab1 class extend fragment called from a fragment list. I have done research and information on the use of fragment within a class but right now I cannot get my setAdapter to work in the tab1 class. Below are my codes: the tab1 class and the XML.
public class Tab1Fragment extends Fragment implements AdapterView.OnItemClickListener {
private static final int ADD_NEW_FRIEND_ID = Menu.FIRST;
private static final int SHOW_DETAILS = 3;
private static final int EXIT_APP_ID = Menu.FIRST + 1;
public IAppManager imService = null;
private FriendListAdapter friendAdapter;
private class FriendListAdapter extends BaseAdapter
{
class ViewHolder {
TextView text;
ImageView icon;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private ListView list;
private ListView listView;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friends = friends;
}
public int getCount() {
return friends.length;
}
public FriendInfo getItem(int position) {
return friends[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.friend_list_screen, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(friends[position].userName);
holder.icon.setImageBitmap(friends[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null)
{
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED))
{
Tab1Fragment.this.updateData(FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo(); //imService.getLastRawFriendList();
if (friends != null) {
Tab1Fragment.this.updateData(friends, null); // parseFriendInfo(friendList);
}
getActivity().setTitle(imService.getUsername() + "'s friend list");
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
}
};
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab1fragment, container, false);
ListView list = (ListView) v.findViewById(R.id.lvn);
return v;
}
void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends)
{
if (friends != null) {
friendAdapter.setFriendList(friends);
setAdapter(friendAdapter);
}
if (unApprovedFriends != null)
{
NotificationManager NM = (NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0)
{
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
Notification notification = new Notification(R.drawable.stat_sample,
getText(R.string.new_friend_request_exist),
System.currentTimeMillis());
Intent i = new Intent(Tab1Fragment.this.getActivity(), UnApprovedFriendList.class);
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
PendingIntent contentIntent = PendingIntent.getActivity(this.getActivity(), 0,
i, 0);
notification.setLatestEventInfo(this.getActivity(), getText(R.string.new_friend_request_exist),
"You have new friend request(s)",
contentIntent);
NM.notify(R.string.new_friend_request_exist, notification);
}
else
{
// if any request exists, then cancel it
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
onItemClick(parent, v, position, id);
// Sensor sensor = sensorAdapter.getItem(AdapterView<?> parent
Intent i = new Intent(Tab1Fragment.this.getActivity(), Messaging.class);
FriendInfo friend = friendAdapter.getItem(position);
if (friend.status == STATUS.ONLINE)
{
i.putExtra(FriendInfo.USERNAME, friend.userName);
// i.putExtra(FriendInfo.ID, friend.uid); // Edit //
i.putExtra(FriendInfo.PORT, friend.port);
i.putExtra(FriendInfo.IP, friend.ip);
startActivity(i);
}
else
{
Toast.makeText(Tab1Fragment.this.getActivity(), R.string.user_offline, Toast.LENGTH_SHORT).show();
}
}
}
The XML for the tab:
<?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:orientation="vertical" >
<ListView
android:id="#+id/lvn"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/no_friend"
android:gravity="center_vertical|center_horizontal"/>
</LinearLayout>

Related

Item List not Clickable

Item list instantiates but the items but click event (toast) doesnt occur when clicked.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
Toolbar toolbar;
FragmentTransaction fragmentTransaction;
FragmentManager fragmentManager;
Fragment fragment;
FrameLayout frameLayout;
ListView listView;
String[] workoutsRoutines = {"Upper Body", "Lower body"};
int[] workoutsBackgrounds = {R.drawable.ic_launcher_background, R.drawable.ic_launcher_foreground};
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(this);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(null);
toolbar.setNavigationIcon(R.drawable.ic_android_black_24dp);
item list click event
listView = findViewById(R.id.listview);
CustomAdapter customAdapter = new CustomAdapter();
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Toast.makeText(MainActivity.this, "succ", Toast.LENGTH_SHORT).show();
}
});
toolbar.setNavigationOnClickListener(v -> {
drawerLayout.openDrawer(GravityCompat.START);
Toast.makeText(MainActivity.this, "succ", Toast.LENGTH_SHORT).show();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
if (fragment != null) {
count = fragmentManager.getBackStackEntryCount();
for (int i = 0; i < count; i++) {
fragmentManager.popBackStack();
drawerLayout.closeDrawer(GravityCompat.START);
}
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction().remove(fragment);
fragmentTransaction.commit();
}
toolbar.setNavigationIcon(R.drawable.ic_android_black_24dp);
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else super.onBackPressed();
count = fragmentManager.getBackStackEntryCount();
for (int i = 0; i < count; i++) {
fragmentManager.popBackStack();
}
toolbar.setNavigationIcon(R.drawable.ic_android_black_24dp);
}
private class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return workoutsBackgrounds.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View view1 = getLayoutInflater().inflate(R.layout.rowdata, null);
TextView name = view1.findViewById((R.id.workouts));
ImageView image = view1.findViewById((R.id.background));
name.setText(workoutsRoutines[i]);
image.setImageResource(workoutsBackgrounds[i]);
return view1;
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_profile:
fragment = new profileFragment();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).addToBackStack(null);
fragmentTransaction.commit();
toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_ios_24);
break;
case R.id.nav_custom_workouts:
fragment = new customWorkoutFragment();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.frameLayout, new customWorkoutFragment()).addToBackStack(null);
fragmentTransaction.commit();
toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_ios_24);
break;
}
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
needed to bring itemlist view to front

PlaceAutoCompleteTextView in map

I have been trying to add a prediction list of places in my 2 AutoCompleteTextView and I also achieved it in my project but now my DashboardActivity is giving error in setting the adapter. The type of error casting error when setting an adapter
activity_dashboard.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/map_marker"
/>
<RelativeLayout
android:id="#+id/pickupRL"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_height="50dp"
android:layout_marginTop="5pt"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:elevation="4pt"
android:background="#drawable/white_border" >
<ImageView
android:id="#+id/pickupIV"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginRight="3pt"
android:layout_centerVertical="true"
android:layout_marginLeft="5pt"
android:src="#drawable/ic_search"
app:tint="#color/colorPrimaryDark"/>
<AutoCompleteTextView
android:id="#+id/pickupATV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/pickupIV"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#color/colorBlack"
android:background="#null"
android:hint="Search location"
android:singleLine="true"
android:imeOptions="actionSearch"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/dropoffRL"
android:layout_marginTop="5pt"
android:layout_below="#id/pickupRL"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:elevation="4pt"
android:background="#drawable/white_border" >
<ImageView
android:id="#+id/dropoffIV"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginRight="3pt"
android:layout_centerVertical="true"
android:layout_marginLeft="5pt"
android:src="#drawable/ic_search"
app:tint="#color/colorPrimaryDark"/>
<AutoCompleteTextView
android:id="#+id/dropoffATV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/dropoffIV"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#color/colorBlack"
android:background="#null"
android:hint="Search location"
android:singleLine="true"
android:imeOptions="actionSearch"/>
</RelativeLayout>
<Button
android:id="#+id/btnconfirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="30dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:padding="20dp"
android:text="Comfirm" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/currentLocationFAB"
android:backgroundTint="#color/colorWhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/btnconfirm"
android:layout_alignParentRight="true"
android:layout_marginBottom="5pt"
android:layout_marginRight="10pt"
android:elevation="4pt"
app:fabSize="mini"
app:borderWidth="0dp"
app:elevation="4pt"
app:backgroundTint="#color/colorWhite"
android:src="#drawable/ic_current_location"
android:tint="#color/colorPrimaryDark"/>
</RelativeLayout>
DashboardActivity.java
public class DashboardActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private Activity activity;
private GoogleMap mMap;
private static final String Tag = "MAP_ACTIVITY";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136));
private Boolean mLocationPermissionsGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
private final ThreadLocal<PlaceAutocompleteAdapter> mplaceAutoCompeleteAdapter = new ThreadLocal<>();
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
private AutoCompleteTextView pickupATV, dropoffATV;
private Button btnconfirm;
private FloatingActionButton currentLocationFAB;
private Toolbar toolbar;
private MenuItem previousItem;
private UtilityModel utilityModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
bindControls();
bindListeners();
getLocationPermission();
setMap();
}
private void getLocationPermission() {
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
setMap();
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
private void bindControls() {
activity = DashboardActivity.this;
utilityModel = new UtilityModel(activity);
toolbar = findViewById(R.id.toolbar);
btnconfirm = findViewById(R.id.btnconfirm);
pickupATV = findViewById(R.id.pickupATV);
dropoffATV = findViewById(R.id.dropoffATV);
currentLocationFAB = findViewById(R.id.currentLocationFAB);
}
private void bindListeners() {
btnconfirm.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(com.google.android.gms.location.places.Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mplaceAutoCompeleteAdapter.set(new PlaceAutocompleteAdapter(activity, mGoogleApiClient, LAT_LNG_BOUNDS, null));
pickupATV.setOnItemClickListener(mAutocompleteClickListener);
pickupATV.setAdapter(mplaceAutoCompeleteAdapter); // This adapter is causing the trouble
pickupATV.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
//execute our method for searching
geoLocate(pickupATV);
}
return false;
}
});
dropoffATV.setOnItemClickListener(mAutocompleteClickListener);
mplaceAutoCompeleteAdapter.set(new PlaceAutocompleteAdapter(activity, mGoogleApiClient, LAT_LNG_BOUNDS, null));
dropoffATV.setAdapter(mplaceAutoCompeleteAdapter); // This adapter is causing the trouble
dropoffATV.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
//execute our method for searching
geoLocate(dropoffATV);
}
return false;
}
});
currentLocationFAB.setOnClickListener(this);
utilityModel.hideSoftKeyboard();
}
private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
utilityModel.hideSoftKeyboard();
final AutocompletePrediction item = mplaceAutoCompeleteAdapter.get().getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
#SuppressLint("RestrictedApi")
#Override
public void onResult(#NonNull PlaceBuffer places) {
if(!places.getStatus().isSuccess()){
Log.d(Tag, "onResult: Place query did not complete successfully: " + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(Tag, "onResult: name: " + place.getName());
mPlace.setAddress(place.getAddress().toString());
Log.d(Tag, "onResult: address: " + place.getAddress());
mPlace.setAttributions(place.getAttributions().toString());
// Log.d(TAG, "onResult: attributions: " + place.getAttributions());
mPlace.setId(place.getId());
Log.d(Tag, "onResult: id:" + place.getId());
mPlace.setLatlng(place.getLatLng());
Log.d(Tag, "onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(Tag, "onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(Tag, "onResult: ic_phone number: " + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(Tag, "onResult: website uri: " + place.getWebsiteUri());
Log.d(Tag, "onResult: place: " + mPlace.toString());
}catch (NullPointerException e){
Log.e(Tag, "onResult: NullPointerException: " + e.getMessage() );
}
setMarkerAndMoveCamera(new LatLng(place.getViewport().getCenter().latitude,
place.getViewport().getCenter().longitude), mPlace);
currentLocationFAB.setVisibility(View.VISIBLE);
places.release();
}
};
private void geoLocate(AutoCompleteTextView view) {
String searchString = view.getText().toString().trim();
Geocoder geocoder = new Geocoder(activity);
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchString, 1);
} catch (IOException e) {
Log.e(Tag, "geoLocate: IOException: " + e.getMessage());
}
if (list.size() > 0) {
Address address = list.get(0);
setMarkerAndMoveCamera(new LatLng(address.getLatitude(), address.getLongitude()), null);
}
}
private void setMap() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (mLocationPermissionsGranted) {
getCurrentLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#SuppressLint("RestrictedApi")
#Override
public void onCameraMove() {
currentLocationFAB.setVisibility(View.VISIBLE);
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#SuppressLint("RestrictedApi")
#Override
public void onMarkerDragEnd(Marker marker) {
setMarkerAndMoveCamera(marker.getPosition(), null);
currentLocationFAB.setVisibility(View.VISIBLE);
}
});
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onMapClick(LatLng latLng) {
setMarkerAndMoveCamera(latLng, null);
currentLocationFAB.setVisibility(View.VISIBLE);
}
});
}
}
private void getCurrentLocation() {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionsGranted) {
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(Tag, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
setMarkerAndMoveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),null);
} else {
Log.d(Tag, "onFailed: current location is null");
Toast.makeText(activity, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e(Tag, "getCurrentLocation: SecurityException: " + e.getMessage());
}
}
private void setMarkerAndMoveCamera(LatLng latLng, PlaceInfo placeInfo){
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM));
}
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
if (v == btnconfirm) {
// LatLng currentMarkerLocation = mMap.getCameraPosition().target;
} else if (v == currentLocationFAB) {
currentLocationFAB.setVisibility(View.INVISIBLE);
getCurrentLocation();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
PlaceInfo.java
public class PlaceInfo {
private String name;
private String address;
private String phoneNumber;
private String id;
private Uri websiteUri;
private LatLng latlng;
private float rating;
private String attributions;
public PlaceInfo(String name, String address, String phoneNumber, String id, Uri websiteUri,
LatLng latlng, float rating, String attributions) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.id = id;
this.websiteUri = websiteUri;
this.latlng = latlng;
this.rating = rating;
this.attributions = attributions;
}
public PlaceInfo() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Uri getWebsiteUri() {
return websiteUri;
}
public void setWebsiteUri(Uri websiteUri) {
this.websiteUri = websiteUri;
}
public LatLng getLatlng() {
return latlng;
}
public void setLatlng(LatLng latlng) {
this.latlng = latlng;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public String getAttributions() {
return attributions;
}
public void setAttributions(String attributions) {
this.attributions = attributions;
}
#Override
public String toString() {
return "PlaceInfo{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", id='" + id + '\'' +
", websiteUri=" + websiteUri +
", latlng=" + latlng +
", rating=" + rating +
", attributions='" + attributions + '\'' +
'}';
}
}
PlaceAutocompleteAdapter.java
public class PlaceAutocompleteAdapter
extends ArrayAdapter<AutocompletePrediction> implements Filterable {
private static final String TAG = "PlaceAutocompleteAd";
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
private ArrayList<AutocompletePrediction> mResultList;
private GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private AutocompleteFilter mPlaceFilter;
public PlaceAutocompleteAdapter(Context context, GoogleApiClient googleApiClient,
LatLngBounds bounds, AutocompleteFilter filter) {
super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
mGoogleApiClient = googleApiClient;
mBounds = bounds;
mPlaceFilter = filter;
}
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
#Override
public int getCount() {
return mResultList.size();
}
#Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
AutocompletePrediction item = getItem(position);
TextView textView1 = row.findViewById(android.R.id.text1);
TextView textView2 = row.findViewById(android.R.id.text2);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
textView2.setText(item.getSecondaryText(STYLE_BOLD));
return row;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<AutocompletePrediction> filterData = new ArrayList<>();
if (constraint != null) {
filterData = getAutocomplete(constraint);
}
results.values = filterData;
if (filterData != null) {
results.count = filterData.size();
} else {
results.count = 0;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
mResultList = (ArrayList<AutocompletePrediction>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
#Override
public CharSequence convertResultToString(Object resultValue) {
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i(TAG, "Starting autocomplete query for: " + constraint);
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
mBounds, mPlaceFilter);
AutocompletePredictionBuffer autocompletePredictions = results
.await(60, TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
return DataBufferUtils.freezeAndClose(autocompletePredictions);
}
Log.e(TAG, "Google API client is not connected for autocomplete query.");
return null;
}
}
My Error is located in DashboardActivity.java in bindListener method on pickupATV.setAdapter and dropoffATV.setAdapter
Build Error
Task :app:compileDebugJavaWithJavac FAILED
/Users/muhammadyousuf/StudioProjects/homemoversfyp/app/src/main/java/com/example/daniyal/fyp_project/activities/DashboardActivity.java:162:
error: method setAdapter in class AutoCompleteTextView cannot be
applied to given types;
pickupATV.setAdapter(mplaceAutoCompeleteAdapter); // This adapter is causing the trouble
^ required: T found: ThreadLocal reason: inferred type does not
conform to upper bound(s)
inferred: ThreadLocal
upper bound(s): ListAdapter,Filterable where T is a type-variable:
T extends ListAdapter,Filterable declared in method setAdapter(T)
/Users/muhammadyousuf/StudioProjects/homemoversfyp/app/src/main/java/com/example/daniyal/fyp_project/activities/DashboardActivity.java:181:
error: method setAdapter in class AutoCompleteTextView cannot be
applied to given types;
dropoffATV.setAdapter(mplaceAutoCompeleteAdapter); // This adapter is causing the trouble
^ required: T found: ThreadLocal reason: inferred type does not
conform to upper bound(s)
inferred: ThreadLocal
upper bound(s): ListAdapter,Filterable where T is a type-variable:
T extends ListAdapter,Filterable declared in method setAdapter(T) Note: Some input files use or override a deprecated
API. Note: Recompile with -Xlint:deprecation for details. Note:
/Users/muhammadyousuf/StudioProjects/homemoversfyp/app/src/main/java/com/example/daniyal/fyp_project/activities/DashboardActivity.java
uses unchecked or unsafe operations. Note: Recompile with
-Xlint:unchecked for details. 2 errors
FAILURE: Build failed with an exception.
What went wrong: Execution failed for task
':app:compileDebugJavaWithJavac'. Compilation failed; see the compiler
error output for details.
I solved it myself by using another approach that is the new one used in the docs by developers.google.com. I used the first approach to add as an autocomplete widget.
on my activity's onCreate i initialised Places instance.
Places.initialize(getApplicationContext(), getResources().getString(R.string.google_maps_key));
PlacesClient placesClient = Places.createClient(activity);
again on my onCreate i initialised and declared my pickupFragment and bind it with a listener.
pickupFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.pickupFragment);
pickupFragment.setCountry("PK");
pickupFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG));
pickupFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.e(TAG, "Place: " + place.getName() + ", " + place.getId() + ", " + place.getLatLng());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.e(TAG, "An error occurred: " + status);
}
});
and used this piece of code in my xml
<fragment
android:id="#+id/pickupFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment" />
I did this for both my pickupFragment and dropoffFragment.

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);
}
}
}

messed up dynamic radio buttons in ArrayAdapter

when i run my app, i get much more radiobuttons than i need. It seems the radiobuttons repeat themselves in the same group. I don't really understand what is is going on. Here is my custom ArrayAdapter. I would like to know the problem here
public class QuestionsListAdapter extends ArrayAdapter<QuestionProperties> {
List<QuestionProperties> list;
Context test;
public QuestionsListAdapter(Context context, int resource, List<QuestionProperties> list2) {
super(context,resource,list2);
test = context;
list =list2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
final RadioButton[] rB;
RadioHolder holder = new RadioHolder();
view= convertView;
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
if(view == null)
{
LayoutInflater inflator = ((Activity) test).getLayoutInflater();
view = inflator.inflate(R.layout.question_list_row, null);
holder.questionTV = (TextView) view.findViewById(R.id.qTextView);
holder.radiogroup = (RadioGroup) view.findViewById(R.id.radio_group);
view.setTag(holder);
}
else{
//view = convertView;
holder = (RadioHolder) view.getTag();
}
holder.questionTV.setText(String.valueOf(list.get(position).getQuestionNo())+"."+" " + list.get(position).getQuestion());
rB=new RadioButton[list.get(position).possibleAns.length];
for(int count = 0; count<(list.get(position).possibleAns.length);count++)
{
rB[count]= new RadioButton(test);
rB[count].setId(count);
rB[count].setText(list.get(position).possibleAns[count]);
layoutParams.weight=1.0f;
layoutParams.setMargins(15, 0, 5, 10);
rB[count].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String a = String.valueOf(v.getId());
Toast.makeText(QActivity.context, "Radio Button "+ a,Toast.LENGTH_SHORT).show();
}
});
holder.radiogroup.addView(rB[count],layoutParams);
}
return view;
}
static class RadioHolder {
protected TextView questionTV;
protected RadioGroup radiogroup;
}
Finally after some hacks i solved it! i removed all the radio buttons in the else clause.
The solution..
public class QuestionsListAdapter extends ArrayAdapter<QuestionProperties> {
List<QuestionProperties> list;
RadioButton rB;
Context test;
RadioHolder holder;
String chkBtn;
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
public QuestionsListAdapter(Context context, int resource, List<QuestionProperties> list2) {
super(context,resource,list2);
test = context;
list =list2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
holder = new RadioHolder();
view= convertView;
Log.v("ConvertView", String.valueOf(position));
if(view == null)
{
LayoutInflater inflator = ((Activity) test).getLayoutInflater();
view = inflator.inflate(R.layout.question_list_row, parent,false);
holder.questionTV = (TextView) view.findViewById(R.id.qTextView);
holder.radiogroup = (RadioGroup) view.findViewById(R.id.radio_group);
//holder.radiogroup.check(list.get(position).getSelectedAns());
view.setTag(holder);
//((RadioHolder) view.getTag()).radiogroup.setTag(list.get(position));
Log.v("holder setTag", String.valueOf(position));
}
else{
view = convertView;
holder = (RadioHolder)view.getTag();
//((RadioHolder)view.getTag()).radiogroup.getTag();
holder.radiogroup.removeAllViews();
}
holder.questionTV.setText(String.valueOf(list.get(position).getQuestionNo())+"."+" " + list.get(position).getQuestion());
configureRadioButtons(position);
chkBtn = String.valueOf(list.get(position).getSelectedAns());
holder.radiogroup.check(Integer.valueOf(chkBtn));
return view;
}
static class RadioHolder {
protected TextView questionTV;
protected RadioGroup radiogroup;
}
public void configureRadioButtons(int pos){
final int position = pos;
//rB=new RadioButton(test);
for(int count = 0; count<(list.get(position).possibleAns.length);count++)
{
rB= new RadioButton(test);
rB.setId(count);
rB.setText(list.get(position).possibleAns[count]);
layoutParams.weight=1.0f;
layoutParams.setMargins(15, 0, 5, 10);
holder.radiogroup.addView(rB,layoutParams);
rB.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String a = String.valueOf(v.getId());
list.get(position).setSelectedAns(v.getId());
chkBtn = String.valueOf(list.get(position).getSelectedAns());
Toast.makeText(QActivity.context, "Radio Button "+ a,Toast.LENGTH_SHORT).show();
}
});
rB.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
});
holder.radiogroup.clearCheck();
Log.v("rB added to radiogroup", String.valueOf(position));
}
}

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