I have made a demo in app purchase for android,I have created a test product and purchase it for testing purpose,all is working very fine,But Only issue is when i tap outside the in app billing Dialog,it disappears,I want to do something like "setCancellable(false)" on it,Please suggest me,I need help,My code is as below:
code
package com.medicineqod.activity;
import inapUtils.IabHelper;
import inapUtils.IabHelper.OnConsumeFinishedListener;
import inapUtils.IabHelper.OnIabPurchaseFinishedListener;
import inapUtils.IabHelper.OnIabSetupFinishedListener;
import inapUtils.IabHelper.QueryInventoryFinishedListener;
import inapUtils.IabResult;
import inapUtils.Inventory;
import inapUtils.Purchase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.drm.DrmStore.ConstraintsColumns;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.medicineqod.FragmentAbstractActivity;
import com.medicineqod.R;
import com.medicineqod.DBAdapter.DataBaseHelper;
import com.medicineqod.model.Question;
import com.medicineqod.utility.CommonVariables;
/**
* Created by basheer on 4/26/14.
*/
public class QuestionOFDayActivity extends FragmentAbstractActivity
/* OnIabSetupFinishedListener, OnIabPurchaseFinishedListener */{
// When requested, this adapter returns a WallpaperCollectionFragment,
// representing an object in the collection.
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
ImageView btnNext, btnPrev;
static TextView tvError;
TextView tvDate;
TextView btnHome;
TextView tvTitle;
int mTotalCount;
int mPosition = 0;
int mActivity = 0;
ArrayList<Question> qusList = new ArrayList<Question>();
// edited by jigar
private static final String TAG = "com.medicineqod.inappbilling";
static IabHelper mHelper;
static final String ITEM_SKU = "com.medicineqod.product.one";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizoftheday);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
// Edited by jigar,....
showCustomeAlertValidation(QuestionOFDayActivity.this);
DataBaseHelper bBase = new DataBaseHelper(this);
mActivity = getIntent().getIntExtra(CommonVariables.ACTIVITY, 0);
if (mActivity == CommonVariables.FavQusAct) {
qusList = bBase.getFavQuestions();
mTotalCount = qusList.size();
} else if (mActivity == CommonVariables.PastQusAct) {
qusList = bBase.getPastQuestions();
mTotalCount = qusList.size();
} else if (mActivity == CommonVariables.QusOfTheDay) {
qusList = bBase.getQuestions();
mTotalCount = qusList.size();
} else {
qusList = bBase.getQuestions();
mTotalCount = qusList.size();
}
if (qusList.size() == 0) {
return;
}
mPosition = getIntent().getIntExtra("postion", 0);
Collections.reverse(qusList);
if (mPosition == -1) {
mPosition = qusList.size() - 1;
}
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(mPosition);
tvError = (TextView) findViewById(R.id.error_tv);
tvDate = (TextView) findViewById(R.id.topbar_date_tv);
tvTitle = (TextView) findViewById(R.id.topbar_title_tv);
btnNext = (ImageView) findViewById(R.id.bottom_next_img);
btnPrev = (ImageView) findViewById(R.id.bottom_prev_img);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mTotalCount - 1 > mPosition) {
mPosition++;
mViewPager.setCurrentItem(mPosition);
}
}
});
btnPrev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (0 < mPosition) {
mPosition--;
mViewPager.setCurrentItem(mPosition);
}
}
});
mViewPager
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mPosition = position;
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
tvDate.setText("" + qusList.get(position).getDate());
setTiltle(qusList.get(mPosition).getDate());
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
tvDate.setText("" + qusList.get(mPosition).getDate());
setTiltle(qusList.get(mPosition).getDate());
btnHome = (TextView) findViewById(R.id.topbar_left_tv);
if (mActivity == CommonVariables.FavQusAct) {
btnHome.setText("Back");
btnHome.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_back,
0, 0, 0);
} else if (mActivity == CommonVariables.PastQusAct) {
btnHome.setText("Back");
btnHome.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_back,
0, 0, 0);
} else if (mActivity == CommonVariables.QusOfTheDay) {
// btnHome.setText("Back");
// btnHome.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
// null);
}
btnHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_right);
}
});
// System.out.println(mPosition + "::::" + (mTotalCount - 1));
if (qusList.size() == 0 || qusList.size() == 1) {
btnPrev.setVisibility(View.INVISIBLE);
btnNext.setVisibility(View.INVISIBLE);
} else if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
}
private void setTiltle(String date) {
if (mActivity == CommonVariables.FavQusAct) {
tvTitle.setText(""
+ getApplication().getResources().getString(
R.string.title_fav_qus));
} else if (getCurrentDate().equals(date)) {
tvTitle.setText(""
+ getApplication().getResources().getString(R.string.qod));
} else {
tvTitle.setText(""
+ getApplication().getResources().getString(
R.string.title_past_qus));
}
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
fragment = new QuizCollectionFragment();
Bundle args = new Bundle();
args.putSerializable(QuizCollectionFragment.ARG_OBJECT,
(Serializable) qusList.get(position));
args.putInt(QuizCollectionFragment.QUZI_POSITION, position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return mTotalCount;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
return "good".toUpperCase(l);
}
}
public void setOnAnswer(String mPerformance, String mAswerView,
String mAswerQue, String mFavourite, int mPosition,
String mPercentage) {
if (qusList.size() > 0 && mPosition < qusList.size()) {
Question mQuizQuestion = qusList.get(mPosition);
mQuizQuestion.setAnsque(mAswerQue);
mQuizQuestion.setPerformance(mPerformance);
mQuizQuestion.setAnsview(mAswerView);
mQuizQuestion.setFavourite(mFavourite);
mQuizQuestion.setPercentage(mPercentage);
qusList.set(mPosition, mQuizQuestion);
}
}
public void refreshTheViewPage(int position) {
if (mActivity == CommonVariables.FavQusAct) {
tvDate.setText("");
qusList.remove(mPosition);
mTotalCount = qusList.size();
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setAdapter(mSectionsPagerAdapter);
if (mTotalCount - 1 < mPosition) {
mPosition = mTotalCount - 1;
}
mViewPager.setCurrentItem(mPosition);
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
if (qusList.size() == 0 || qusList.size() == 1) {
btnNext.setVisibility(View.INVISIBLE);
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
}
}
// Popup of subscribing app..
public void showCustomeAlertValidation(final Context context) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup);
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
final Button btn_subscribe = (Button) dialog
.findViewById(R.id.btn_subscribe);
btn_subscribe.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Subscribing code here...!!!
mHelper.launchPurchaseFlow(QuestionOFDayActivity.this,
ITEM_SKU, 10001, mPurchaseFinishedListener,
"mypurchasetoken");
dialog.dismiss();
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
String base64EncodedPublicKey = "MIIBIjANyOvuqXSF8qd4NAapQdRohAajUA3/N/L9XoD21B7lVqZnICXh1dFEnnVvNyhK+ws1Cr5YsPvIAprHvsQNJ2xtEGypNivk/AA6N91OY0r2dtZJZHGpSxDSsfHTfKk5/4CaW1itbdIo+JiGTieJyHIvMFdWSkLqaxR3JWy+0KwTHvzMrR15oClM9v8fKjNT6M8qxlhnyzLDd7G2/ifBIPTJjfdvWHoXaP/rHa2MbN2acPwvbbwIDAQAB";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
} else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
System.out
.println(":::::::::::::::::::::Purchase consumed successfuly::::::::::::::::::::");
}
}
};
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
System.out
.println("::::::::::::::::::::::::Purchase consumehas been finished successfully:::::::::::::::::::::");
} else {
// handle error
System.out
.println("::::::::::::::::::::::::Purchase consumehas failed:::::::::::::::::::::");
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
}
this is what you need to do in order to ristrict that.
dialog.setCanceledOnTouchOutside(false);
this will make sure dialog is not dismissed when touched outside of dialog box area.
Related
I am getting error at:
com.projects.fragments.MapFragment.onMapReady(MapFragment.java:200) at
com.projects.fragments.MapFragment.onMapReady(MapFragment.java:200)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown
Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown
Source)
Occurs in run time this the Mapfragment class
package com.projects.fragments;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.application.RealEstateApplication;
import com.config.Config;
import com.config.UIConfig;
import com.db.Queries;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.libraries.asynctask.MGAsyncTask;
import com.libraries.asynctask.MGAsyncTaskNoDialog;
import com.libraries.dataparser.DataParser;
import com.libraries.drawingview.DrawingView;
import com.libraries.location.MGLocationManagerUtils;
import com.libraries.sliding.MGSliding;
import com.libraries.usersession.UserAccessSession;
import com.libraries.utilities.MGUtilities;
import com.models.DataResponse;
import com.models.Favorite;
import com.models.Photo;
import com.models.PropertyType;
import com.models.RealEstate;
import com.projects.activities.DetailActivity;
import com.projects.realestatefinder.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* Created by mg on 27/07/16.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback,
RealEstateApplication.OnLocationListener,
GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapClickListener,
DrawingView.OnDrawingViewListener {
private View viewInflate;
private GoogleMap googleMap;
private MGSliding frameSliding;
SwipeRefreshLayout swipeRefresh;
MGAsyncTaskNoDialog task;
ArrayList<RealEstate> realEstates;
private HashMap<String, RealEstate> markers;
private ArrayList<Marker> markerList;
private RealEstate selectedRealEstate;
private DrawingView drawingView;
private Unbinder unbinder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_map, null);
unbinder = ButterKnife.bind(this, viewInflate);
return viewInflate;
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
if(task != null)
task.cancel(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
realEstates = new ArrayList<RealEstate>();
swipeRefresh = (SwipeRefreshLayout) viewInflate.findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
swipeRefresh.setProgressViewOffset(false, 0,100);
}
swipeRefresh.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
showRefresh(false);
FragmentManager fManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getChildFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
supportMapFragment.getMapAsync(this);
frameSliding = (MGSliding) viewInflate.findViewById(R.id.frameSliding);
Animation animationIn = AnimationUtils.loadAnimation(this.getActivity(), R.anim.slide_up2);
Animation animationOut = AnimationUtils.loadAnimation(this.getActivity(), R.anim.slide_down2);
frameSliding.setInAnimation(animationIn);
frameSliding.setOutAnimation(animationOut);
frameSliding.setVisibility(View.GONE);
markers = new HashMap<String, RealEstate>();
markerList = new ArrayList<Marker>();
}
#Override
public void onMapReady(GoogleMap _googleMap) {
googleMap = _googleMap;
googleMap.setOnInfoWindowClickListener(this);
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
if(frameSliding.getVisibility() == View.VISIBLE)
frameSliding.setVisibility(View.INVISIBLE);
}
});
drawingView = (DrawingView) viewInflate.findViewById(R.id.drawingView);
drawingView.setBrushSize(5);
drawingView.setPolygonFillColor(getResources().getColor(R.color.colorPrimaryAlpha));
drawingView.setColor(getResources().getColor(R.color.colorAccent));
drawingView.setPolylineColor(getResources().getColor(R.color.colorAccent));
drawingView.setGoogleMap(googleMap);
drawingView.setOnDrawingViewListener(this);
if(!MGUtilities.isLocationEnabled(getActivity()) && RealEstateApplication.currentLocation == null) {
MGLocationManagerUtils utils = new MGLocationManagerUtils();
utils.setOnAlertListener(new MGLocationManagerUtils.OnAlertListener() {
#Override
public void onPositiveTapped() {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
Config.PERMISSION_REQUEST_LOCATION_SETTINGS);
}
#Override
public void onNegativeTapped() {
showRefresh(false);
}
});
utils.showAlertView(
getActivity(),
R.string.location_error,
R.string.gps_not_on,
R.string.go_to_settings,
R.string.cancel);
}
else {
showRefresh(true);
if(RealEstateApplication.currentLocation != null) {
getData();
}
else {
refetch();
}
}
}
public void refetch() {
showRefresh(true);
RealEstateApplication app = (RealEstateApplication) getActivity().getApplication();
app.setOnLocationListener(this, getActivity());
}
private void getData() {
showRefresh(true);
task = new MGAsyncTaskNoDialog(getActivity());
task.setMGAsyncTaskListener(new MGAsyncTaskNoDialog.OnMGAsyncTaskListenerNoDialog() {
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTaskNoDialog asyncTask) {
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
showRefresh(false);
addMarkers(realEstates);
// showBoundedMap();
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
if(RealEstateApplication.currentLocation != null && MGUtilities.hasConnection(getContext())) {
try {
UserAccessSession accessSession = UserAccessSession.getInstance(getActivity());
float radius = accessSession.getFilterDistance();
if(radius == 0)
radius = Config.DEFAULT_FILTER_DISTANCE_IN_KM;
String strUrl = String.format("%s?api_key=%s&lat=%f&lon=%f&radius=%f&get_propertytypes=1&default_count_to_find_distance=%d",
Config.GET_DATA_JSON_URL,
Config.API_KEY,
RealEstateApplication.currentLocation.getLatitude(),
RealEstateApplication.currentLocation.getLongitude(),
radius,
Config.DEFAULT_COUNT_TO_FIND);
Log.e("URL", strUrl);
DataParser parser = new DataParser();
DataResponse data = parser.getData(strUrl);
if (data == null)
return;
if(data.getMax_distance() > 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistanceMax(data.getMax_distance());
}
if(Config.AUTO_ADJUST_DISTANCE) {
if(UserAccessSession.getInstance(getActivity()).getFilterDistance() == 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistance(data.getDefault_distance());
}
}
Queries q = RealEstateApplication.getQueriesInstance(getContext());
if (data.getProperty_types() != null && data.getProperty_types().size() > 0) {
for (PropertyType obj : data.getProperty_types()) {
q.deletePropertyType(obj.getPropertytype_id());
q.insertPropertyType(obj);
}
}
if (data.getReal_estates() != null && data.getReal_estates().size() > 0) {
for (RealEstate obj : data.getReal_estates()) {
double distance = obj.getDistance() * Config.CONVERSION_SERVER_DATA_DISTANCE_TO_KM;
obj.setDistance(distance);
q.deleteRealEstate(obj.getRealestate_id());
q.insertRealEstate(obj);
if (obj.getPhotos() != null && obj.getPhotos().size() > 0) {
for (Photo photo : obj.getPhotos()) {
q.deletePhoto(photo.getPhoto_id());
q.insertPhoto(photo);
}
}
if(obj.getAgent() != null) {
q.deleteAgent(obj.getAgent().getAgent_id());
q.insertAgent(obj.getAgent());
}
realEstates.add(obj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
realEstates = RealEstateApplication.getQueriesInstance(getContext()).getRealEstates();
if(RealEstateApplication.currentLocation != null) {
for(RealEstate realEstate : realEstates) {
Location locStore = new Location("Store");
locStore.setLatitude(realEstate.getLat());
locStore.setLongitude(realEstate.getLon());
double userDistanceFromStore =
RealEstateApplication.currentLocation.distanceTo(locStore) *
Config.CONVERSION_OFFLINE_DATA_DISTANCE_TO_KM;
realEstate.setDistance(userDistanceFromStore);
}
Collections.sort(realEstates, new Comparator<RealEstate>() {
#Override
public int compare(RealEstate obj1, RealEstate obj2) {
if (obj1.getDistance() < obj2.getDistance())
return -1;
if (obj1.getDistance() > obj2.getDistance())
return 1;
return 0;
}
});
}
}
}
});
task.execute();
}
private void addMarkers(ArrayList<RealEstate> arrayList) {
if(googleMap != null)
googleMap.clear();
try {
markerList.clear();
markers.clear();
for(RealEstate entry: arrayList) {
if(entry.getLat() == 0 || entry.getLon() == 0)
continue;
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
showBoundedMap();
}
catch(Exception e) {
e.printStackTrace();
}
}
private Marker createMarker(RealEstate realEstate) {
final MarkerOptions markerOptions = new MarkerOptions();
String strPrice = String.format("%s %s", realEstate.getCurrency(), realEstate.getPrice());
Spanned price = Html.fromHtml(strPrice);
price = Html.fromHtml(price.toString());
Spanned storeAddress = Html.fromHtml(realEstate.getAddress());
storeAddress = Html.fromHtml(storeAddress.toString());
markerOptions.title( price.toString() );
String address = storeAddress.toString();
if(address.length() > Config.ELLIPSE_HOME_COUNT)
address = storeAddress.toString().substring(0, Config.ELLIPSE_HOME_COUNT) + "...";
markerOptions.snippet(address);
markerOptions.position(new LatLng(realEstate.getLat(), realEstate.getLon()));
markerOptions.icon(BitmapDescriptorFactory.fromResource(UIConfig.MAP_PIN_REAL_ESTATE));
Marker mark = googleMap.addMarker(markerOptions);
mark.setInfoWindowAnchor(Config.MAP_INFO_WINDOW_X_OFFSET, 0);
return mark;
}
private void showBoundedMap() {
if(markerList == null && markerList.size() == 0 ) {
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
return;
}
if(markerList.size() > 0) {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < markerList.size(); i++) {
Marker marker = markerList.get(i);
bld.include(marker.getPosition());
}
LatLngBounds bounds = bld.build();
googleMap.moveCamera(
CameraUpdateFactory.newLatLngBounds(bounds,
this.getResources().getDisplayMetrics().widthPixels,
this.getResources().getDisplayMetrics().heightPixels,
70));
}
else {
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
Location loc = RealEstateApplication.currentLocation;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(loc.getLatitude(), loc.getLongitude()),
70) );
}
}
}
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
final RealEstate obj = markers.get(marker.getId());
selectedRealEstate = obj;
if(RealEstateApplication.currentLocation != null) {
Location loc = new Location("marker");
loc.setLatitude(marker.getPosition().latitude);
loc.setLongitude(marker.getPosition().longitude);
double meters = RealEstateApplication.currentLocation.distanceTo(loc);
double miles = meters * Config.METERS_TO_KM;
String str = String.format("%.1f %s",
miles,
MGUtilities.getStringFromResource(getActivity(), R.string.km));
TextView tvDistance = (TextView) viewInflate.findViewById(R.id.tvDistance);
tvDistance.setText(str);
}
frameSliding.setVisibility(View.VISIBLE);
Queries q = RealEstateApplication.getQueriesInstance(getContext());
ImageView imgViewThumb = (ImageView) viewInflate.findViewById(R.id.imgViewThumb);
Photo p = q.getPhotoByRealEstateId(obj.getRealestate_id());
if(p != null) {
RealEstateApplication.getImageLoaderInstance(
getActivity()).displayImage(p.getPhoto_url(),
imgViewThumb,
RealEstateApplication.getDisplayImageOptionsInstance());
}
else {
imgViewThumb.setImageResource(UIConfig.IMAGE_PLACEHOLDER);
}
imgViewThumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), DetailActivity.class);
i.putExtra("realestate", obj);
getActivity().startActivity(i);
}
});
String strPrice = String.format("%s %s", obj.getCurrency(), obj.getPrice());
Spanned spannedPrice = Html.fromHtml(strPrice);
spannedPrice = Html.fromHtml(spannedPrice.toString());
Spanned spannedAddress = Html.fromHtml(obj.getAddress());
spannedAddress = Html.fromHtml(spannedAddress.toString());
String address = spannedAddress.toString();
if(address.length() > Config.ELLIPSE_HOME_COUNT)
address = spannedAddress.toString().substring(0, Config.ELLIPSE_HOME_COUNT) + "...";
TextView tvTitle = (TextView) viewInflate.findViewById(R.id.tvTitle);
TextView tvSubtitle = (TextView) viewInflate.findViewById(R.id.tvSubtitle);
tvTitle.setText(spannedPrice);
tvSubtitle.setText(address);
ToggleButton toggleButtonFave = (ToggleButton) viewInflate.findViewById(R.id.toggleButtonFave);
toggleButtonFave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkFave(v, obj);
}
});
Favorite fave = q.getFavoriteByRealEstateId(obj.getRealestate_id());
toggleButtonFave.setChecked(true);
if(fave == null)
toggleButtonFave.setChecked(false);
}
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
frameSliding.setVisibility(View.INVISIBLE);
}
private void checkFave(View view, RealEstate realEstate) {
Queries q = RealEstateApplication.getQueriesInstance(getContext());
Favorite fave = q.getFavoriteByRealEstateId(realEstate.getRealestate_id());
if(fave != null) {
q.deleteFavorite(realEstate.getRealestate_id());
((ToggleButton) view).setChecked(false);
}
else {
fave = new Favorite();
fave.setRealestate_id(realEstate.getRealestate_id());
q.insertFavorite(fave);
((ToggleButton) view).setChecked(true);
}
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
ArrayList<Marker> markers1;
#SuppressLint("DefaultLocale")
#Override
public void onUserDidFinishDrawPolygon(PolygonOptions polygonOptions) {
// TODO Auto-generated method stub
googleMap.clear();
googleMap.addPolygon( polygonOptions );
markers1 = getMarkersInsidePoly(polygonOptions, null, markerList);
markerList.clear();
markers.clear();
for(Marker mark1 : markers1) {
for(RealEstate realEstate : realEstates) {
String strPrice = String.format("%s %s", realEstate.getCurrency(), realEstate.getPrice());
if(mark1.getPosition().latitude == realEstate.getLat() &&
mark1.getPosition().longitude == realEstate.getLon() &&
mark1.getTitle().compareTo(strPrice) == 0) {
Marker mark = createMarker(realEstate);
markerList.add(mark);
markers.put(mark.getId(), realEstate);
break;
}
}
}
drawingView.enableDrawing(false);
drawingView.resetPolygon();
drawingView.startNew();
if(markers1.size() == 0)
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
}
#Override
public void onUserDidFinishDrawPolyline(PolylineOptions polylineOptions) { }
public ArrayList<Marker> getMarkersInsidePoly(PolygonOptions polygonOptions,
PolylineOptions polylineOptions, ArrayList<Marker> markers) {
ArrayList<Marker> markersFound = new ArrayList<Marker>();
for(Marker mark : markers) {
Boolean isFound = polygonOptions != null ?
drawingView.latLongContainsInPolygon(mark.getPosition(), polygonOptions) :
drawingView.latLongContainsInPolyline(mark.getPosition(), polylineOptions);
if(isFound) {
markersFound.add(mark);
}
}
return markersFound;
}
#OnClick(R.id.btnDraw)
public void drawMap() {
drawingView.enableDrawing(true);
drawingView.startDrawingPolygon(true);
}
#OnClick(R.id.btnRefresh)
public void refresh() {
showRefresh(true);
addMarkers(realEstates);
showRefresh(false);
}
#OnClick(R.id.btnRoute)
public void route() {
if(selectedRealEstate == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.action_error,
R.string.cannot_proceed_route);
return;
}
String geo = String.format("http://maps.google.com/maps?f=d&daddr=%s&dirflg=d", selectedRealEstate.getAddress()) ;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geo));
intent.setComponent(new ComponentName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"));
startActivity(intent);
}
#OnClick(R.id.btnCurrentLocation)
public void currentLocation() {
Location loc = RealEstateApplication.currentLocation;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(loc.getLatitude(), loc.getLongitude()),
70) );
}
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
RealEstateApplication app = (RealEstateApplication) getActivity().getApplication();
app.setOnLocationListener(null, getActivity());
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
googleMap.setMyLocationEnabled(true);
}
#Override
public void onLocationRequestDenied() {
showRefresh(false);
MGUtilities.showAlertView(getActivity(), R.string.permission_error, R.string.permission_error_details_location);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Config.PERMISSION_REQUEST_LOCATION_SETTINGS) {
if(MGUtilities.isLocationEnabled(getActivity()))
refetch();
else {
showRefresh(false);
Toast.makeText(getActivity(),
R.string.location_error_not_turned_on, Toast.LENGTH_LONG).show();
}
}
}
}
I'm not even sure if this is the right thing to do any more with Google not supporting 'Google Now', but I can't seem to find any suitable alternative.
Using this https://antonioleiva.com/voice_search_google_now/#comment-8611 as a guide I am trying o implement a voice search in my App, but not having much luck.
I already have a search facility for users. What I have done so far:-
GlobalApplication.java
public static Queries getQueriesInstance(Context context) {
if(q == null) {
dbHelper = new DbHelper(context);
q = new Queries(db, dbHelper);
}
return q;
}
Then in MainActivity.java
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Intent i;
int id = item.getItemId();
...
...
if(id == R.id.nav_search) {
i = new Intent(this, SearchActivity.class);
startActivity(i);
}
...
...
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And finally, before adding anything, my SearchActivity.java file
package com.projects.activities;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.SpannableString;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.application.GlobalApplication;
import com.config.Config;
import com.db.Queries;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.libraries.asynctask.MGAsyncTaskNoDialog;
import com.libraries.dataparser.DataParser;
import com.libraries.location.MGLocationManagerUtils;
import com.libraries.utilities.MGUtilities;
import com.models.DataResponse;
import com.models.Deal;
import com.models.DealCategory;
import com.models.Status;
import com.projects.adapp.R;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class SearchActivity extends AppCompatActivity implements
GlobalApplication.OnLocationListener{
private AsyncTaskNoDialog task;
SeekBar seekBarRadius;
SwipeRefreshLayout swipeRefresh;
Queries q;
Button btnSearch;
ArrayList<DealCategory> selectedCategories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setContentView(R.layout.activity_list_swipe_search);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.search);
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
swipeRefresh.setProgressViewOffset(false, 0,100);
}
swipeRefresh.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
showRefresh(false);
q = GlobalApplication.getQueriesInstance(this);
seekBarRadius = (SeekBar) findViewById(R.id.seekBarRadius);
seekBarRadius.setMax(Config.SEARCH_RADIUS_MAX_VALUE);
seekBarRadius.setProgress(Config.SEARCH_RADIUS_DEFAULT_VALUE);
seekBarRadius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) { }
#Override
public void onStartTrackingTouch(SeekBar arg0) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
updateRadius(progress);
}
});
updateRadius(seekBarRadius.getProgress());
selectedCategories = new ArrayList<DealCategory>();
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search();
}
});
FrameLayout frameCategory = (FrameLayout) findViewById(R.id.frameCategory);
frameCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SearchActivity.this, CategorySearchActivity.class);
startActivityForResult(i, Config.RESULT_CODE_CATEGORY);
}
});
seekBarRadius.setEnabled(false);
btnSearch.setEnabled(false);
if(!MGUtilities.isLocationEnabled(this) && GlobalApplication.currentLocation == null) {
MGLocationManagerUtils utils = new MGLocationManagerUtils();
utils.setOnAlertListener(new MGLocationManagerUtils.OnAlertListener() {
#Override
public void onPositiveTapped() {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
Config.PERMISSION_REQUEST_LOCATION_SETTINGS);
}
#Override
public void onNegativeTapped() {
Toast.makeText(SearchActivity.this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
});
utils.showAlertView(
this,
R.string.location_error,
R.string.gps_not_on,
R.string.go_to_settings,
R.string.cancel);
}
else {
refetch();
}
GlobalApplication app = (GlobalApplication)getApplication();
app.sendScreenView(Config.kGAIScreenNameSearch);
}
public void refetch() {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(this, this);
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(null, this);
seekBarRadius.setEnabled(true);
btnSearch.setEnabled(true);
}
#Override
public void onLocationRequestDenied() {
MGUtilities.showAlertView(this, R.string.permission_error, R.string.permission_error_details_location);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Config.RESULT_CODE_CATEGORY && resultCode == RESULT_OK) {
selectedCategories = (ArrayList<DealCategory>) data.getSerializableExtra("categories");
if(selectedCategories != null && selectedCategories.size() > 0) {
TextView tvCategory = (TextView) findViewById(R.id.tvCategory);
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += cat.getCategory();
if(x < selectedCategories.size() - 1)
cats += ", ";
}
if(!cats.isEmpty()) {
tvCategory.setText(cats);
}
else {
tvCategory.setText(R.string.all_categories);
}
}
}
if (requestCode == Config.PERMISSION_REQUEST_LOCATION_SETTINGS) {
if(MGUtilities.isLocationEnabled(this))
refetch();
else {
Toast.makeText(this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
}
}
public void updateRadius(int progress){
String strSeekVal = String.format("%d %s",
progress,
MGUtilities.getStringFromResource(SearchActivity.this, R.string.km));
TextView tvRadius = (TextView) findViewById(R.id.tvRadius);
tvRadius.setText(strSeekVal);
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
public void search() {
showRefresh(true);
beginParsing();
}
public ArrayList<Deal> searchLocal() {
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
int radius = seekBarRadius.getProgress();
int countParams = 0;
countParams += searchStr.length() > 0 ? 1 : 0;
countParams += radius > 0 ? 1 : 0;
countParams += selectedCategories != null && selectedCategories.size() > 0 ? 1 : 0;
ArrayList<Deal> array = q.getDeals();
ArrayList<Deal> results = new ArrayList<>();
for(Deal event : array) {
try {
int qualifyCount = 0;
if(searchStr.length() > 0) {
boolean isFound = searchStr.contains(event.getTitle()) ||
searchStr.contains(event.getAddress()) ||
searchStr.contains(event.getDesc()) ||
event.getTitle().contains(searchStr) ||
event.getAddress().contains(searchStr) ||
event.getDesc().contains(searchStr);
if(isFound)
qualifyCount += 1;
}
if(GlobalApplication.currentLocation != null) {
Location loc1 = new Location("Loc1");
loc1.setLatitude(event.getLat());
loc1.setLongitude(event.getLon());
Location loc2 = new Location("Loc2");
loc2.setLatitude(GlobalApplication.currentLocation.getLatitude());
loc2.setLongitude(GlobalApplication.currentLocation.getLongitude());
double distance = loc1.distanceTo(loc2) * Config.METERS_TO_KM;
event.setDistance(distance);
if(distance <= radius)
qualifyCount += 1;
}
ObjectMapper mapper = new ObjectMapper();
DataResponse categories = mapper.readValue(event.getCategories(), DataResponse.class);
if(categories != null && categories.getCategories() != null) {
for(DealCategory cat : categories.getCategories()) {
boolean isFound = false;
for(DealCategory selectedCat : selectedCategories) {
if(selectedCat.getCategory_id() == cat.getCategory_id()) {
isFound = true;
break;
}
}
if(isFound) {
qualifyCount += 1;
break;
}
}
}
if(qualifyCount == countParams)
results.add(event);
}
catch(Exception e) {
e.printStackTrace();
}
}
return results;
}
public void beginParsing() {
if(task != null)
task.cancel(true);
task = new MGAsyncTaskNoDialog(this);
task.setMGAsyncTaskListener(new MGAsyncTaskNoDialog.OnMGAsyncTaskListenerNoDialog() {
DataResponse response;
ArrayList<Deal> events;
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPostExecute(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
updateData(response, events);
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
if(MGUtilities.hasConnection(SearchActivity.this)) {
response = syncData();
}
else{
events = searchLocal();
}
}
});
task.execute();
}
public DataResponse syncData() {
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += String.valueOf(cat.getCategory_id());
if (x < selectedCategories.size() - 1)
cats += ",";
}
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
double radius = seekBarRadius.getProgress() * Config.KM_TO_MILES;
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("keywords", searchStr ));
params.add(new BasicNameValuePair("lat", String.valueOf(GlobalApplication.currentLocation.getLatitude()) ));
params.add(new BasicNameValuePair("lon", String.valueOf(GlobalApplication.currentLocation.getLongitude()) ));
params.add(new BasicNameValuePair("category_ids", cats) );
params.add(new BasicNameValuePair("radius", String.valueOf(radius)) );
params.add(new BasicNameValuePair("api_key", Config.API_KEY ));
GlobalApplication.params = params;
DataResponse response = DataParser.getJSONFromUrlWithPostRequest(Config.SEARCH_DEALS_JSON_URL, params);
return response;
}
public void updateData(DataResponse response, ArrayList<Deal> deals) {
showRefresh(false);
if(response != null) {
Status status = response.getStatus();
if(status.getStatus_code() == -1 && response.getDeals() != null ) {
if(response.getDeals().size() == 0) {
Toast.makeText(SearchActivity.this, R.string.no_results_found, Toast.LENGTH_SHORT).show();
return;
}
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", response.getDeals());
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, status.getStatus_text());
}
}
else if(deals != null && deals.size() > 0) {
GlobalApplication.params = null;
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", deals);
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, R.string.problems_encountered_while_syncing);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
// Handle action bar actions click
switch (item.getItemId()) {
default:
finish();
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(android.view.Menu menu) {
// if nav drawer is opened, hide the action items
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onDestroy() {
super.onDestroy();
if(task != null)
task.cancel(true);
}
}
Taken from the tutorial link above, I then added the following to my Manifest
AndroidManifest.xml
<activity
android:name="com.projects.activities.SearchActivity">
<intent-filter>
<action android:name="com.google.android.gms.actions.SEARCH_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I then added the following to my SearchActivity.java file
private static final String ACTION_VOICE_SEARCH =
"com.google.android.gms.actions.SEARCH_ACTION";
private void handleVoiceSearch(Intent intent) {
if (intent != null && ACTION_VOICE_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
setSearchViewVisible(true);
searchView.setQuery(query, true);
}
}
The in various places and in slightly different ways, I have tried adding
handleVoiceSearch(getIntent());
to the SearchActivity.java file, but I don't seem to be having much luck. I am testing from an Alpha version uploaded to Play Store.
Is there anything obvious anyone can see I am missing?
Thanks
I'm developing a messaging app using quickblox, the activity where all the users in the database show, only 10 users show up when there's more users than just 10. Any help would be much appreciated!! Got to add more details, but this should explain the problem enough
ListUsers Class
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.liftersheaven.messaging.Adapter.ListUsersAdapter;
import com.liftersheaven.messaging.Common.Common;
import com.liftersheaven.messaging.Holder.QBUsersHolder;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.QBSystemMessagesManager;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.chat.model.QBChatMessage;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.chat.request.QBDialogRequestBuilder;
import com.quickblox.chat.utils.DialogUtils;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import org.jivesoftware.smack.SmackException;
import java.util.ArrayList;
import java.util.List;
public class ListUsers extends AppCompatActivity {
ListView lstUsers;
Button btnCreate;
String mode="";
QBChatDialog qbChatDialog;
List<QBUser> userAdd=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_users);
Toolbar toolbar = (Toolbar)findViewById(R.id.chatusers_toolbar);
toolbar.setTitle("Users");
setSupportActionBar(toolbar);
mode = getIntent().getStringExtra(Common.UPDATE_MODE);
qbChatDialog=(QBChatDialog)getIntent().getSerializableExtra(Common.UPDATE_DIALOG_EXTRA);
lstUsers = (ListView)findViewById(R.id.lstUsers);
lstUsers.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btnCreate = (Button)findViewById(R.id.btn_create_chat);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mode == null) {
int countChoice = lstUsers.getCount();
if (lstUsers.getCheckedItemPositions().size() == 1)
createPrivateChat(lstUsers.getCheckedItemPositions());
else if (lstUsers.getCheckedItemPositions().size() > 1)
createGroupChat(lstUsers.getCheckedItemPositions());
else
Toast.makeText(ListUsers.this, "Select a friend to chat with", Toast.LENGTH_SHORT).show();
} else if (mode.equals(Common.UPDATE_ADD_MODE) && qbChatDialog != null) {
if (userAdd.size() > 0) {
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
int cntChoice = lstUsers.getCount();
SparseBooleanArray checkItemPositions = lstUsers.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (checkItemPositions.get(i)) {
QBUser user = (QBUser) lstUsers.getItemAtPosition(i);
requestBuilder.addUsers(user);
}
}
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(getBaseContext(), "Add user success", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onError(QBResponseException e) {
}
});
}
} else if (mode.equals(Common.UPDATE_REMOVE_MODE) && qbChatDialog != null) {
if (userAdd.size() > 0) {
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
int cntChoice = lstUsers.getCount();
SparseBooleanArray checkItemPositions = lstUsers.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (checkItemPositions.get(i)) {
QBUser user = (QBUser) lstUsers.getItemAtPosition(i);
requestBuilder.removeUsers(user);
}
}
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(getBaseContext(), "Remove user success", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
}
});
if (mode == null && qbChatDialog == null)
retrieveAllUser();
else{
if (mode.equals(Common.UPDATE_ADD_MODE))
loadListAvailableUser();
else if (mode.equals(Common.UPDATE_REMOVE_MODE))
loadListUserInGroup();
}
}
private void loadListUserInGroup() {
btnCreate.setText("Remove User");
QBRestChatService.getChatDialogById(qbChatDialog.getDialogId())
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
List<Integer> occupantsId = qbChatDialog.getOccupants();
List<QBUser> listUserAlreadyInGroup = QBUsersHolder.getInstance().getUsersByIds(occupantsId);
ArrayList<QBUser> users = new ArrayList<QBUser>();
users.addAll(listUserAlreadyInGroup);
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),users);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
userAdd = users;
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(ListUsers.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void loadListAvailableUser() {
btnCreate.setText("Add User");
QBRestChatService.getChatDialogById(qbChatDialog.getDialogId())
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
ArrayList<QBUser> listUsers = QBUsersHolder.getInstance().getAllUsers();
List<Integer> occupantsId = qbChatDialog.getOccupants();
List<QBUser>listUserAlreadyInChatGroup = QBUsersHolder.getInstance().getUsersByIds(occupantsId);
for (QBUser user:listUserAlreadyInChatGroup)
listUsers.remove(user);
if (listUsers.size() > 0){
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),listUsers);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
userAdd = listUsers;
}
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(ListUsers.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void createGroupChat(SparseBooleanArray checkedItemPositions) {
final ProgressDialog mDialog = new ProgressDialog(ListUsers.this);
mDialog.setMessage("Waiting...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
int countChoice = lstUsers.getCount();
ArrayList<Integer> occupantIdsList = new ArrayList<>();
for (int i =0;i<countChoice;i++){
if (checkedItemPositions.get(i)){
QBUser user = (QBUser)lstUsers.getItemAtPosition(i);
occupantIdsList.add(user.getId());
}
}
QBChatDialog dialog = new QBChatDialog();
dialog.setName(Common.createChatDialogName(occupantIdsList));
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
mDialog.dismiss();
Toast.makeText(getBaseContext(), "Chat dialog successfully created", Toast.LENGTH_SHORT).show();
finish();
QBSystemMessagesManager qbSystemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
QBChatMessage qbChatMessage = new QBChatMessage();
qbChatMessage.setBody(qbChatDialog.getDialogId());
for (int i=0;i<qbChatDialog.getOccupants().size();i++) {
qbChatMessage.setRecipientId(qbChatDialog.getOccupants().get(i));
try {
qbSystemMessagesManager.sendSystemMessage(qbChatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
finish();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR",e.getMessage());
}
});
}
private void createPrivateChat(SparseBooleanArray checkedItemPositions) {
final ProgressDialog mDialog = new ProgressDialog(ListUsers.this);
mDialog.setMessage("Waiting...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
int countChoice = lstUsers.getCount();
for(int i=0;i<countChoice;i++){
if (checkedItemPositions.get(i)){
final QBUser user = (QBUser)lstUsers.getItemAtPosition(i);
QBChatDialog dialog = DialogUtils.buildPrivateDialog(user.getId());
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
mDialog.dismiss();
Toast.makeText(getBaseContext(), "Private chat dialog successfully created", Toast.LENGTH_SHORT).show();
finish();
QBSystemMessagesManager qbSystemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
QBChatMessage qbChatMessage = new QBChatMessage();
qbChatMessage.setRecipientId(user.getId());
qbChatMessage.setBody(qbChatDialog.getDialogId());
try {
qbSystemMessagesManager.sendSystemMessage(qbChatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
finish();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR",e.getMessage());
}
});
}
}
}
private void retrieveAllUser() {
QBUsers.getUsers(null).performAsync(new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> qbUsers, Bundle bundle) {
QBUsersHolder.getInstance().putUsers(qbUsers);
ArrayList<QBUser> qbUserWithoutCurrent = new ArrayList<QBUser>();
for (QBUser user : qbUsers){
if (!user.getLogin().equals(QBChatService.getInstance().getUser().getLogin()))
qbUserWithoutCurrent.add(user);
}
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),qbUserWithoutCurrent);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR", e.getMessage());
}
});
}
}
ListUsersAdapter Class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
public class ListUsersAdapter extends BaseAdapter {
private Context context;
private ArrayList<QBUser> qbUserArrayList;
public ListUsersAdapter(Context context, ArrayList<QBUser> qbUserArrayList){
this.context = context;
this.qbUserArrayList = qbUserArrayList;
}
#Override
public int getCount() {
return qbUserArrayList.size();
}
#Override
public Object getItem(int position) {
return qbUserArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(android.R.layout.simple_list_item_multiple_choice,null);
TextView textView = (TextView)view.findViewById(android.R.id.text1);
textView.setText(qbUserArrayList.get(position).getLogin());
}
return view;
}
}
QBUserHolder Class
import android.util.SparseArray;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
import java.util.List;
public class QBUsersHolder {
private static QBUsersHolder instance;
private SparseArray<QBUser> qbUserSparseArray;
public static synchronized QBUsersHolder getInstance(){
if (instance == null)
instance = new QBUsersHolder();
return instance;
}
private QBUsersHolder(){
qbUserSparseArray = new SparseArray<>();
}
public void putUsers(List<QBUser> users){
for (QBUser user:users)
putUser(user);
}
public void putUser(QBUser user) {
qbUserSparseArray.put(user.getId(),user);
}
public QBUser getUserById(int id){
return qbUserSparseArray.get(id);}
public List<QBUser> getUsersByIds(List<Integer> ids){
List<QBUser> qbUser = new ArrayList<>();
for(Integer id:ids) {
QBUser user = getUserById(id);
if (user != null)
qbUser.add(user);
}
return qbUser;
}
public ArrayList<QBUser> getAllUsers() {
ArrayList<QBUser> result = new ArrayList<>();
for (int i=0;i<qbUserSparseArray.size();i++)
result.add(qbUserSparseArray.valueAt(i));
return result;
}
}
By default you could retrieve only 10 users per page. You should change JSON request which retrieve users
This is my code for youtube view in this when I am clicking zoom button of youtube view, Buffering continues on changing the screen orientation I have added configuration changes in the manifest file but it's not working for zoom button of youtube view. How should I handle buffering when button is clicked so that it do not start again?
## Heading ##package com.assignment.root.movielistingapp.activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.assignment.root.movielistingapp.R;
import com.assignment.root.movielistingapp.model.Results;
import com.assignment.root.movielistingapp.model.ResultsForVideo;
import com.assignment.root.movielistingapp.model.VideoKeyModel;
import com.assignment.root.movielistingapp.utils.Constants;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.kelltontech.ui.IScreen;
import com.kelltontech.utils.ConnectivityUtils;
import com.kelltontech.utils.StringUtils;
import com.kelltontech.volley.ext.GsonObjectRequest;
import com.kelltontech.volley.ext.RequestManager;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
public class VideoPlayActivity extends YouTubeBaseActivity implements IScreen, YouTubePlayer.OnInitializedListener {
private ArrayList<ResultsForVideo> mVideoAvailableList;
private String mStringId;
private YouTubePlayerView mYouTubePlayerView;
private TextView mNameTextView;
private Results mResults;
private YouTubePlayer youTubePlayer;
private TextView mOverViewTextView;
private ScrollView scrollView;
private TextView mReleasedDateTextView;
private boolean isFullScreen;
private TextView mTotalViewsTextViews;
private YouTubePlayer mYouTubePlayer;
/**
* #param savedInstanceState
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_play);
initLayout();
if (savedInstanceState == null) {
getIntentFromActivity();
getData(Constants.Action_ID_FOR_VIDEO);
setAllData();
checkOrientation();
}
}
private void checkOrientation() {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
scrollView.setVisibility(View.GONE);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
scrollView.setVisibility(View.VISIBLE);
}
}
private void initLayout() {
scrollView = (ScrollView) findViewById(R.id.scrollViewId);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
mNameTextView = (TextView) findViewById(R.id.textView_name_id);
mOverViewTextView = (TextView) findViewById(R.id.textViewOverViewId);
mReleasedDateTextView = (TextView) findViewById(R.id.releasedDateTextViewID);
mTotalViewsTextViews = (TextView) findViewById(R.id.textViewTotalViewsId);
}
#Override
public void updateUi(boolean status, int actionID, Object serviceResponse) {
if (serviceResponse instanceof VideoKeyModel) {
VideoKeyModel videoKeyModel = (VideoKeyModel) serviceResponse;
mVideoAvailableList = videoKeyModel.getResults();
mYouTubePlayerView.initialize(Constants.API_KEY, this);
}
}
#Override
public void onEvent(int eventId, Object eventData) {
//not in use
}
/**
* #param actionID this fucntion is used to hit the Api
*/
#Override
public void getData(int actionID) {
if (!ConnectivityUtils.isNetworkEnabled(this)) {
return;
}
if (actionID == Constants.Action_ID_FOR_VIDEO) {
try {
String totalUrl = Constants.baseURl + mStringId + Constants.VIDEOS + Constants.API_KEY;
RequestManager.addRequest(new GsonObjectRequest<VideoKeyModel>(totalUrl, new HashMap<String, String>(), null, VideoKeyModel.class, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(VideoPlayActivity.this, getResources().getString(R.string.ERROR_OCCUR), Toast.LENGTH_LONG);
//not in use
}
}) {
#Override
protected void deliverResponse(VideoKeyModel response) {
updateUi(true, Constants.Action_ID_FOR_VIDEO, response);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
void getIntentFromActivity() {
Intent intent = getIntent();
if (intent != null) {
mResults = getIntent().getParcelableExtra(Constants.SEND_RESULT);
mStringId = mResults.getId().toString();
}
}
/**
* #param provider
* #param youTubePlayer
* #param wasRestored
*/
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer youTubePlayer, boolean wasRestored) {
this.youTubePlayer = youTubePlayer;
/* YouTubePlayer.PlayerStyle style = YouTubePlayer.PlayerStyle.MINIMAL;
youTubePlayer.setPlayerStyle(style);*/
mYouTubePlayer = youTubePlayer;
if (mVideoAvailableList.size() != 0) {
if (mVideoAvailableList.size() != 0) {
this.mYouTubePlayer.loadVideo(mVideoAvailableList.get(0).getKey());
if (!wasRestored) {
this.mYouTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = b;
if (isFullScreen) {
scrollView.setVisibility(View.GONE);
} else {
youTubePlayer.setFullscreen(false);
setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
scrollView.setVisibility(View.VISIBLE);
}
}
});
}
}
} else
Toast.makeText(VideoPlayActivity.this, getResources().getString(R.string.CANNOT_PLAY_VIDEO), Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
public void onBackPressed() {
if (isFullScreen) {
youTubePlayer.setFullscreen(false);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
super.onBackPressed();
}
}
private String getFormattedDate(String date) {
String orignalDate = date;
String splittedDate[] = orignalDate.split("-");
int month = Integer.parseInt(splittedDate[1]);
String yearString = splittedDate[0].substring(2);
String monthString = (new DateFormatSymbols().getMonths()[month - 1]).substring(0, 3);
String dateString;
if (splittedDate[2].charAt(0) == '0') {
dateString = String.valueOf(splittedDate[2].charAt(1));
} else {
dateString = splittedDate[2];
}
String finalDate = dateString + getDayNumberSuffix(Integer.parseInt(dateString)) +
String.valueOf(" ") + monthString + String.valueOf(" ") + String.valueOf("'") + yearString + String.valueOf("'");
return finalDate;
}
private String getDayNumberSuffix(int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
scrollView.setVisibility(View.VISIBLE);
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
scrollView.setVisibility(View.GONE); // or here
}
}
private void setAllData() {
if (!StringUtils.isNullOrEmpty(mResults.getTitle())) {
mNameTextView.setText(mResults.getTitle());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mReleasedDateTextView.setText(Html.fromHtml("<b>" + getResources().getString(R.string.RELEASED_DATE) + "</b>" + String.valueOf(" ") + getFormattedDate(mResults.getRelease_date()), Html.FROM_HTML_MODE_LEGACY));
} else {
mReleasedDateTextView.setText(Html.fromHtml("<b>" + getResources().getString(R.string.RELEASED_DATE) + "</b>" + String.valueOf(" ") + getFormattedDate(mResults.getRelease_date())));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mReleasedDateTextView.setText(Html.fromHtml("<b>" + getResources().getString(R.string.RELEASED_DATE) + "</b>" + String.valueOf(" ") + getFormattedDate(mResults.getFirst_air_date()), Html.FROM_HTML_MODE_LEGACY));
} else {
mReleasedDateTextView.setText(Html.fromHtml("<b>" + getResources().getString(R.string.RELEASED_DATE) + "</b>" + String.valueOf(" ") + getFormattedDate(mResults.getFirst_air_date())));
}
mNameTextView.setText(mResults.getName());
}
mOverViewTextView.setText(mResults.getOverview());
mTotalViewsTextViews.setText(mResults.getVote_count() + String.valueOf(" ") + String.valueOf(getResources().getString(R.string.VIEWS)));
}
}
I try to solve using below code:
[Reference: Android: Clear Cache of All Apps?
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
and add permission in AndroidMenifest.xml file
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
But when i run this code, then throw exception :
java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 2
Any suggestion to overcome this exception or another solution for clear cache of all apps programmatically. Thanks
follow the link. hopefully get a solutions
https://fossdroid.com/s.html?q=cache+cleaner
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
import com.frozendevs.cache.cleaner.R;
import com.frozendevs.cache.cleaner.activity.SettingsActivity;
import com.frozendevs.cache.cleaner.model.AppsListItem;
import com.frozendevs.cache.cleaner.model.CleanerService;
import com.frozendevs.cache.cleaner.model.adapter.AppsListAdapter;
import com.frozendevs.cache.cleaner.widget.DividerDecoration;
import com.frozendevs.cache.cleaner.widget.RecyclerView;
import java.util.List;
public class CleanerFragment extends Fragment implements CleanerService.OnActionListener {
private static final int REQUEST_STORAGE = 0;
private static final String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private CleanerService mCleanerService;
private AppsListAdapter mAppsListAdapter;
private TextView mEmptyView;
private SharedPreferences mSharedPreferences;
private ProgressDialog mProgressDialog;
private View mProgressBar;
private TextView mProgressBarText;
private LinearLayoutManager mLayoutManager;
private Menu mOptionsMenu;
private boolean mAlreadyScanned = false;
private boolean mAlreadyCleaned = false;
private String mSearchQuery;
private String mSortByKey;
private String mCleanOnAppStartupKey;
private String mExitAfterCleanKey;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mCleanerService = ((CleanerService.CleanerServiceBinder) service).getService();
mCleanerService.setOnActionListener(CleanerFragment.this);
updateStorageUsage();
if (!mCleanerService.isCleaning() && !mCleanerService.isScanning()) {
if (mSharedPreferences.getBoolean(mCleanOnAppStartupKey, false) &&
!mAlreadyCleaned) {
mAlreadyCleaned = true;
cleanCache();
} else if (!mAlreadyScanned) {
mCleanerService.scanCache();
}
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mCleanerService.setOnActionListener(null);
mCleanerService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
mSortByKey = getString(R.string.sort_by_key);
mCleanOnAppStartupKey = getString(R.string.clean_on_app_startup_key);
mExitAfterCleanKey = getString(R.string.exit_after_clean_key);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mAppsListAdapter = new AppsListAdapter();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.cleaning_cache);
mProgressDialog.setMessage(getString(R.string.cleaning_in_progress));
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return true;
}
});
getActivity().getApplication().bindService(new Intent(getActivity(), CleanerService.class),
mServiceConnection, Context.BIND_AUTO_CREATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleaner_fragment, container, false);
mEmptyView = (TextView) rootView.findViewById(R.id.empty_view);
mLayoutManager = new LinearLayoutManager(getActivity());
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAppsListAdapter);
recyclerView.setEmptyView(mEmptyView);
recyclerView.addItemDecoration(new DividerDecoration(getActivity()));
mProgressBar = rootView.findViewById(R.id.progressBar);
mProgressBarText = (TextView) rootView.findViewById(R.id.progressBarText);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
mOptionsMenu = menu;
inflater.inflate(R.menu.main_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
mSearchQuery = query;
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (ViewCompat.isLaidOut(searchView) && mSearchQuery != null) {
String oldText = mSearchQuery;
mSearchQuery = newText;
if (!oldText.equals(newText)) {
mAppsListAdapter.sortAndFilter(getActivity(), getSortBy(), newText);
}
}
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
if (mSearchQuery == null) {
mSearchQuery = "";
}
mAppsListAdapter.setShowHeaderView(false);
mEmptyView.setText(R.string.no_such_app);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mSearchQuery = null;
mAppsListAdapter.clearFilter();
mAppsListAdapter.setShowHeaderView(true);
if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
mLayoutManager.scrollToPosition(0);
}
mEmptyView.setText(R.string.empty_cache);
return true;
}
});
if (mSearchQuery != null) {
MenuItemCompat.expandActionView(searchItem);
searchView.setQuery(mSearchQuery, false);
}
updateOptionsMenu();
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clean:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning() && mCleanerService.getCacheSize() > 0) {
mAlreadyCleaned = false;
cleanCache();
}
return true;
case R.id.action_refresh:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mCleanerService.scanCache();
}
return true;
case R.id.action_settings:
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
case R.id.action_sort_by_app_name:
setSortBy(AppsListAdapter.SortBy.APP_NAME);
updateOptionsMenu();
return true;
case R.id.action_sort_by_cache_size:
setSortBy(AppsListAdapter.SortBy.CACHE_SIZE);
updateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
updateOptionsMenu();
}
#Override
public void onDestroyOptionsMenu() {
mOptionsMenu = null;
}
#Override
public void onResume() {
updateStorageUsage();
updateOptionsMenu();
if (mCleanerService != null) {
if (mCleanerService.isScanning() && !isProgressBarVisible()) {
showProgressBar(true);
} else if (!mCleanerService.isScanning() && isProgressBarVisible()) {
showProgressBar(false);
}
if (mCleanerService.isCleaning() && !mProgressDialog.isShowing()) {
mProgressDialog.show();
}
}
super.onResume();
}
#Override
public void onPause() {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
super.onPause();
}
#Override
public void onDestroy() {
getActivity().getApplication().unbindService(mServiceConnection);
super.onDestroy();
}
private void updateOptionsMenu() {
if (mOptionsMenu != null) {
mOptionsMenu.findItem(R.id.action_sort_by_app_name).setVisible(
getSortBy() == AppsListAdapter.SortBy.CACHE_SIZE);
mOptionsMenu.findItem(R.id.action_sort_by_cache_size).setVisible(
getSortBy() == AppsListAdapter.SortBy.APP_NAME);
}
}
private void updateStorageUsage() {
if (mAppsListAdapter != null) {
StatFs stat = new StatFs(Environment.getDataDirectory().getAbsolutePath());
long totalMemory = (long) stat.getBlockCount() * (long) stat.getBlockSize();
long medMemory = mCleanerService != null ? mCleanerService.getCacheSize() : 0;
long lowMemory = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB &&
!Environment.isExternalStorageEmulated()) {
stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
totalMemory += (long) stat.getBlockCount() * (long) stat.getBlockSize();
lowMemory += (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
long highMemory = totalMemory - medMemory - lowMemory;
mAppsListAdapter.updateStorageUsage(totalMemory, lowMemory, medMemory, highMemory);
}
}
private AppsListAdapter.SortBy getSortBy() {
try {
return AppsListAdapter.SortBy.valueOf(mSharedPreferences.getString(mSortByKey,
AppsListAdapter.SortBy.CACHE_SIZE.toString()));
} catch (ClassCastException e) {
return AppsListAdapter.SortBy.CACHE_SIZE;
}
}
private void setSortBy(AppsListAdapter.SortBy sortBy) {
mSharedPreferences.edit().putString(mSortByKey, sortBy.toString()).apply();
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mAppsListAdapter.sortAndFilter(getActivity(), sortBy, mSearchQuery);
}
}
private boolean isProgressBarVisible() {
return mProgressBar.getVisibility() == View.VISIBLE;
}
private void showProgressBar(boolean show) {
if (show) {
mProgressBar.setVisibility(View.VISIBLE);
} else {
mProgressBar.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_out));
mProgressBar.setVisibility(View.GONE);
}
}
private void showStorageRationale() {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
dialog.setTitle(R.string.rationale_title);
dialog.setMessage(getString(R.string.rationale_storage));
dialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private void cleanCache() {
if (!CleanerService.canCleanExternalCache(getActivity())) {
if (shouldShowRequestPermissionRationale(PERMISSIONS_STORAGE[0])) {
showStorageRationale();
} else {
requestPermissions(PERMISSIONS_STORAGE, REQUEST_STORAGE);
}
} else {
mCleanerService.cleanCache();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_STORAGE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCleanerService.cleanCache();
} else {
showStorageRationale();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onScanStarted(Context context) {
if (isAdded()) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mProgressBarText.setText(R.string.scanning);
showProgressBar(true);
}
}
#Override
public void onScanProgressUpdated(Context context, int current, int max) {
if (isAdded()) {
mProgressBarText.setText(getString(R.string.scanning_m_of_n, current, max));
}
}
#Override
public void onScanCompleted(Context context, List<AppsListItem> apps) {
mAppsListAdapter.setItems(getActivity(), apps, getSortBy(), mSearchQuery);
if (isAdded()) {
updateStorageUsage();
showProgressBar(false);
}
mAlreadyScanned = true;
}
#Override
public void onCleanStarted(Context context) {
if (isAdded()) {
if (isProgressBarVisible()) {
showProgressBar(false);
}
if (!getActivity().isFinishing()) {
mProgressDialog.show();
}
}
}
#Override
public void onCleanCompleted(Context context, boolean succeeded) {
if (succeeded) {
mAppsListAdapter.trashItems();
}
if (isAdded()) {
updateStorageUsage();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
Toast.makeText(context, succeeded ? R.string.cleaned : R.string.toast_could_not_clean,
Toast.LENGTH_LONG).show();
if (succeeded && getActivity() != null && !mAlreadyCleaned &&
mSharedPreferences.getBoolean(mExitAfterCleanKey, false)) {
getActivity().finish();
}
}
}
It looks like there is an additional freeStorage() method added in Android 6 (Marshmallow) that takes an additional volumeUuid parameter:
public void freeStorage(long freeStorageSize, IntentSender pi)
public abstract void freeStorage(String volumeUuid, long freeStorageSize,
IntentSender pi)
Obviously, the new method is showing up first in the returned list of declared methods.
To get around this, you can alter the orginal code so that it looks like this:
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
Class[] params = m.getParameterTypes();
if (params.length == 2) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
}