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.
Related
I've started to program an app in Android Studio and I downloaded Moverio SDK and sample from here: https://tech.moverio.epson.com/en/bt-35e/developers_guide/developing_android_apps.html#ac2-3-2
I'm able to set the glasses resolution and all the other stuff described in the doc, in short:
using a SurfaceView I can see a video preview on the device that come from glasses camera.
What I need to do is to use the glasses camera in a WebView that load an html page with AR javascript lib.
I've tried in a easy way to make it with ionic and all works great except that I can't setup camera resolution..
this is my code, I hope someone can help me. Thank you
//SetupActivity.java
package io.ionic.starter;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.TextView;
import android.webkit.WebView;
import com.epson.moverio.hardware.camera.CameraDevice;
import com.epson.moverio.hardware.camera.CameraManager;
import com.epson.moverio.hardware.camera.CameraProperty;
import com.epson.moverio.hardware.camera.CaptureDataCallback;
import com.epson.moverio.hardware.camera.CaptureStateCallback;
import com.epson.moverio.util.PermissionHelper;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class SetupActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private final String TAG = this.getClass().getSimpleName();
private CameraManager mCameraManager = null;
private CameraDevice mCameraDevice = null;
private SurfaceView mSurfaceView = null;
private PermissionHelper mPermissionHelper = null;
private TextView mTextView_captureRate = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mPermissionHelper = new PermissionHelper(this);
mCameraManager = new CameraManager(this);
}
private CaptureStateCallback mCaptureStateCallback = null;
private CaptureDataCallback mCaptureDataCallback = null;
private TimerTask mTimerTask = new TimerTask(){
#Override
public void run() {
mHandler.post( new Runnable() {
public void run() {
if(null != mTextView_captureRate) mTextView_captureRate.setText(String.valueOf(mFps) + "[fps]");
else ;
}
});
}
};
private Timer mTimer = null;
private Handler mHandler = new Handler();
private float mFps = 0;
private final Handler handler = new Handler();
#Override
protected void onStart() {
super.onStart();
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
mTimer = new Timer(true);
mTimer.schedule( mTimerTask, 1000, 1000);
//mTextView_captureRate = (TextView) findViewById(R.id.textView_rate);
String launchUrl = "";
WebView Webv = null;
try {
mCaptureStateCallback = new CaptureStateCallback() {
#Override
public void onCaptureStarted() {
mCameraDevice.startPreview();
}
#Override
public void onCaptureStopped() {
}
#Override
public void onPreviewStarted() {
//setContentView(R.layout.activity_testo);
// Load and use views afterwards
}
#Override
public void onPreviewStopped() {
}
#Override
public void onRecordStarted() {
}
#Override
public void onRecordStopped() {
}
#Override
public void onPictureCompleted() {
}
};
mCameraDevice = mCameraManager.open(mCaptureStateCallback, null, mSurfaceView.getHolder());
CameraProperty property = mCameraDevice.getProperty();
property.setExposureMode(CameraProperty.EXPOSURE_MODE_MANUAL);
property.setExposureStep(5);
property.setCaptureSize(1920, 1080);
property.setCaptureFps(30);
mCameraDevice.setProperty(property);
//mCameraDevice.startCapture();
mCameraDevice.startCapture();
TextView sample = (TextView)findViewById(R.id.textView3);
if(null != mCameraDevice){
if(null != property){
String str = "";
str += "Size : " + property.getCaptureSize()[0] + "x" + property.getCaptureSize()[1] + " / " + property.getCaptureFps() + " [fps] ";
str += "Exposure : " + (property.getExposureMode().equals(CameraProperty.EXPOSURE_MODE_AUTO) ? property.getExposureMode() + "(" + property.getExposureStep() + ")" : property.getExposureStep()) + " ";
str += "Brightness : " + property.getBrightness() + " ";
str += "Sharpness : " + property.getSharpness() + " ";
//str += "Whitebalance : " + (property.getWhiteBalanceMode().equals(CameraProperty.WHITE_BALANCE_MODE_AUTO) ? property.getWhiteBalanceMode() + "(" + property.getWhiteBalanceTemperature() + ")" : property.getWhiteBalanceTemperature()) + "\n";
//str += "PowerLineFrequency : " + property.getPowerLineFrequencyControlMode() + "\n";
str += "CaptureDataFormat : " + property.getCaptureDataFormat() + "\n";
sample.setText(str);
}
else {
sample.setText("null");
}
}
//sample.setText("Hello");
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onRestart() {
super.onRestart();
if(null != mCameraDevice) {
mCameraDevice.stopCapture();
} else;
}
#Override
protected void onStop(){
super.onStop();
if(null != mCameraDevice) {
mCameraDevice.stopCapture();
} else ;
}
#Override
protected void onDestroy() {
super.onDestroy();
if(null != mCameraDevice) {
mCameraDevice.stopCapture();
mCameraManager.close(mCameraDevice);
} else;
mTimer.cancel();
mTimer = null;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
mPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
and this is the xml
<!---activity_setup.xml-->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SetupActivity">
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="965dp"
android:layout_height="541dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.161" />
<TextView
android:id="#+id/textView3"
android:layout_width="943dp"
android:layout_height="75dp"
android:text="Prova"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.157"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
I have an activity with tow tabs(with viewPager). inside viewPager is a fragment that have RecyclerView.
first tab is for (Monday-Friday) and second tab is for (Saturday-Sunday)
I want to retrieve data from database and show in recyclerview on each tab. but i cant update my recyclerView. Please help me to do that.And another problem is that when RecyclerView show data only show first row, but the number of rows in the table.like this:
10:06:00
10:06:00
10:06:00
10:06:00
10:06:00
10:06:00
here is my code:
this is my Fragment code:
public class toDastgheybFragment extends BaseFragment {
private List<DatabaseModel> Times = new ArrayList<DatabaseModel>();
DatabaseHelper databaseHelper;
private View mView;
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_to_dastgheyb, container,
false);
databaseHelper = new DatabaseHelper(getContext());
Times = databaseHelper.getAllUsers();
mRecyclerView = mView.findViewById(R.id.myRecycler);
mAdapter = new DataAdapter(Times);
mRecyclerView.setLayoutManager(new
LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(mAdapter);
return mView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<DatabaseModel> LineList = new ArrayList<>();
LineList.clear();
mAdapter = new DataAdapter(LineList);
DatabaseHelper db = new DatabaseHelper(getContext());
final List<DatabaseModel> m = db.getAllUsers();
if (m.size() > 0) {
for (int i = 0; i < m.size(); i++) {
LineList.add(m.get(i));
mAdapter.notifyDataSetChanged();
}
}
db.close();
}
}
and this is my DataHelper code:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MetroDB";//name of the
database
private static final String TABLE_NAME = "stationtime";//name for the
table
static String db_path = "/data/data/ir.shirazmetro/databases/";
private static final String Station = "station";
private static final String Time = "time";
private static final String Line = "line";
private final Context context;
private SQLiteDatabase database;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " +
TABLE_NAME + "(" + Station + " TEXT," + Time + " TEXT," + Line + " TEXT)";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
private boolean checkExist() {
SQLiteDatabase db = null;
try {
db = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
}
return db != null;
}
private void copyDatabase() throws IOException {
OutputStream myOutput = new FileOutputStream(db_path +
DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = context.getAssets().open(DATABASE_NAME +
".db");
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
public void importIfNotExist() throws IOException {
boolean dbExist = checkExist();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void open() {
database = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null,
SQLiteDatabase.OPEN_READWRITE);
}
public List<DatabaseModel> getAllUsers() {
List<DatabaseModel> contactList = new ArrayList<DatabaseModel>();
String whatStation = C.whatStation;
String whatLine = C.whatLine;
String selectQuery = "SELECT " + Time + " FROM " + TABLE_NAME + "
WHERE " + Station + " LIKE '%" + whatStation + "%' AND " + Line + " LIKE '%"
+ whatLine + "%'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
do {
DatabaseModel m = new DatabaseModel();
m.setTime(cursor.getString(cursor.getColumnIndex(Time)));
contactList.add(m);
} while (cursor.moveToNext());
}
return contactList;
}
}
and finally this is my activity code:
public class station extends BaseActivity {
Toolbar mToolbar;
private TabLayout tbLayout;
private ViewPager vPager;
RecyclerView.Adapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station);
final DatabaseHelper helper = new DatabaseHelper(this);
try {
helper.importIfNotExist();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
mToolbar = findViewById(R.id.tlbr1);
setSupportActionBar(mToolbar);
initView();
setupWithViewPager();
tbLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
public void line1(View view) {
Intent line1 = new Intent(this, line1.class);
startActivity(line1);
}
private void setupWithViewPager() {
BasePagerAdapter basePagerAdapter = new BasePagerAdapter(this,
getSupportFragmentManager());
vPager.setAdapter(basePagerAdapter);
tbLayout.setupWithViewPager(vPager);
}
private void initView() {
vPager = findViewById(R.id.view_pager);
tbLayout = findViewById(R.id.tab_layout);
backBtn = findViewById(R.id.backBtn);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backBtn:
line1(view);
return;
}
}
}
I want to refresh the getview() of baseadapter each time when user click on multispinner. Also wants to deselect all the selected checkbox.
Anybody please help.
Blockquote
Below is my multispinner java class
public class MultiSpinnerSearch extends Spinner implements OnCancelListener {
private static final String TAG = MultiSpinnerSearch.class.getSimpleName();
private List<KeyPairBoolData> items;
private String defaultText = "";
private String spinnerTitle = "";
private SpinnerListener listener;
private int limit = 0;
private int selected = 0;
private LimitExceedListener limitListener;
MyAdapter adapter;
public static AlertDialog.Builder builder;
public static AlertDialog ad;
public MultiSpinnerSearch(Context context) {
super(context);
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
TypedArray a = arg0.obtainStyledAttributes(arg1, R.styleable.MultiSpinnerSearch);
limit = a.getIndexCount();
for (int i = 0; i < limit; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.MultiSpinnerSearch_hintText) {
spinnerTitle = a.getString(attr);
defaultText = spinnerTitle;
break;
}
}
Log.i(TAG, "spinnerTitle: " + spinnerTitle);
a.recycle();
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
public void setLimit(int limit, LimitExceedListener listener) {
this.limit = limit;
this.limitListener = listener;
}
public List<KeyPairBoolData> getSelectedItems() {
List<KeyPairBoolData> selectedItems = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItems.add(item);
}
}
return selectedItems;
}
public List<Long> getSelectedIds() {
List<Long> selectedItemsIds = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItemsIds.add(item.getId());
}
}
return selectedItemsIds;
}
#Override
public void onCancel(DialogInterface dialog) {
// refresh text on spinner
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
String spinnerText = spinnerBuffer.toString();
if (spinnerText.length() > 2)
spinnerText = defaultText;
else
spinnerText = defaultText;
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{spinnerText});
setAdapter(adapterSpinner);
if (adapter != null)
adapter.notifyDataSetChanged();
listener.onItemsSelected(items);
}
#Override
public boolean performClick() {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.Material_App_Dialog));
builder.setTitle(spinnerTitle);
final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alert_dialog_listview_search, null);
builder.setView(view);
final ListView listView = (ListView) view.findViewById(R.id.alertSearchListView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setFastScrollEnabled(false);
adapter = new MyAdapter(getContext(), items);
listView.setAdapter(adapter);
final TextView emptyText = (TextView) view.findViewById(R.id.empty);
listView.setEmptyView(emptyText);
final EditText editText = (EditText) view.findViewById(R.id.alertSearchEditText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, " ITEMS : " + items.size());
dialog.cancel();
}
});
builder.setOnCancelListener(this);
ad = builder.show();
return true;
}
public void setItems(List<KeyPairBoolData> items, int position, SpinnerListener listener) {
this.items = items;
this.listener = listener;
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
if (spinnerBuffer.length() > 2)
defaultText = spinnerBuffer.toString().substring(0, spinnerBuffer.toString().length() - 2);
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{defaultText});
setAdapter(adapterSpinner);
if (position != -1) {
items.get(position).setSelected(true);
//listener.onItemsSelected(items);
onCancel(null);
}
}
public interface LimitExceedListener {
void onLimitListener(KeyPairBoolData data);
}
//Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<KeyPairBoolData> arrayList;
List<KeyPairBoolData> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<KeyPairBoolData> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView() enter");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_listview_multiple, parent, false);
holder.textView = (TextView) convertView.findViewById(R.id.alertTextView);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.alertCheckbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final int backgroundColor = (position % 2 == 0) ? R.color.list_background : R.color.list_background;
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), backgroundColor));
if (position==0)
{
holder.textView.setTextColor(Color.BLACK);
}
if (position==3)
{
holder.textView.setTextColor(Color.GREEN);
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.list_selected));
}
final KeyPairBoolData data = arrayList.get(position);
holder.textView.setText(data.getName());
holder.textView.setTypeface(null, Typeface.NORMAL);
holder.checkBox.setChecked(data.isSelected());
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (data.isSelected()) { // unselect
selected--;
} else if (selected == limit) { // select with limit
if (limitListener != null)
limitListener.onLimitListener(data);
return;
} else { // selected
selected++;
}
final ViewHolder temp = (ViewHolder) v.getTag();
temp.checkBox.setChecked(!temp.checkBox.isChecked());
data.setSelected(!data.isSelected());
Log.i(TAG, "On Click Selected Item : " + data.getName() + " : " + data.isSelected());
}
});
holder.checkBox.setTag(holder);
return convertView;
}
#SuppressLint("DefaultLocale")
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (List<KeyPairBoolData>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<KeyPairBoolData> FilteredArrList = new ArrayList<>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
Log.i(TAG, "Filter : " + mOriginalValues.get(i).getName() + " -> " + mOriginalValues.get(i).isSelected());
String data = mOriginalValues.get(i).getName();
if (data.toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
}
}
}
And from my main activity
MultiSpinnerSearch searchSpinner = (MultiSpinnerSearch) findViewById(R.id.searchMultiSpinner);
searchSpinner.setItems(listArray, -1, new SpinnerListener() {
#Override
public void onItemsSelected(List<KeyPairBoolData> items) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
Log.i("TAG", i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
FlashMessage(i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
if (GroupName.equals(""))
{
GroupName=GroupName+items.get(i).getName();
Group_stuid=Group_stuid+student_idlist[i+1];
}
else
{
GroupName=GroupName+","+items.get(i).getName();
Group_stuid=Group_stuid+"#"+student_idlist[i+1];
}
}
}
FlashMessage("grp name : "+GroupName);
FlashMessage("grp id : "+Group_stuid);
Audiofilename=appfunct.checkfile(eventType,acdses_sct,class_sct,category_sct,subject_sct,test_sct,Group_stuid,GroupName);
outfolder=appfunct.outfldr();
Group_stuid=Group_stuid.replaceAll("/","-");
File create_stuid=new File(outfolder.toString()+"/"+Group_stuid);
if(!create_stuid.exists()) {
create_stuid.mkdirs();
}
FlashMessage(""+GroupFoldername);
Group_listFiles=appfunct.showlistfiles(GroupFoldername);
if (Group_listFiles != null)
{
final CustomGroupFolder_ListDispaly adapter1 = new CustomGroupFolder_ListDispaly(Group_recording.this,R.layout.group_item_listview,Group_listFiles);
group_listview.setAdapter(adapter1);
}
GroupName="";
Group_stuid="";
selected_students=appfunct.getSelectedNamesGroup(GroupFoldername);
}
});
FlashMessage("out : grp id "+Group_stuid);
searchSpinner.setLimit(2, new MultiSpinnerSearch.LimitExceedListener() {
#Override
public void onLimitListener(KeyPairBoolData data) {
Toast.makeText(getApplicationContext(),
"Limit exceed ", Toast.LENGTH_LONG).show();
}
});
apply this to your adapter adapter.notifyDataSetChanged();
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>
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!