I need to create 3 custom Cordova WebView using Cordova Android 5.1.0. Previously I have succeeded to create custom WebView using Cordova Android 2.7 by modifying/overwriting file platform/android/src/com/hello/helloapp.java. Below is my previous code:
package com.hello.helloapp;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import com.hello.helloapp.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class HelloApp extends Activity implements CordovaInterface {
int SCREEN_WIDTH;
int SCREEN_HEIGHT;
static String parentUrl;;
CordovaWebView view2;
CordovaWebView view1;
CordovaWebView view3;
static String htmlStr;
LinearLayout layout;
boolean connectionStatus;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Config.init(this);
this.getScreenSize();
view1 = (CordovaWebView) findViewById(R.id.local_web_view);
view1.loadUrl("file:///android_asset/www/index.html");
view2 = (CordovaWebView) findViewById(R.id.external_web_view);
view2.loadUrl("http://google.com");
view2.requestFocus(WebView.FOCUS_DOWN);
view2.setWebViewClient(new MyWebViewClient(this, view2));
view3 = (CordovaWebView) findViewById(R.id.articles_web_view);
view3.loadUrl("file:///android_asset/www/articles.html");
view2.addJavascriptInterface(this, "GetHTML");
layout = (LinearLayout) findViewById(R.id.progressBar);
if (!isTabletDevice(this)) {
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (isAirplaneModeOn(this)) {
connectionStatus = false;
} else if (isNetworkOnline()) {
connectionStatus = true;
} else
connectionStatus = false;
System.out.println(connectionStatus);
if (!connectionStatus) {
view2.setVisibility(View.GONE);
view3.loadUrl("file:///android_asset/www/articles.html");
view3.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isNetworkOnline() {
boolean status = false;
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
NetworkInfo netInfo1 = cm.getNetworkInfo(1);
if ((netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
|| (netInfo1 != null && netInfo1.getState() == NetworkInfo.State.CONNECTED)) {
status = true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
System.out.println(status);
return status;
}
public static boolean isTabletDevice(Context activityContext) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
#SuppressWarnings("deprecation")
private static boolean isAirplaneModeOn(Context context)
throws SettingNotFoundException {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
#Override
public Activity getActivity() {
return this;
}
#Override
public ExecutorService getThreadPool() {
return threadPool;
}
public void getScreenSize() {
Display display = getWindowManager().getDefaultDisplay();
SCREEN_WIDTH = display.getWidth();
SCREEN_HEIGHT = display.getHeight();
}
public class MyWebViewClient extends CordovaWebViewClient {
private CordovaInterface cordova;
public MyWebViewClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
this.cordova = ctx;
}
#Override
public void onReceivedError(WebView arg0, int arg1, String arg2,
String arg3) {
arg0.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
}
public boolean shouldOverrideUrlLoading(final WebView view, String url) {
connectionStatus = isNetworkOnline();
System.out.println(connectionStatus);
if (connectionStatus) {
System.out.println("---------shouldoverride-------" + url);
if (url.contains(".pdf")&& !url.contains("originUrl")) {
System.out.println(HelloApp.htmlStr);
view1.loadUrl("javascript:downloadFile(\"" + url + "\",\""
+ HelloApp.htmlStr + "\",\"" + HelloApp.parentUrl
+ "\");");
return false;
} else if (url.contains("search?")
&& HelloApp.parentUrl
.equalsIgnoreCase("http://google.com/")) {
System.out.println("parenturl");
url = url.concat("&showAll=false");
view2.loadUrl(url);
return false;
} else {
return false;
}
} else {
view1.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layout.setVisibility(View.VISIBLE);
if (url.contains(".pdf")) {
}else {
HelloApp.parentUrl = url;
if (view2.canGoBack() && view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1B_1\")");
} else if (view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1\")");
} else if (view2.canGoBack()) {
view1.loadUrl("javascript:callBackFun(\"B_1\")");
}
}
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains(".pdf")) {
} else {
System.out.println("----------------" + url);
view2.loadUrl("javascript: GetHTML.getHtml(document.body.innerHTML);");
view2.loadUrl("javascript: $(\".content-pricing\").hide()");
view2.loadUrl("javascript: $(\"a[href*='mailto']\").removeAttr('href');");
System.out.println("REMOVE------------------------>>>");
view2.loadUrl("javascript:$('head').append('<style>#coverImageUrl, .content-pricing, .price-disclaimer {display : none;}</style>')");
layout.setVisibility(View.INVISIBLE);
}
}
}
public Object onMessage(String arg0, Object arg1) {
return null;
}
#Override
public void setActivityResultCallback(CordovaPlugin arg0) {
}
#Override
public void startActivityForResult(CordovaPlugin arg0, Intent arg1, int arg2) {
}
#JavascriptInterface
public void getHtml(String html) {
this.htmlStr = html.replace("\"", "\'").replaceAll("\n", "").replaceAll("%22", "\'").trim();
}
}
Now there is lots of update in Cordova, they also update there CordovaWebView code. After updating Cordova Android version from 2.7 to 5.1.0, app is crashed. I tried to use SystemWebView instead of CordovaWebView but still get error and crashes as some of methods are missing in SystemWebView.
Please help how can I update previous WebView code or create new multiple WebView in Cordova 5.1.0.
Thanks!!
This is how I implemented new Cordova library in my existing project.
public class MyWebViewFragment extends Fragment{
private Activity mActivity;
private SystemWebView syswvPhoneWebview;
private CordovaWebView wvPhoneWebview;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity) context;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (mView == null) {
mView = inflater.inflate(R.layout.fragment_web_view, null);
setLayoutViews(mView);
}
return mView;
}
private void setLayoutViews(View mView) {
syswvPhoneWebview = (SystemWebView) mView.findViewById(R.id.wvPhoneWebview);
wvPhoneWebview = new CordovaWebViewImpl(new SystemWebViewEngine(syswvPhoneWebview));
wvPhoneWebview.init((CordovaInterface) getParentFragment(), parser.getPluginEntries(), parser.getPreferences());
syswvPhoneWebview.setWebContentsDebuggingEnabled(true);
syswvPhoneWebview.getSettings().setLoadsImagesAutomatically(true);
syswvPhoneWebview.getSettings().setJavaScriptEnabled(true);
syswvPhoneWebview.getSettings().setDomStorageEnabled(true);
syswvPhoneWebview.getSettings().setBuiltInZoomControls(true);
syswvPhoneWebview.getSettings().setSupportZoom(true);
wvPhoneWebview.loadUrl("www.google.com");
SystemWebViewEngine systemWebViewEngine = (SystemWebViewEngine) wvPhoneWebview.getEngine();
syswvPhoneWebview.setWebViewClient(new DocumentViewClient(systemWebViewEngine, mActivity));
}
}
now webviewclient code.
public class DocumentViewClient extends SystemWebViewClient {
private final Activity activity;
public DocumentViewClient(SystemWebViewEngine parentEngine, Activity activity) {
super(parentEngine);
this.activity = activity;
}
}
Related
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;
}
}
}
Been trying to load data from sqlite and display it on viewpager without much success.
I have a viewpager with two tabs which should hold data based on the tag_id passed as a parameter of newInstance. There is also an action bar navigation spinner with a list of counties that is used for filter data displayed based on the county_id.
Am able to fetch data from server and save it in the sqlite db but displaying it is the problem. Data is not dispalyed on the first page of the viewpager but it exists in the sqlite. Data for the second is the only one laoded.
Below is my implementation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.app.adapter.CustomCountySpinnerAdapter;
import com.app.adapter.TendersAdapter;
import com.app.database.DBFunctions;
import com.app.externallib.AppController;
import com.app.model.CountyModel;
import com.app.model.PostsModel;
import com.app.utils.AppConstants;
import com.app.utils.PostsListLoader;
import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter;
import com.viewpagerindicator.TabPageIndicator;
public class PublicTendersFragment extends Fragment{
private static List<PubliTenders> public_tenders;
public PublicTendersFragment newInstance(String text) {
PublicTendersFragment mFragment = new PublicTendersFragment();
Bundle mBundle = new Bundle();
mBundle.putString(AppConstants.TEXT_FRAGMENT, text);
mFragment.setArguments(mBundle);
return mFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public_tenders = new ArrayList<PubliTenders>();
public_tenders.add(new PubliTenders(14, "County"));
public_tenders.add(new PubliTenders(15, "National"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context contextThemeWrapper = new ContextThemeWrapper(
getActivity(), R.style.StyledIndicators);
LayoutInflater localInflater = inflater
.cloneInContext(contextThemeWrapper);
View v = localInflater.inflate(R.layout.fragment_tenders, container,
false);
FragmentPagerAdapter adapter = new TendersVPAdapter(
getFragmentManager());
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) v
.findViewById(R.id.indicator);
indicator.setViewPager(pager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
class TendersVPAdapter extends FragmentPagerAdapter{
public TendersVPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tenders.newInstance(public_tenders.get(position).tag_id);
case 1:
return Tenders.newInstance(public_tenders.get(position).tag_id);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return public_tenders.get(position).tender_type.toUpperCase(Locale
.getDefault());
}
#Override
public int getCount() {
return public_tenders.size();
}
}
public class PubliTenders {
public int tag_id;
public String tender_type;
public PubliTenders(int tag_id, String tender_type) {
this.tag_id = tag_id;
this.tender_type = tender_type;
}
}
public static class Tenders extends ListFragment implements
OnNavigationListener, LoaderCallbacks<ArrayList<PostsModel>> {
boolean mDualPane;
int mCurCheckPosition = 0;
// private static View rootView;
private SwipeRefreshLayout swipeContainer;
private ListView lv;
private View rootView;
private DBFunctions mapper;
private CustomCountySpinnerAdapter spinadapter;
private TendersAdapter mTendersAdapter;
private static final String ARG_TAG_ID = "tag_id";
private int tag_id;
private int mycounty;
private static final int INITIAL_DELAY_MILLIS = 500;
private static final String DEBUG_TAG = "BlogsFragment";
private final String TAG_REQUEST = "BLOG_TAG";
private JsonArrayRequest jsonArrTendersRequest;
// private OnItemSelectedListener listener;
public static Tenders newInstance(int tag_id) {
Tenders fragment = new Tenders();
Bundle b = new Bundle();
b.putInt(ARG_TAG_ID, tag_id);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag_id = getArguments().getInt(ARG_TAG_ID);
}
#Override
public void onStart() {
super.onStart();
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_headlines_blog,
container, false);
swipeContainer = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipeProjectsContainer);
lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (lv == null || lv
.getChildCount() == 0) ? 0 : lv.getChildAt(0)
.getTop();
swipeContainer.setEnabled(topRowVerticalPosition >= 0);
}
});
swipeContainer.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
fetchPublicTenders(mycounty);
}
});
swipeContainer.setColorSchemeResources(R.color.blue_dark,
R.color.irdac_green, R.color.red_light,
R.color.holo_red_light);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mapper = new DBFunctions(getActivity());
mapper.open();
// initialize AB Spinner
populateSpinner();
fetchPublicTenders(mycounty);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
private void populateSpinner() {
try {
List<CountyModel> counties = new ArrayList<CountyModel>();
counties = mapper.getAllCounties();
ActionBar actBar = ((ActionBarActivity) getActivity())
.getSupportActionBar();
actBar.setDisplayShowTitleEnabled(true);
actBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
spinadapter = new CustomCountySpinnerAdapter(getActivity(),
android.R.layout.simple_spinner_dropdown_item, counties);
actBar.setListNavigationCallbacks(spinadapter, this);
} catch (NullPointerException exp) {
}
}
#Override
public Loader<ArrayList<PostsModel>> onCreateLoader(int arg0,
Bundle arg1) {
Log.v(DEBUG_TAG, "On Create Loader");
return new PostsListLoader(getActivity(), mycounty, tag_id);
}
#Override
public void onLoadFinished(Loader<ArrayList<PostsModel>> arg0,
ArrayList<PostsModel> data) {
// System.out.println("results " + data.size());
addToAdapter(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<PostsModel>> arg0) {
lv.setAdapter(null);
}
#Override
public boolean onNavigationItemSelected(int pos, long arg1) {
CountyModel mo = spinadapter.getItem(pos);
this.mycounty = mo.getId();
refresh(mo.getId());
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextView txtTitle = (TextView) v.findViewById(R.id.tender_title);
TextView txtRefNo = (TextView) v.findViewById(R.id.ref_no);
TextView txtExpiryDate = (TextView) v
.findViewById(R.id.expiry_date);
TextView txtOrg = (TextView) v.findViewById(R.id.dept_or_org);
Intent intTenderFullDetails = new Intent(getActivity(),
TenderDetailsActivity.class);
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_TITLE,
txtTitle.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_REF_NO,
txtRefNo.getText().toString().trim());
intTenderFullDetails.putExtra(
TenderDetailsActivity.TENDER_EXPIRY_DATE, txtExpiryDate
.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_ORG,
txtOrg.getText().toString().trim());
// intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_DESC,
// Lorem);
startActivity(intTenderFullDetails);
}
private void fetchPublicTenders(final int county_id) {
swipeContainer.setRefreshing(true);
Uri.Builder builder = Uri.parse(AppConstants.postsUrl).buildUpon();
builder.appendQueryParameter("tag_id", Integer.toString(tag_id));
System.out.println("fetchPublicTenders with tag_id " + tag_id
+ " and county_id " + county_id);
jsonArrTendersRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject tender_item = response
.getJSONObject(i);
mapper.createPost(
tender_item.getInt("id"),
tender_item.getInt("tag_id"),
tender_item.getInt("county_id"),
tender_item.getInt("sector_id"),
tender_item.getString("title"),
tender_item.getString("slug"),
tender_item.getString("content"),
tender_item
.getString("reference_no"),
tender_item
.getString("expiry_date"),
tender_item
.getString("organization"),
tender_item
.getString("image_url"),
tender_item
.getString("created_at"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
refresh(county_id);
}
} else {
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
try {
Toast.makeText(getActivity(),
"Sorry! No results found",
Toast.LENGTH_LONG).show();
} catch (NullPointerException npe) {
System.out.println(npe);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
try {
Toast.makeText(
getActivity(),
"Network Error. Cannot refresh list",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
refresh(county_id);
} else if (error instanceof ServerError) {
try {
Toast.makeText(
getActivity(),
"Problem Connecting to Server. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
try {
Toast.makeText(getActivity(),
"No Connection", Toast.LENGTH_SHORT)
.show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
} else if (error instanceof TimeoutError) {
try {
Toast.makeText(
getActivity()
.getApplicationContext(),
"Timeout Error. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
// Set a retry policy in case of SocketTimeout & ConnectionTimeout
// Exceptions. Volley does retry for you if you have specified the
// policy.
jsonArrTendersRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonArrTendersRequest.setTag(TAG_REQUEST);
AppController.getInstance().addToRequestQueue(jsonArrTendersRequest);
}
public void refresh(int county_id) {
Bundle b = new Bundle();
b.putInt("myconty", county_id);
if (isAdded()) {
getLoaderManager().restartLoader(0, b, this);
}
}
private void addToAdapter(ArrayList<PostsModel> plist) {
mTendersAdapter = new TendersAdapter(rootView.getContext(), plist);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
mTendersAdapter);
swingBottomInAnimationAdapter.setAbsListView(lv);
assert swingBottomInAnimationAdapter.getViewAnimator() != null;
swingBottomInAnimationAdapter.getViewAnimator()
.setInitialDelayMillis(INITIAL_DELAY_MILLIS);
setListAdapter(swingBottomInAnimationAdapter);
mTendersAdapter.notifyDataSetChanged();
}
}
}
And this is the PostsListLoader class
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.app.database.DBFunctions;
import com.app.model.PostsModel;
public class PostsListLoader extends AsyncTaskLoader<ArrayList<PostsModel>> {
private DBFunctions mapper;
private ArrayList<PostsModel> myPostsModel;
private int county_id;
private int tag_id;
public PostsListLoader(Context context, int county_id, int tag_id) {
super(context);
mapper = new DBFunctions(getContext());
mapper.open();
this.county_id = county_id;
this.tag_id = tag_id;
}
#Override
public ArrayList<PostsModel> loadInBackground() {
String query_string = AppConstants.KEY_COUNTY_ID + " = " + county_id
+ " AND " + AppConstants.KEY_TAG_ID + " = " + tag_id;
myPostsModel = mapper.getPosts(query_string);
return myPostsModel;
}
#Override
public void deliverResult(ArrayList<PostsModel> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<PostsModel> oldNews = data;
myPostsModel = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldNews' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldNews != null) {
onReleaseResources(oldNews);
}
}
/**
* Handles a request to start the Loader.
*/
#Override
protected void onStartLoading() {
if (myPostsModel != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(myPostsModel);
}
if (takeContentChanged() || myPostsModel == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(ArrayList<PostsModel> news) {
super.onCanceled(news);
// At this point we can release the resources associated with 'news'
// if needed.
onReleaseResources(news);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (myPostsModel != null) {
onReleaseResources(myPostsModel);
myPostsModel = null;
}
}
/**
* Helper function to take care of releasing resources associated with an
* actively loaded data set.
*/
protected void onReleaseResources(List<PostsModel> news) {
}
}
What could I be doing wrong?
Any help will be appreciated.
Thanks
I have many customview in the scrollview. I have implemented swipe feature on the the customview . When I swipe customview to left , scrollview also move vertical. I don't want scroll view to be moved vertical while swiping. I thing Action_Cancel event of touch is going to scrollview which I have to stop. I tried to stop it but it is not working .
Below is the
package com.AA.KK.customui;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.AA.ax4mobile.AAPreferences;
import com.AA.ax4mobile.Constants;
import com.AA.ax4mobile.Session;
import com.AA.ax4mobile.Utils;
import com.AA.ax4mobile.network.Network;
import com.AA.ax4mobile.network.NetworkResponseListener;
import com.AA.KK.R;
import com.AA.KK.activities.KKBaseActivity;
import com.AA.KK.activities.PDFViewerActivity;
public class MailLayout extends RelativeLayout implements OnClickListener, OnTouchListener,
GestureDetector.OnGestureListener {
private CheckBox checkBox;
private TextView title;
private TextView fileSize;
private ImageView fileIcon;
private ImageView tray;
private String url;
private String fileId;
private ViewGroup swipeView;
private boolean isPreview;
private boolean isSelected = true;
private GestureDetectorCompat mDetector;
private static final int SWIPE_OFFSET = 20;
private static final int ANIMATION_OFFSET= 30;
public MailLayout(Context context) {
super(context);
init(context);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
private void init(Context context) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.activity_mail_layout, this);
LayoutParams linLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setLayoutParams(linLayoutParam);
swipeView = (RelativeLayout) findViewById(R.id.swipe);
swipeView.setOnTouchListener(this);
title = (TextView) findViewById(R.id.file_name);
fileIcon = (ImageView) findViewById(R.id.file_image);
fileSize = (TextView) findViewById(R.id.file_size);
tray = (ImageView) findViewById(R.id.clickme);
tray.setOnClickListener(this);
checkBox = (CheckBox) findViewById(R.id.chk_checkBox);
mDetector = new GestureDetectorCompat(Utils.getInstance().getContext(), this);
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public boolean isPreview() {
return isPreview;
}
public void setPreview(boolean isPreview) {
this.isPreview = isPreview;
}
public ViewGroup getSwipeView() {
return swipeView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public void setTitleText(String text) {
title.setText(text);
}
public String getTitleText() {
return (String) title.getText();
}
public void setFileSize(String text) {
fileSize.setText(text);
}
public void setChecked(boolean checked) {
checkBox.setChecked(checked);
}
public boolean getChecked() {
return checkBox.isChecked();
}
public void setFileIcon(String fileName) {
if (fileName.contains(".pdf") || fileName.contains(".PDF")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_pdf_selected);
} else if (fileName.contains(".docx") || fileName.contains(".DOCX")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_docx_selected);
} else if (fileName.contains(".doc") || fileName.contains(".DOC")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_doc_selected);
} else if (fileName.contains(".ppt") || fileName.contains(".PPT")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_ppt_selected);
} else if (fileName.contains(".pptx") || fileName.contains(".PPTX")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_pptx_selected);
} else if (fileName.contains(".png") || fileName.contains(".PNG")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_png_selected);
} else if (fileName.contains(".gif") || fileName.contains(".GIF")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_gif_selected);
} else if (fileName.contains(".csv") || fileName.contains(".CSV")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_csv_selected);
} else if (fileName.contains(".bmp") || fileName.contains(".BMP")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_bmp_selected);
} else if (fileName.contains(".txt") || fileName.contains(".TXT")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_txt_selected);
} else if (fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".JPG")
|| fileName.contains(".JPEG")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_jpg_selected);
} else if (fileName.contains(".xls") || fileName.contains(".XLS")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_xls_selected);
} else if (fileName.contains(".xlsx") || fileName.contains(".XLXS")) {
fileIcon.setBackgroundResource(R.drawable.ic_file_xlsx_selected);
} else {
fileIcon.setBackgroundResource(R.drawable.ic_file_selected);
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener) {
checkBox.setOnCheckedChangeListener(listener);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clickme:
doAddToTray(getFileId());
break;
}
}
public void setFileId(String fileId) {
this.fileId = fileId;
// TODO Auto-generated method stub
}
public String getFileId() {
return fileId;
}
public static void dismissProgress() {
Message msg = new Message();
msg.what = Constants.UIMSG_HIDE_PROGRESSDIALOG;
Bundle data = new Bundle();
data.putStringArray("caller", Utils.getInstance().getStackTraceArray());
msg.setData(data);
Session.getInstance().getMsgHandler().sendMessage(msg);
}
public static void showProgress() {
String message = Utils.getInstance().getContext().getString(R.string.loading);
Message msg = new Message();
msg.what = Constants.UIMSG_SHOW_PROGRESSDIALOG;
Bundle data = new Bundle();
data.putString("message", message);
data.putStringArray("caller", Utils.getInstance().getStackTraceArray());
msg.setData(data);
Session.getInstance().getMsgHandler().sendMessage(msg);
}
public static void doAddToTray(final String ids) {
AAPreferences settings = AAPreferences.getPreferences(Utils.getInstance().getContext());
String accToken = settings.getString(Constants.REQUEST_KEY_ACCESS_TOKEN, null);
String servername = settings.getString(Constants.REQUEST_KEY_SERVERNAME, null);
JSONObject req = new JSONObject();
Network net = Network.getInstance();
try {
req.accumulate(Constants.REQUEST_KEY_ACCESS_TOKEN, accToken);
req.accumulate(Constants.REQUEST_KEY_SERVERNAME, servername);
req.accumulate(Constants.REQUEST_KEY_ID, ids);
req.accumulate(Constants.REQUEST_KEY_PARENT_ID, "");
showProgress();
NetworkResponseListener listener = new NetworkResponseListener() {
#Override
public void handleSuccessResponse(List<NameValuePair> request, JSONObject response, boolean cancelflag) {
dismissProgress();
Toast.makeText(Utils.getInstance().getContext(), R.string.file_added_to_move_tray,
Toast.LENGTH_LONG).show();
String count = null;
try {
JSONObject json = response.getJSONObject("payload");
count = json.getString("total_count");
if (!TextUtils.isEmpty(count))
Utils.getInstance().saveTrayCount(count);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(Constants.ACTION_UPDATE_TRAY);
LocalBroadcastManager.getInstance(Utils.getInstance().getContext()).sendBroadcast(intent);
}
#Override
public void handleErrorResponse(List<NameValuePair> request, JSONObject response, boolean cancelflag) {
dismissProgress();
String count = null;
try {
JSONObject json = response.getJSONObject("payload");
count = json.getString("total_count");
Utils.getInstance().saveTrayCount(count);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(Constants.ACTION_UPDATE_TRAY);
LocalBroadcastManager.getInstance(Utils.getInstance().getContext()).sendBroadcast(intent);
Message msg = Network.defaultErrorManager(request, response);
if (msg != null) {
KKBaseActivity.defaultUIHandler.sendMessage(msg);
}
}
};
net.linkTray(req, listener);
} catch (JSONException e) {
e.printStackTrace();
}
};
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// TODO Auto-generated method stub
Log.e("onFling", "event"+e1.getAction());
if (swipeView.getX() > -(tray.getWidth() + SWIPE_OFFSET)) {
swipeView.animate().translationX(0).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
} else {
if (isPreview) {
swipeView.animate().translationX(0).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
} else {
swipeView.animate().translationX(-(tray.getWidth() + SWIPE_OFFSET)).alpha(1).setDuration(ANIMATION_OFFSET).setListener(null);
}
}
return false;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// TODO Auto-generated method stub
if (isSelected) {
if (swipeView.getX() <= 0)
swipeView.setX(e2.getX() - e1.getX() + swipeView.getX());
}
return true;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
String s = getUrl();
if (getUrl() == "" || getUrl() == null || getUrl().equalsIgnoreCase("null")) {
Toast.makeText(Utils.getInstance().getContext(), "File is not viewable", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(Utils.getInstance().getContext(), PDFViewerActivity.class);
intent.putExtra("filename", getTitleText());
intent.putExtra("view_url", getUrl());
intent.putExtra("preview_from_notification", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Utils.getInstance().getContext().startActivity(intent);
}
return true;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.e("onTouch", "event"+event.getAction());
boolean flag;
if (isPreview) {
tray.setVisibility(View.INVISIBLE);
} else {
tray.setVisibility(View.VISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
flag = onFling(event, event, 0f, 0f);
} else {
flag = mDetector.onTouchEvent(event);
}
return flag;
}
/* #Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.e("onTouchEvent", "event"+event.getAction());
return super.onTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev){
Log.e("dispatchTouchEvent", "event"+ev.getAction());
if(ev.getAction()== 3)
return false;
else
return super.dispatchTouchEvent(ev);
}*/
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
Log.e("onInterceptTouchEvent", "event"+ev.getAction());
return true;
}
}
in your onScroll()
put this -
ViewParent parent = getParent();
if(parent!= null){
parent.requestDisallowOnInterceptTouchEvent(true);
}
Hello everyone i got a question regarding how to enable full screen support in html embed videos on my webview i have hardware accelerated true on manifest and the video works ok but wen pressed to go fullscreen the video stops.
here is my code
import com.photoshop.video.tutorials.R;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebViewFragment extends Fragment {
public final static String TAG = WebViewFragment.class.getSimpleName();
private WebView viewContentWebView;
private String url;
private boolean resetHistory = true;
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.webview, container, false);
final ProgressBar viewContentProgress = (ProgressBar) v.findViewById(R.id.progress);
viewContentWebView = (WebView) v.findViewById(R.id.webview);
viewContentWebView.getSettings().setJavaScriptEnabled(true);
viewContentWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
viewContentWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
});
viewContentWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
viewContentProgress.setProgress(newProgress);
viewContentProgress.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
if (newProgress == 100 && resetHistory) {
viewContentWebView.clearHistory();
resetHistory = false;
}
}
});
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
reload();
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden)
viewContentWebView.stopLoading();
else
reload();
}
public void setUrl(String url) {
this.url = url;
if (viewContentWebView != null)
viewContentWebView.stopLoading();
resetHistory = true;
}
public void reload() {
if (TextUtils.isEmpty(url))
return;
viewContentWebView.loadUrl(url);
}
public boolean onBackPressed() {
if (viewContentWebView.canGoBack()) {
viewContentWebView.goBack();
return true;
}
return false;
}
}
How can i achieve this
many thanks in advance and a little patience with me because i am very very VERY new to android
You should override the two following methods in your WebChromeClient:
public void onShowCustomView(View view, CustomViewCallback callback);
public void onHideCustomView();
This is an extract of the code I'm using:
private View mCustomView;
private class MyWebChromeClient extends WebChromeClient {
private int mOriginalOrientation;
private FullscreenHolder mFullscreenContainer;
private CustomViewCallback mCustomViewCollback;
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mOriginalOrientation = mActivity.getRequestedOrientation();
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
mFullscreenContainer = new FullscreenHolder(mActivity);
mFullscreenContainer.addView(view, ViewGroup.LayoutParams.MATCH_PARENT);
decor.addView(mFullscreenContainer, ViewGroup.LayoutParams.MATCH_PARENT);
mCustomView = view;
mCustomViewCollback = callback;
mActivity.setRequestedOrientation(mOriginalOrientation);
}
#Override
public void onHideCustomView() {
if (mCustomView == null) {
return;
}
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
decor.removeView(mFullscreenContainer);
mFullscreenContainer = null;
mCustomView = null;
mCustomViewCollback.onCustomViewHidden();
// show the content view.
mActivity.setRequestedOrientation(mOriginalOrientation);
}
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
#Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}
I've adapted the code from AOSP "Launcher2" WallpaperChooser & WallpaperChooserDialogFragment to be a standalone Gallery App, and I wanted it to work on API levels 7 up to API 16.
To make it work for API levels < 11 I added the Android Support Library (rev.10) "Compability Package", V4 package.
I based my changes in the compability package (android.support.v4.app.DialogFragment.java) on the suggestions from here:
DialogFragments with devices api level < 11.
Otherwise the app would crash with an error ("DialogFragment can not be attached to a container view").
However, the app refuses to work as intended when deployed to an actual Jelly Bean 4.1.1 device (Nexus S), but it works perfectly fine on the emulator.
Tested & Works on:
Android 2.1 Emulator (API 7)
Android 2.2 Emulator (API 8)
Android 2.3.3 Emulator (API 10)
Android 4.0.3 Emulator (API 15)
Android 4.1 Emulator (API 16)
Android 2.3.7 Device (API 10)
Tested & Doesn't Work on:
Android 4.1.1 Device (API 16)
When running on the 4.1.1 device, it never loads/displays the gallery images when tapping on them in the horizontal view.
It only displays each picture after selecting and rotating the device, and then again, select a new picture, rotate again, and it displays correctly.
I haven't managed to figure out the problem why it wouldn't work on a real device so any help is appreciated.
If I remove the compability package and only targets API level +11, the app works on the real 4.1.1 device.
This is the code for the app:
GalleryDemo.java:
package gallery.android.demo;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
public class GalleryDemo extends FragmentActivity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.wallpaper_chooser_base);
Fragment fragmentView = getSupportFragmentManager().findFragmentById(R.id.wallpaper_chooser_fragment);
if (fragmentView == null) {
DialogFragment fragment = GalleryDemoDialogFragment.newInstance();
fragment.show(getSupportFragmentManager(), "dialog");
}
}
}
GalleryDemoDialogFragment.java:
package gallery.android.demo;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import java.util.ArrayList;
#SuppressWarnings("deprecation")
#TargetApi(16)
public class GalleryDemoDialogFragment extends DialogFragment implements AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String TAG = "GalleryDemoDialogFragment";
private static final String EMBEDDED_KEY = "gallery.android.demo.GalleryDemoDialogFragment.EMBEDDED_KEY";
private boolean mEmbedded;
private Bitmap mBitmap = null;
private ArrayList<Integer> mThumbs;
private ArrayList<Integer> mImages;
private WallpaperLoader mLoader;
private WallpaperDrawable mWallpaperDrawable = new WallpaperDrawable();
public static GalleryDemoDialogFragment newInstance() {
GalleryDemoDialogFragment fragment = new GalleryDemoDialogFragment();
fragment.setCancelable(true);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(EMBEDDED_KEY)) {
mEmbedded = savedInstanceState.getBoolean(EMBEDDED_KEY);
} else {
mEmbedded = isInLayout();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(EMBEDDED_KEY, mEmbedded);
}
private void cancelLoader() {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel(true);
mLoader = null;
}
}
#Override
public void onDetach() {
super.onDetach();
cancelLoader();
}
#Override
public void onDestroy() {
super.onDestroy();
cancelLoader();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
FragmentActivity activity = getActivity();
if (activity != null) {
activity.finish();
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
findWallpapers();
return null;
}
#TargetApi(16)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
findWallpapers();
if (mEmbedded) {
View view = inflater.inflate(R.layout.wallpaper_chooser, container, false);
switch (Build.VERSION.SDK_INT) {
case Build.VERSION_CODES.ICE_CREAM_SANDWICH :
view.setBackgroundDrawable(mWallpaperDrawable);
break;
case Build.VERSION_CODES.JELLY_BEAN :
view.setBackground(mWallpaperDrawable);
break;
default:
view.setBackgroundDrawable(mWallpaperDrawable);
break;
}
final Gallery gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setCallbackDuringFling(false);
gallery.setOnItemSelectedListener(this);
gallery.setAdapter(new ImageAdapter(getActivity()));
View setButton = view.findViewById(R.id.set);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int position = gallery.getSelectedItemPosition();
String[] wallpaperArray = getResources().getStringArray(R.array.wallpapers);
String name = wallpaperArray[position]+".jpg";
Log.i(TAG, "Position="+position);
Log.i(TAG, "Filename="+name);
Toast.makeText(getActivity().getApplicationContext(), "(Save2SD)\n"+
"Position="+position+"\n"+
"Filename="+name+
"", Toast.LENGTH_SHORT).show();
}
});
return view;
}
return null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel();
}
Log.d(TAG, "onItemSelected()");
mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private void findWallpapers() {
mThumbs = new ArrayList<Integer>(24);
mImages = new ArrayList<Integer>(24);
final Resources resources = getResources();
final String packageName = resources.getResourcePackageName(R.array.wallpapers);
addWallpapers(resources, packageName, R.array.wallpapers);
addWallpapers(resources, packageName, R.array.extra_wallpapers);
}
private void addWallpapers(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra + "_small", "drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
mImages.add(res);
}
}
}
}
private class ImageAdapter extends BaseAdapter implements ListAdapter, SpinnerAdapter {
private LayoutInflater mLayoutInflater;
ImageAdapter(FragmentActivity activity) {
mLayoutInflater = activity.getLayoutInflater();
}
public int getCount() {
return mThumbs.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
} else {
view = convertView;
}
ImageView iv = (ImageView) view.findViewById(R.id.wallpaper_image);
int thumbRes = mThumbs.get(position);
iv.setImageResource(thumbRes);
Drawable thumbDrawable = iv.getDrawable();
if (thumbDrawable != null) {
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error decoding thumbnail resId=" + thumbRes + " for wallpaper #" + position);
}
return view;
}
}
private class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
BitmapFactory.Options mOptions;
WallpaperLoader() {
mOptions = new BitmapFactory.Options();
mOptions.inDither = false;
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
#Override
protected Bitmap doInBackground(Integer... params) {
if (isCancelled()) return null;
try {
return BitmapFactory.decodeResource(getResources(), mImages.get(params[0]), mOptions);
} catch (OutOfMemoryError e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap b) {
if (b == null) return;
if (!isCancelled() && !mOptions.mCancel) {
if (mBitmap != null) {
mBitmap.recycle();
}
View v = getView();
if (v != null) {
Log.d(TAG, "WallpaperLoader.onPostExecute() getView != null");
mBitmap = b;
mWallpaperDrawable.setBitmap(b); // Doesn't appear to work on (physical) device with Jelly Bean (4.1.1)?
v.postInvalidate();
} else {
Log.d(TAG, "WallpaperLoader.onPostExecute(Bitmap b) getView == null");
mBitmap = null;
mWallpaperDrawable.setBitmap(null);
}
mLoader = null;
} else {
b.recycle();
}
}
void cancel() {
mOptions.requestCancelDecode();
super.cancel(true);
}
}
private static class WallpaperDrawable extends Drawable {
Bitmap mBitmap;
int mIntrinsicWidth;
int mIntrinsicHeight;
void setBitmap(Bitmap bitmap) {
Log.d(TAG, "WallpaperDrawable.setBitmap(Bitmap)");
mBitmap = bitmap;
if (mBitmap == null) {
Log.d(TAG, "WallpaperDrawable.setBitmap(Bitmap) mBitmap == null");
return;
}
mIntrinsicWidth = mBitmap.getWidth();
mIntrinsicHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
if (mBitmap == null) {
Log.d(TAG, "WallpaperDrawable.draw(Canvas) mBitmap == null");
return;
}
Log.d(TAG, "WallpaperDrawable.draw(Canvas)");
int width = canvas.getWidth();
int height = canvas.getHeight();
int x = (width - mIntrinsicWidth) / 2;
int y = (height - mIntrinsicHeight) / 2;
canvas.drawBitmap(mBitmap, x, y, null);
}
#Override
public int getOpacity() {
return android.graphics.PixelFormat.OPAQUE;
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
}
}
The real device running API 16 is the only device with hardware accelerated rendering, which is why it behaves differently. You can try setting android:hardwareAccelerated="false" in your activity's manifest entry to experiment with this.
You can leave acceleration on if you call invalidateSelf() when you change the content of a Drawable:
private static class WallpaperDrawable extends Drawable {
void setBitmap(Bitmap bitmap) {
. . .
invalidateSelf();
}
}