Green N White Screen issue in Camera activity Android - java

This bug is only on some devices.
Project scope:
Indoor navigation system used in malls/ships to locate shops.
It uses beacons to locate shops with bluetooth connection. It uses camera to show directions (arrow) image overlays.
In ArCameraActivity, half green screen shows up in camera preview.
code:
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.opengl.Matrix;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dagger.android.support.DaggerAppCompatActivity;
public class ARActivity extends DaggerAppCompatActivity implements SensorEventListener, LocationListener,
ActivityCompat.OnRequestPermissionsResultCallback, ARView {
private static boolean IS_NAVIGATION_CLICKED = false;
#Inject
ARPresenter presenter;
#BindView(R.id.img_clear)
ImageView imgClear;
#BindView(R.id.img_logout)
ImageView imgLogout;
#BindView(R.id.img_map)
ImageView imgMap;
#BindView(R.id.img_navigation)
ImageView imgNavigation;
final static String TAG = "ARActivity";
private SurfaceView surfaceView;
private FrameLayout cameraContainerLayout;
private AROverlayView arOverlayView;
private Camera camera;
private ARCamera arCamera;
private TextView tvCurrentLocation;
private SensorManager sensorManager;
private final static int REQUEST_CAMERA_PERMISSIONS_CODE = 11;
public static final int REQUEST_LOCATION_PERMISSIONS_CODE = 0;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute
private LocationManager locationManager;
public Location location;
boolean isGPSEnabled;
boolean isNetworkEnabled;
boolean locationServiceAvailable;
private ScanRegionsService scanRegionsService;
private boolean isBeaconLoaded = false;
// private static GetMallResponse.Data.Mall identifiedMall;
private Dialog dialog = null;
private static final String IMAGE_URL = "http://98.156.231.92/maps/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ar);
ButterKnife.bind(this);
sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
cameraContainerLayout = (FrameLayout) findViewById(R.id.camera_container_layout);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
tvCurrentLocation = (TextView) findViewById(R.id.tv_current_location);
arOverlayView = new AROverlayView(this);
scanRegionsService = new ScanRegionsService(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
beginService();
}
}
if (Util.getSelectedShop() != null) {
showLoading();
}
}
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
if (!isBeaconLoaded) {
Log.d(TAG, "run: "+ isBeaconLoaded);
dismissLoading();
if(!isFinishing()) {
new AlertDialog.Builder(ARActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("There is no beacon in your surroundings")
.setMessage("Are you sure you want to stop navigation?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.setSelectedShop(null);
finish();
}
})
.show();
}
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION) &&
grantResults[i] == PackageManager.PERMISSION_GRANTED) {
beginService();
} else if (permissions[i].equalsIgnoreCase(Manifest.permission.CAMERA) &&
grantResults[i] == PackageManager.PERMISSION_DENIED) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
}
private void beginService() {
isBeaconLoaded = false;
arOverlayView.registerReceiver();
scanRegionsService.setupSpaces();
scanRegionsService.startScanning();
onMallIdentified(Util.getSelectedMall());
new Handler().postDelayed(mRunnable, 10000);
}
#OnClick(R.id.img_map)
public void onMapClicked() {
arOverlayView.unregisterReceiver();
// Util.getRouteMap().clear();
Util.setSelectedShop(null);
// Intent intent = new Intent(this, MainActivity.class);
// startActivity(intent);
finish();
}
#OnClick(R.id.img_navigation)
public void onNavClicked() {
if (!IS_NAVIGATION_CLICKED) {
IS_NAVIGATION_CLICKED = true;
arOverlayView.showNavigationMap();
imgNavigation.setImageDrawable(getResources().getDrawable(R.drawable.navigation_on));
} else {
IS_NAVIGATION_CLICKED = false;
arOverlayView.hideNavigationMap();
imgNavigation.setImageDrawable(getResources().getDrawable(R.drawable.navigation_off));
}
}
#OnClick(R.id.img_logout)
public void onLogoutClicked() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to logout?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.set("authToken", "");
Intent intent = new Intent(ARActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onBackPressed() {
if(!((Activity) this).isFinishing()) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to exit the screen?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
#Override
public void onResume() {
super.onResume();
requestLocationPermission();
requestCameraPermission();
registerSensors();
initAROverlayView();
IntentFilter intentFilter = new IntentFilter(ForegroundScanService.ACTION_DEVICE_DISCOVERED);
registerReceiver(scanningBroadcastReceiver, intentFilter);
}
public void showClearMap() {
imgClear.setVisibility(View.VISIBLE);
}
public void hideClearMap() {
imgClear.setVisibility(View.GONE);
}
#OnClick(R.id.img_clear)
public void onClearClicked() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to stop navigation?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.setSelectedShop(null);
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onPause() {
unregisterReceiver(scanningBroadcastReceiver);
releaseCamera();
super.onPause();
}
public void requestCameraPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSIONS_CODE);
} else {
initARCameraView();
}
}
public void requestLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSIONS_CODE);
} else {
initLocationService();
}
}
public void initAROverlayView() {
if (arOverlayView.getParent() != null) {
((ViewGroup) arOverlayView.getParent()).removeView(arOverlayView);
}
cameraContainerLayout.addView(arOverlayView);
}
public void initARCameraView() {
reloadSurfaceView();
if (arCamera == null) {
arCamera = new ARCamera(this, surfaceView);
}
if (arCamera.getParent() != null) {
((ViewGroup) arCamera.getParent()).removeView(arCamera);
}
cameraContainerLayout.addView(arCamera);
arCamera.setKeepScreenOn(true);
initCamera();
}
private void initCamera() {
int numCams = Camera.getNumberOfCameras();
if (numCams > 0) {
try {
camera = Camera.open();
camera.startPreview();
arCamera.setCamera(camera);
} catch (RuntimeException ex) {
Toast.makeText(this, "Camera not found", Toast.LENGTH_LONG).show();
}
}
}
private void reloadSurfaceView() {
if (surfaceView.getParent() != null) {
((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
}
cameraContainerLayout.addView(surfaceView);
}
private void releaseCamera() {
if (camera != null) {
camera.setPreviewCallback(null);
camera.stopPreview();
arCamera.setCamera(null);
camera.release();
camera = null;
}
}
private void registerSensors() {
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
float[] rotationMatrixFromVector = new float[16];
float[] projectionMatrix = new float[16];
float[] rotatedProjectionMatrix = new float[16];
SensorManager.getRotationMatrixFromVector(rotationMatrixFromVector, sensorEvent.values);
if (arCamera != null) {
projectionMatrix = arCamera.getProjectionMatrix();
}
Matrix.multiplyMM(rotatedProjectionMatrix, 0, projectionMatrix, 0, rotationMatrixFromVector, 0);
this.arOverlayView.updateRotatedProjectionMatrix(rotatedProjectionMatrix);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
//do nothing
}
private void initLocationService() {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
this.locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
// Get GPS and network status
this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isNetworkEnabled && !isGPSEnabled) {
// cannot get location
this.locationServiceAvailable = false;
}
this.locationServiceAvailable = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateLatestLocation();
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateLatestLocation();
}
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
private void updateLatestLocation() {
if (arOverlayView != null && location != null) {
arOverlayView.updateCurrentLocation(location);
tvCurrentLocation.setText(String.format("lat: %s \nlon: %s \naltitude: %s \n",
location.getLatitude(), location.getLongitude(), location.getAltitude()));
}
}
#Override
public void onLocationChanged(Location location) {
updateLatestLocation();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private final BroadcastReceiver scanningBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: ");
isBeaconLoaded = true;
String shopname=Util.getSelectedShop().getShopImage();
Toast.makeText(context, "You are in "+shopname, Toast.LENGTH_LONG).show();
int devicesCount = intent.getIntExtra(BackgroundScanService.EXTRA_DEVICES_COUNT, 0);
RemoteBluetoothDevice device = intent.getParcelableExtra(BackgroundScanService.EXTRA_DEVICE);
Log.i("BEACON", String.format("Total discovered devices: %d\n\nLast scanned device:\n%s", devicesCount, device.toString()));
// statusText.setText(String.format("Total discovered devices: %d\n\nLast scanned device:\n%s", devicesCount, device.toString()));
}
};
#Override
public void onMallIdentified(GetMallResponse.Data.Mall mall) {
// identifiedMall = mall;
// Toast.makeText(this, "Identified "+mall.getPropertyName(), Toast.LENGTH_LONG).show();
presenter.loadShops(mall.getId());
presenter.loadRouteBeacons(mall.getId());
}
public void onUnkownPlaceIdentified() {
arOverlayView.registerReceiver();
Toast.makeText(this, "Unknown place identified", Toast.LENGTH_LONG).show();
List<GetRouteBeaconsResponse.Data.Route> floorRoute = new ArrayList<>();
}
#Override
public void onShopLoaded(List<GetShopsResponse.Data.Shop> shops) {
Log.i(TAG, "onShopLoaded");
if (shops.size() > 0) {
Util.shopMap.clear();
Log.i(TAG, "onShopLoaded shops.size " + shops.size());
Util.activeDeviceMap.clear();
for (GetShopsResponse.Data.Shop shop : shops) {
Util.shopMap.put("" + shop.getId(), shop);
if (shop.getAdImage().length() > 0) {
Drawable drbl = Util.promoImageMap.get(IMAGE_URL + shop.getAdImage());
if (drbl == null) {
String imgkey = IMAGE_URL + shop.getAdImage();
drbl = getResources().getDrawable(R.drawable.promo1, null);
Util.promoImageMap.put(imgkey, drbl);
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Drawable drb2 = drawableFromUrl(imgkey);
Util.promoImageMap.put(IMAGE_URL + shop.getAdImage(), drb2);
} catch (Exception e) {
Log.i(TAG, "Unable to download image");
}
}
};
new Thread(runnable).start();
}
}
}
}
}
#Override
public void onRouteBeaconLoaded(List<GetRouteBeaconsResponse.Data.Route> floors) {
Log.d(TAG, "onRouteBeaconLoaded: ");
Log.i(TAG, "onRouteBeaconLoaded");
// if (floors.size()>0 && Util.getSelectedShop()!=null){
// Log.i(TAG, "onRouteBeaconLoaded floors.size "+floors.size());
// Util.getRouteMap().clear();
// for (GetRouteBeaconsResponse.Data.Route route: floors){
// String comkey = route.proximityUUID+route.major+route.minor;
// Util.getRouteMap().put(comkey, route);
// }
// Util.setSelectedShop(Util.getSelectedShop());
// Log.i(TAG, "onShopLoaded setup space scanRegionsService");
// scanRegionsService.setupSpaces();
// Log.i(TAG, "onShopLoaded startScanning");
// scanRegionsService.startScanning();
// }
if (floors.size() > 0) {
Log.i(TAG, "onRouteBeaconLoaded floors.size " + floors.size());
Util.getRouteMap().clear();
for (GetRouteBeaconsResponse.Data.Route route : floors) {
String comkey = route.proximityUUID + route.major + route.minor;
Util.getRouteMap().put(comkey, route);
}
Log.i(TAG, "onShopLoaded setup space scanRegionsService");
scanRegionsService.setupSpaces();
Log.i(TAG, "onShopLoaded startScanning");
scanRegionsService.startScanning();
}
arOverlayView.registerReceiver();
}
public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
private void initLoadingDialog() {
dialog = new Dialog(this);
dialog.setCancelable(false);
dialog.setContentView(R.layout.show_loading);
TextView txtFind = dialog.findViewById(R.id.findingBeacons);
txtFind.setVisibility(View.VISIBLE);
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss();
}
return true;
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
public void showLoading() {
try {
if (dialog != null) {
dialog.show();
} else {
initLoadingDialog();
dialog.show();
}
} catch (Exception e) {
}
}
public void dismissLoading() {
try {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
}
green screen
Getting like this for camera activity in redmi y2 phone only. Its works well on other models. What might be issue? It shows directions in camera to shop using beacon device. Android os version is not problem.
white screen on some devices - samsung tab, oneplus 7, BLU G9 Pro phone
white screen
this activity shows navigation with help of beacons in camera shows overlay of imageview. it works on some devices, i have tried various methods to resolve it,
doesn't work. added latest camera v2 api.
How can i resolve this issue? thanks in advance.

Sometimes this "green screen" issue is caused by the camera's preview resolution. Try to get supported preview size from camera instance.
mParams = mCamera.getParameters();
List<Camera.Size> supportedPreviewSizes = mParams.getSupportedPreviewSizes();
Camera.Size bestPreviewSize = supportedPreviewSizes.get(0);
for (Camera.Size sz : supportedPreviewSizes) {
/* perfect match */
if(sz.width == mWidth && sz.height == mHeight) {
bestPreviewSize = sz;
break;
} else {
int bestArea = bestPreviewSize.width*bestPreviewSize.height;
int currArea = sz.width*sz.height;
int targetArea = mWidth*mHeight;
if (Math.abs(currArea-targetArea) < Math.abs(bestArea-targetArea)) {
bestPreviewSize = sz;
}
}
}
mCurrWidth = bestPreviewSize.width;
mCurrHeight = bestPreviewSize.height;
mParams.setPreviewSize(mCurrWidth, mCurrHeight);
/* Set preview format */
mParams.setPreviewFormat(ImageFormat.NV21);
/* Apply Parameters */
mCamera.setParameters(mParams);
mCamera.startPreview();
You can also try to force some fixed resolution depending on some device conditions, like display width, for example. Some resolutions i found useful on my use case:
width = 1280;
heigth = 720;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics windowMetrics = getWindowManager().getCurrentWindowMetrics();
if (isPortrait) {
if (windowMetrics.getBounds().width() <= 720) {
width = 720;
heigth = 480;
}
} else {
if (windowMetrics.getBounds().width() <= 1344) {
width = 960;
heigth = 540;
}
}
} else {
if (isPortrait) {
if (getDisplay().getWidth() <= 720) {
width = 720;
heigth = 480;
}
} else {
if (getDisplay().getWidth() <= 1344) {
width = 960;
heigth = 540;
}
}
}
Keep in mind that the best solution for me was getting the supported sizes to calculate the best preview size.

Related

How to open links in the corresponding page in webview android application and not in browser

I was tired of searching and trying months ago to try opening links in my webview app but not the browser. I hope I find a solution here.
if I add any links in my notifications, it only opens the application homepage.
I use onesignal to send push notification
This is my app class:
package com.drbrandat.grinta;
public class App extends MultiDexApplication {
private static final String ONESIGNAL_APP_ID = "4cda77cb-1587-4b27-b708-7a427b9c1b1b";
private String push_url = null;
#Override
public void onCreate() {
super.onCreate();
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
//OneSignal Push
OneSignal.initWithContext(this);
OneSignal.setAppId(String.valueOf(R.string.ONESIGNAL_APP_ID));
OneSignal.setNotificationOpenedHandler(new NotificationHandler());
}
private class NotificationHandler implements OneSignal.OSNotificationOpenedHandler {
#Override
public void notificationOpened(OSNotificationOpenedResult result) {
try {
JSONObject data = result.getNotification().getAdditionalData();
String webViewUrl = (data != null) ? data.optString("url", null) : null;
String browserUrl = result.getNotification().getLaunchURL();
if (webViewUrl != null || browserUrl != null) {
if (browserUrl != null) {
browserUrl = (browserUrl == null) ? webViewUrl : browserUrl;
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserUrl));
startActivity(browserIntent);
Log.v("INFO", "Received notification while app was on foreground or url for browser");
} else {
push_url = webViewUrl;
}
} else {
Intent mainIntent;
mainIntent = new Intent(App.this, MainActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
public synchronized String getPushUrl(){
String url = push_url;
push_url = null;
return url;
}
public synchronized void setPushUrl(String url){
this.push_url = url;
}
}
This is my main activity:
package com.drbrandat.grinta.activity;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.drbrandat.grinta.App;
import com.drbrandat.grinta.Config;
import com.drbrandat.grinta.R;
import com.drbrandat.grinta.adapter.NavigationAdapter;
import com.drbrandat.grinta.drawer.menu.Action;
import com.drbrandat.grinta.drawer.menu.MenuItemCallback;
import com.drbrandat.grinta.drawer.menu.SimpleMenu;
import com.drbrandat.grinta.fragment.WebFragment;
import com.drbrandat.grinta.util.ThemeUtils;
import com.drbrandat.grinta.widget.SwipeableViewPager;
import com.drbrandat.grinta.widget.webview.WebToAppWebClient;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.onesignal.OneSignal;
import com.tjeannin.apprate.AppRate;
public class MainActivity extends AppCompatActivity implements MenuItemCallback{
//Views
public Toolbar mToolbar;
public View mHeaderView;
public TabLayout mSlidingTabLayout;
public SwipeableViewPager mViewPager;
//App Navigation Structure
private NavigationAdapter mAdapter;
private NavigationView navigationView;
private SimpleMenu menu;
private WebFragment CurrentAnimatingFragment = null;
private int CurrentAnimation = 0;
//Identify toolbar state
private static int NO = 0;
private static int HIDING = 1;
private static int SHOWING = 2;
//Keep track of the interstitials we show
private int interstitialCount = -1;
private InterstitialAd mInterstitialAd;
// OneSignal
private static final String ONESIGNAL_APP_ID = "4cda77cb-1587-4b27-b708-7a427b9c1b1b";
ImageView previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
try {
WebFragment.notification_url = getIntent().getExtras().getString("Notification_url","");
}catch (Exception e){
WebFragment.notification_url = "";
}
ThemeUtils.setTheme(this);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mHeaderView = (View) findViewById(R.id.header_container);
mSlidingTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (SwipeableViewPager) findViewById(R.id.pager);
previous = (ImageView) findViewById(R.id.previous);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mAdapter = new NavigationAdapter(getSupportFragmentManager(), this);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
String data = intent.getDataString();
((App) getApplication()).setPushUrl(data);
}
//Hiding ActionBar/Toolbar
if (Config.HIDE_ACTIONBAR)
getSupportActionBar().hide();
if (getHideTabs())
mSlidingTabLayout.setVisibility(View.GONE);
hasPermissionToDo(this, Config.PERMISSIONS_REQUIRED);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
if ((Config.HIDE_ACTIONBAR && getHideTabs()) || ((Config.HIDE_ACTIONBAR || getHideTabs()) && getCollapsingActionBar())){
lp.topMargin = 0;
} else if ((Config.HIDE_ACTIONBAR || getHideTabs()) || (!Config.HIDE_ACTIONBAR && !getHideTabs() && getCollapsingActionBar())){
lp.topMargin = getActionBarHeight();
} else if (!Config.HIDE_ACTIONBAR && !getHideTabs()){
lp.topMargin = getActionBarHeight() * 2;
}
mViewPager.setLayoutParams(lp);
//Tabs
mViewPager.setAdapter(mAdapter);
mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount() - 1);
mSlidingTabLayout.setupWithViewPager(mViewPager);
mSlidingTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (getCollapsingActionBar()) {
showToolbar(getFragment());
}
mViewPager.setCurrentItem(tab.getPosition());
showInterstitial();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
for (int i = 0; i < mSlidingTabLayout.getTabCount(); i++) {
if (Config.ICONS.length > i && Config.ICONS[i] != 0) {
mSlidingTabLayout.getTabAt(i).setIcon(Config.ICONS[i]);
}
}
//Drawer
if (Config.USE_DRAWER) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DrawerLayout drawer = ((DrawerLayout) findViewById(R.id.drawer_layout));
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, 0, 0);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Menu items
navigationView = (NavigationView) findViewById(R.id.nav_view);
menu = new SimpleMenu(navigationView.getMenu(), this);
configureMenu(menu);
if (Config.HIDE_DRAWER_HEADER) {
navigationView.getHeaderView(0).setVisibility(View.GONE);
navigationView.setFitsSystemWindows(false);
} else {
if (Config.DRAWER_ICON != R.mipmap.ic_launcher)
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setImageResource(Config.DRAWER_ICON);
else {
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.launcher_icon)).setVisibility(View.VISIBLE);
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setVisibility(View.INVISIBLE);
}
}
} else {
((DrawerLayout) findViewById(R.id.drawer_layout)).setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//Admob
if (!getResources().getString(R.string.ad_banner_id).equals("")) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
adView.loadAd(adRequest);
} else {
AdView adView = (AdView) findViewById(R.id.adView);
adView.setVisibility(View.GONE);
}
if (getResources().getString(R.string.ad_interstitial_id).length() > 0 && Config.INTERSTITIAL_INTERVAL > 0){
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ad_interstitial_id));
AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
mInterstitialAd.loadAd(adRequestInter);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build());
}
});
}
//Application rating
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.rate_title))
.setMessage(String.format(getString(R.string.rate_message), getString(R.string.app_name)))
.setPositiveButton(getString(R.string.rate_yes), null)
.setNegativeButton(getString(R.string.rate_never), null)
.setNeutralButton(getString(R.string.rate_later), null);
new AppRate(this)
.setShowIfAppHasCrashed(false)
.setMinDaysUntilPrompt(2)
.setMinLaunchesUntilPrompt(2)
.setCustomDialog(builder)
.init();
//Showing the splash screen
if (Config.SPLASH) {
findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE);
findViewById(R.id.mmprogressbar).setVisibility(View.VISIBLE);
//getFragment().browser.setVisibility(View.GONE);
}
//Toolbar styling
if (Config.TOOLBAR_ICON != 0) {
getSupportActionBar().setTitle("");
ImageView imageView = findViewById(R.id.toolbar_icon);
imageView.setImageResource(Config.TOOLBAR_ICON);
imageView.setVisibility(View.VISIBLE);
if (!Config.USE_DRAWER){
imageView.setScaleType(ImageView.ScaleType.FIT_START);
}
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WebView browser = getFragment().browser;
browser.goBack();
}
});
}
// using the back button of the device
#Override
public void onBackPressed() {
View customView = null;
WebChromeClient.CustomViewCallback customViewCallback = null;
if (getFragment().chromeClient != null) {
customView = getFragment().chromeClient.getCustomView();
customViewCallback = getFragment().chromeClient.getCustomViewCallback();
}
if ((customView == null)
&& getFragment().browser.canGoBack()) {
getFragment().browser.goBack();
} else if (customView != null
&& customViewCallback != null) {
customViewCallback.onCustomViewHidden();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if(isHome){
previous.setVisibility(View.GONE);
inflater.inflate(R.menu.menu2, menu);
}else{
previous.setVisibility(View.VISIBLE);
inflater.inflate(R.menu.menu, menu);
}
//Adjust menu item visibility/availability based on settings
if (Config.HIDE_MENU_SHARE) {
menu.findItem(R.id.share).setVisible(false);
}
if (Config.HIDE_MENU_HOME) {
menu.findItem(R.id.home).setVisible(false);
}
if (Config.HIDE_MENU_NAVIGATION){
menu.findItem(R.id.previous).setVisible(false);
menu.findItem(R.id.next).setVisible(false);
}
if (!Config.SHOW_NOTIFICATION_SETTINGS || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
menu.findItem(R.id.notification_settings).setVisible(false);
}
ThemeUtils.tintAllIcons(menu, this);
return true;
}
//added
public static boolean isHome = true;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
WebView browser = getFragment().browser;
if (item.getItemId() == (R.id.next)) {
browser.goForward();
return true;
} else if (item.getItemId() == R.id.previous) {
browser.goBack();
return true;
} else if (item.getItemId() == R.id.share) {
getFragment().shareURL();
return true;
} else if (item.getItemId() == R.id.about) {
AboutDialog();
return true;
} else if (item.getItemId() == R.id.home) {
browser.loadUrl(getFragment().mainUrl);
return true;
} else if (item.getItemId() == R.id.close) {
finish();
Toast.makeText(getApplicationContext(),
getText(R.string.exit_message), Toast.LENGTH_SHORT).show();
return true;
} else if (item.getItemId() == R.id.notification_settings){
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
/**
* Showing the About Dialog
*/
private void AboutDialog() {
// setting the dialogs text, and making the links clickable
final TextView message = new TextView(this);
// i.e.: R.string.dialog_message =>
final SpannableString s = new SpannableString(
this.getText(R.string.dialog_about));
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setTextSize(15f);
int padding = Math.round(20 * getResources().getDisplayMetrics().density);
message.setPadding(padding, 15, padding, 15);
message.setText(Html.fromHtml(getString(R.string.dialog_about)));
message.setMovementMethod(LinkMovementMethod.getInstance());
// creating the actual dialog
AlertDialog.Builder AlertDialog = new AlertDialog.Builder(this);
AlertDialog.setTitle(Html.fromHtml(getString(R.string.about)))
// .setTitle(R.string.about)
.setCancelable(true)
// .setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton("ok", null).setView(message).create().show();
}
/**
* Set the ActionBar Title
* #param title title
*/
public void setTitle(String title) {
if (mAdapter != null && mAdapter.getCount() == 1 && !Config.USE_DRAWER && !Config.STATIC_TOOLBAR_TITLE)
getSupportActionBar().setTitle(title);
}
/**
* #return the Current WebFragment
*/
public WebFragment getFragment(){
return (WebFragment) mAdapter.getCurrentFragment();
}
/**
* Hide the Splash Screen
*/
public void hideSplash() {
if (Config.SPLASH) {
if (findViewById(R.id.imageLoading1).getVisibility() == View.VISIBLE) {
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
public void run() {
// hide splash image
findViewById(R.id.imageLoading1).setVisibility(
View.GONE);
}
// set a delay before splashscreen is hidden
}, Config.SPLASH_SCREEN_DELAY);
}
if (findViewById(R.id.mmprogressbar).getVisibility() == View.VISIBLE) {
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
public void run() {
// hide splash image
findViewById(R.id.mmprogressbar).setVisibility(
View.GONE);
}
// set a delay before splashscreen is hidden
}, Config.SPLASH_SCREEN_DELAY);
}
}
}
/**
* Hide the toolbar
*/
public void hideToolbar() {
if (CurrentAnimation != HIDING) {
CurrentAnimation = HIDING;
AnimatorSet animSetXY = new AnimatorSet();
ObjectAnimator animY = ObjectAnimator.ofFloat(getFragment().rl, "y", 0);
ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, "y", -getActionBarHeight());
animSetXY.playTogether(animY, animY1);
animSetXY.start();
animSetXY.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
CurrentAnimation = NO;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
/**
* Show the toolbar
* #param fragment for which to show the toolbar
*/
public void showToolbar(WebFragment fragment) {
if (CurrentAnimation != SHOWING || fragment != CurrentAnimatingFragment) {
CurrentAnimation = SHOWING;
CurrentAnimatingFragment = fragment;
AnimatorSet animSetXY = new AnimatorSet();
ObjectAnimator animY = ObjectAnimator.ofFloat(fragment.rl, "y", getActionBarHeight());
ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, "y", 0);
animSetXY.playTogether(animY, animY1);
animSetXY.start();
animSetXY.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
CurrentAnimation = NO;
CurrentAnimatingFragment = null;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
public int getActionBarHeight() {
int mHeight = mToolbar.getHeight();
//Just in case we get a unreliable result, get it from metrics
if (mHeight == 0){
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
mHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
}
return mHeight;
}
boolean getHideTabs(){
if (mAdapter.getCount() == 1 || Config.USE_DRAWER){
return true;
} else {
return Config.HIDE_TABS;
}
}
public static boolean getCollapsingActionBar(){
if (Config.COLLAPSING_ACTIONBAR && !Config.HIDE_ACTIONBAR){
return true;
} else {
return false;
}
}
/**
* Check permissions on app start
* #param context
* #param permissions Permissions to check
* #return if the permissions are available
*/
private static boolean hasPermissionToDo(final Activity context, final String[] permissions) {
boolean oneDenied = false;
for (String permission : permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ContextCompat.checkSelfPermission(context, permission)
!= PackageManager.PERMISSION_GRANTED)
oneDenied = true;
}
if (!oneDenied) return true;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.common_permission_explaination);
builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
context.requestPermissions(permissions,1);
}
});
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
/**
* Show an interstitial ad
*/
public void showInterstitial(){
if (interstitialCount == (Config.INTERSTITIAL_INTERVAL - 1)) {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
interstitialCount = 0;
} else {
interstitialCount++;
}
}
/**
* Configure the navigationView
* #param menu to modify
*/
public void configureMenu(SimpleMenu menu){
for (int i = 0; i < Config.TITLES.length; i++) {
//The title
String title = null;
Object titleObj = Config.TITLES[i];
if (titleObj instanceof Integer && !titleObj.equals(0)) {
title = getResources().getString((int) titleObj);
} else {
title = (String) titleObj;
}
//The icon
int icon = 0;
if (Config.ICONS.length > i)
icon = Config.ICONS[i];
menu.add((String) Config.TITLES[i], icon, new Action(title, Config.URLS[i]));
}
menuItemClicked(menu.getFirstMenuItem().getValue(), menu.getFirstMenuItem().getKey());
}
#Override
public void menuItemClicked(Action action, MenuItem item) {
if (WebToAppWebClient.urlShouldOpenExternally(action.url)){
//Load url outside WebView
try {
startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url)));
} catch(ActivityNotFoundException e) {
if (action.url.startsWith("intent://") || (action.url.startsWith("whatsapp:")
|| (action.url.startsWith("tel:")))){
startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace("intent://", "http://"))));
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace("whatsapp:", "http://")));
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace("tel:", "http://")));
} else {
Toast.makeText(this, getResources().getString(R.string.no_app_message), Toast.LENGTH_LONG).show();
}
}
} else {
//Uncheck all other items, check the current item
for (MenuItem menuItem : menu.getMenuItems())
menuItem.setChecked(false);
item.setChecked(true);
//Close the drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
//Load the url
if (getFragment() == null) return;
getFragment().browser.loadUrl("about:blank");
getFragment().setBaseUrl(action.url);
//Show intersitial if applicable
showInterstitial();
Log.v("INFO", "Drawer Item Selected");
}
}
}

java.util.List com.twitter.sdk.android.core.models.VideoInfo.variants' on a null object reference

I'm trying to build a twitter image, video, and gif downloader app on Android Studio.
*I'm able to download video and gif files but I'm unable to download images. It gives me an error when I put Twitter image URL in Edittext:
java.lang.NullPointerException: Attempt to read from field
'java.util.List
com.twitter.sdk.android.core.models.VideoInfo.variants' on a null
object reference
*The error in code : url = result.data.extendedEntities.media.get(0).videoInfo.variants.get(i).url; How can I achieve to download images from Twitter URL?
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.esafirm.rxdownloader.RxDownloader;
import com.shid.twittervideo.R;
import com.shid.twittervideo.util.Constant;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.DefaultLogger;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterConfig;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.core.services.StatusesService;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;
public class MainActivity extends AppCompatActivity {
private Button btn_download, btn_paste;
private ProgressDialog progressDialog;
private TextView txt_url;
private ClipboardManager clipboardManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUI();
btnClick();
checkPermission();
setTwitterConfig();
}
public void setTwitterConfig() {
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(Constant.TWITTER_KEY, Constant.TWITTER_SECRET))
.debug(true)
.build();
Twitter.initialize(config);
}
#SuppressLint("ClickableViewAccessibility")
public void setUI() {
btn_download = findViewById(R.id.btn_download);
txt_url = findViewById(R.id.txt_tweet_url);
btn_paste = findViewById(R.id.btn_paste);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Fetching video....");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
txt_url.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (txt_url.getRight() - txt_url.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
txt_url.setText("");
return true;
}
}
return false;
}
});
}
public void btnClick() {
btn_paste.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
CharSequence textToPaste = clipboardManager.getPrimaryClip().getItemAt(0).getText();
txt_url.setText(textToPaste);
} catch (Exception e) {
return;
}
}
});
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname;
//Check if the tweet url field has text containing twitter.com/...
if (txt_url.getText().length() > 0 && txt_url.getText().toString().contains("twitter.com/")) {
Long id = getTweetId(txt_url.getText().toString());
fname = String.valueOf(id);
//Call method to get tweet
if (id != null) {
getTweet(id, fname);
} else {
alertNoUrl();
}
} else{
alertNoUrl();
}
}
});
}
public void checkPermission() {
//If we don't have permission we prompt the user
if (!storageAllowed()) {
ActivityCompat.requestPermissions(this, Constant.PERMISSION_STRORAGE, Constant.REQUEST_EXTERNAL_STORAGE);
}
}
private void getTweet(Long id, String fname) {
progressDialog.show();
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
StatusesService statusesService = twitterApiClient.getStatusesService();
Call<Tweet> tweetCall = statusesService.show(id, null, null, null);
tweetCall.enqueue(new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
Log.d("MartianDeveloper", ""+result.data.extendedEntities.media.get(0).type);
//Check if media is present
if (result.data.extendedEntities == null && result.data.entities.media == null) {
alertNoMedia();
} else if (result.data.extendedEntities != null) {
if (!(result.data.extendedEntities.media.get(0).type).equals("video") &&
!(result.data.extendedEntities.media.get(0).type).equals("animated_gif") && !(result.data.extendedEntities.media.get(0).type).equals("photo")) {
alertNoVideo();
} else {
String filename = fname;
String url;
//Set filename to gif or mp4
if ((result.data.extendedEntities.media.get(0).type).equals("video") ||
(result.data.extendedEntities.media.get(0).type).equals("animated_gif")) {
filename = filename + ".mp4";
Log.d("TAG", "filenme for video is " + filename);
}else if ((result.data.extendedEntities.media.get(0).type).equals("photo")){
filename = filename + ".jpg";
}
int i = 0;
url = result.data.extendedEntities.media.get(0).videoInfo.variants.get(i).url;
Log.d("TAG", "url is " + url);
while (!url.contains(".mp4")) {
try {
if (result.data.extendedEntities.media.get(0).videoInfo.variants.get(i) != null) {
url = result.data.extendedEntities.media.get(0).videoInfo.variants.get(i).url;
Log.d("TAG", "url2 is " + url);
i += 1;
}
} catch (IndexOutOfBoundsException e) {
downloadVideo(url, filename);
}
}
downloadVideo(url, filename);
}
}
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(MainActivity.this, "Request failed, check your Internet connection", Toast.LENGTH_SHORT).show();
}
});
}
private void downloadVideo(String url, String filename) {
//Check if External Storage permission js allowed
if (!storageAllowed()) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(this, Constant.PERMISSION_STRORAGE, Constant.REQUEST_EXTERNAL_STORAGE);
progressDialog.hide();
Toast.makeText(this, "Kindly grant the request and try again", Toast.LENGTH_SHORT).show();
} else {
RxDownloader rxDownloader = new RxDownloader(MainActivity.this);
rxDownloader.download(url, filename, "video/*", true)
.subscribe(new Observer<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(String s) {
}
#Override
public void onError(Throwable e) {
Toast.makeText(MainActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete() {
Toast.makeText(MainActivity.this, "Download Complete", Toast.LENGTH_SHORT).show();
}
});
progressDialog.hide();
Toast.makeText(this, "Download Started: Check Notification", Toast.LENGTH_LONG).show();
}
}
private void alertNoVideo() {
progressDialog.hide();
Toast.makeText(this, "URL entered do not contain any video or gif", Toast.LENGTH_SHORT).show();
}
private void alertNoMedia() {
progressDialog.hide();
Toast.makeText(this, "The link entered do not contain any media", Toast.LENGTH_SHORT).show();
}
private Long getTweetId(String s) {
Log.d("TAG", "link is :" + s);
try {
String[] split = s.split("\\/");
String id = split[5].split("\\?")[0];
return Long.parseLong(id);
} catch (Exception e) {
Log.d("TAG", "getTweetId: " + e.getLocalizedMessage());
alertNoUrl();
return null;
}
}
private void alertNoUrl() {
Toast.makeText(this,getResources().getString(R.string.toast_url) , Toast.LENGTH_LONG).show();
}
//Method that checks the permission depending on the version of the phone
private boolean storageAllowed() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
return permission == PackageManager.PERMISSION_GRANTED;
}
return true;
}
}
I just put this code to retrieve the image result.data.extendedEntities.media.get(0).mediaUrl

How to remove the button after purchase

Please help!!!
I am creating a screen capture application and the problem is that after clicking the PRO button and after the purchase, the ads and the button do not hide.
I am trying to remove a button and ads using layout changes:
setContentView (R.layout.main_pro)
the code:
IabHelper.OnIabPurchaseFinishedListener () {
#Override
public void onIabPurchaseFinished (IabResult result, purchase purchase) {
if (result.isFailure ()) {
Log.d (TAG, "Purchase Error:" result);
return;
}
even if (purchase.getSku (). equals (SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView (R.layout.main_pro);
remove ads ();
Toast.makeText (MainActivity.this, “The purchase was successful,” Toast.LENGTH_LONG) .show ();
}
}
};
}
Full code:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.icu.text.SimpleDateFormat;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.ViewFlipper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.davidgrigoryan.screenrecorder.util.Constants;
import com.davidgrigoryan.screenrecorder.util.IabHelper;
import com.davidgrigoryan.screenrecorder.util.IabResult;
import com.davidgrigoryan.screenrecorder.util.Inventory;
import com.davidgrigoryan.screenrecorder.util.Purchase;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE = 1000;
private int mScreenDensity;
File file;
private Context context;
private ShareActionProvider mShareActionProvider;
private MediaProjectionManager mProjectionManager;
private static final int DISPLAY_WIDTH = 720;
private static final int DISPLAY_HEIGHT = 1280;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
static final String SKU_REMOVE_ADS = "android.test.purchased";
static final int RC_REQUEST = 10111;
private MediaProjectionCallback mMediaProjectionCallback;
private MediaRecorder mMediaRecorder;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final int REQUEST_PERMISSION_KEY = 1;
boolean isRecording = false;
private FloatingActionButton rec;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private Intent intent;
private Activity activity;
private boolean URL_TO_SHARE;
private ImageView wm;
private NotificationManagerCompat notificationManager;
private String title;
private String message;
private InterstitialAd mInterstitialAd;
private String testDeviceId;
AdRequest adRequest;
private AdView adView;
IabHelper mHelper;
String base64EncodedPublicKey = "PublicKey";
Boolean isAdsDisabled = false;
String payload = "Upgrade PRO";
private Inventory i;
private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
private static boolean isWidget = false;
private static Context appContext;
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView pro = (ImageView) findViewById(R.id.buy);
final SharedPreferences prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
pro.setVisibility(prefs.getBoolean("isPurchase", true) ? View.VISIBLE : View.INVISIBLE);
pro.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
purchaseRemoveAds();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Handler handler = new Handler();
final Timer timer = new Timer();
final TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 120000);
adView = (AdView) findViewById(R.id.adView);
adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-9842509861911521/3646081879");
AdRequest adRequestInterstitial = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest adRequestBanner = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
AdSize adSize = new AdSize(320, 50);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-9842509861911521/3646081879");
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-9842509861911521/1961271598");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
};
if (!Service.hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_KEY);
}
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mMediaRecorder = new MediaRecorder();
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
rec = (FloatingActionButton) findViewById(R.id.rec);
rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onToggleScreenShare();
}
});
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(false);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#Override
public void onIabSetupFinished(IabResult result, IabHelper.QueryInventoryFinishedListener mGotInventoryListener) throws IabHelper.IabAsyncInProgressException {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
return;
}
if (mHelper == null)
return;
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
queryPurchased();
IabHelper.OnIabPurchaseFinishedListener mPurchasedFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView(R.layout.main_pro);
removeAds();
Toast.makeText(MainActivity.this,"Purchase successful",Toast.LENGTH_LONG).show();
}
}
};
}
private void queryPurchased() {
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else{
// does the user have the premium upgrade?
isAdsDisabled = inventory.hasPurchase(SKU_REMOVE_ADS);
// update UI accordingly
}
}
};
}
public void purchaseRemoveAds() {
try {
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, SKU_REMOVE_ADS, 9, mPurchaseFinishedListener, "SECURITYSTRING");
} catch (Exception e) {
e.printStackTrace();
mHelper.flagEndAsync();
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.error)
.setMessage(R.string.error_play_store)
.setPositiveButton("OK", null)
.show();
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG, "Purchase finished: " + result + ", purchase: "
+ purchase);
if (mHelper == null)
return;
if (result.isFailure()) {
return;
}
if (!verifyDeveloperPayload(purchase)) {
return;
}
if (isAdsDisabled == true){
setContentView(R.layout.main_pro);
}
Log.d(TAG, "Purchase successful.");
if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
removeAds();
}
}
};
}
private void removeAds() {
adView.setEnabled(false);
adView.setVisibility(View.INVISIBLE);
}
public void onToggleScreenShare() {
if (!isRecording) {
Toast.makeText(getApplicationContext(), R.string.start_rec, Toast.LENGTH_LONG).show();
startService();
initRecorder();
shareScreen();
} else {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ads not loaded!");
}
Toast.makeText(getApplicationContext(), R.string.stop_rec, Toast.LENGTH_LONG).show();
stopService();
mMediaRecorder.stop();
mMediaRecorder.reset();
stopScreenSharing();
}
}
private void shareScreen() {
if (mMediaProjection == null) {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
return;
}
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
private VirtualDisplay createVirtualDisplay() {
return mMediaProjection.createVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
}
private void initRecorder() {
try {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //THREE_GPP
mMediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(16); // 30
mMediaRecorder.setVideoEncodingBitRate(3000000);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mMediaRecorder.setOrientationHint(orientation);
mMediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
private File initFile() {
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator + "ScreenRecorder");
if (!dir.exists() && !dir.mkdirs()) {
Log.wtf(TAG,
R.string.error_folder
+ dir.getAbsolutePath());
file = null;
} else {
file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
"'VIDEO-'yyyyMMddHHmmss'.mp4'").format(new Date()));
}
return file;
}
private void stopScreenSharing() {
if (mVirtualDisplay == null) {
return;
}
mVirtualDisplay.release();
destroyMediaProjection();
isRecording = false;
}
private void destroyMediaProjection() {
if (mMediaProjection != null) {
mMediaProjection.unregisterCallback(mMediaProjectionCallback);
mMediaProjection.stop();
mMediaProjection = null;
}
Log.i(TAG, "MediaProjection Stopped");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != REQUEST_CODE) {
Log.e(TAG, "Unknown request code: " + requestCode);
return;
}
if (resultCode != RESULT_OK) {
Toast.makeText(this, R.string.denied, Toast.LENGTH_SHORT).show();
isRecording = false;
return;
}
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
} else
Log.d(TAG, "onActivityResult handled by IABUtil.");
mMediaProjectionCallback = new MediaProjectionCallback();
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
mMediaProjection.registerCallback(mMediaProjectionCallback, null);
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_KEY: {
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
onToggleScreenShare();
} else {
isRecording = false;
Snackbar.make(findViewById(android.R.id.content), R.string.message,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.enable,
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}).show();
}
return;
}
}
}
private class MediaProjectionCallback extends MediaProjection.Callback {
#Override
public void onStop() {
if (isRecording) {
isRecording = false;
mMediaRecorder.stop();
mMediaRecorder.reset();
}
mMediaProjection = null;
stopScreenSharing();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onDestroy() {
if (mHelper != null)
try {
mHelper.dispose();
mHelper = null;
} catch (IabHelper.IabAsyncInProgressException e) {
e.printStackTrace();
}
if (adView != null) {
adView.destroy();
}
super.onDestroy();
destroyMediaProjection();
}
private void about() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle(R.string.about);
builder1.setMessage(R.string.description);
builder1.setCancelable(true);
builder1.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#SuppressLint("ResourceType")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
about();
return true;
case R.id.share:
shareApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void shareApp() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
#SuppressLint({"StringFormatInvalid", "LocalSuppress"})
String extraText = getString(R.string.share_desc, getString(R.string.link));
intent.putExtra(Intent.EXTRA_TEXT, extraText);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
public void startService() {
Intent serviceIntent = new Intent(this, Background.class);
serviceIntent.putExtra("inputExtra", "Notification");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, Background.class);
stopService(serviceIntent);
}
boolean verifyDeveloperPayload(Purchase p) {
String payload = p.getDeveloperPayload();
return true;
}
}
And it looks like this:
What am I doing wrong? How can I fix this?
Thanks for any help!

How do i make an repeat button that cycles through repeat all and repeat one for an android music player?

This is my code I have got repeat one working but I want to be able to repeat all songs so it does not stop playing the music, I also want to be able to repeat one single song. I have tried to find documentation to help me but I haven't found anything. Any help would be appreciated
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import static android.R.drawable.ic_media_play;
public class MainActivity extends Activity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 5000;
private static final int CALL = 872;
static MediaPlayer mp = null;
private final Handler handler = new Handler();
private TextView selectedFile;
private TextView selectedArtist;
private RecyclerView recyclerView;
private SeekBar seekbar;
private MediaPlayer player;
private ImageButton playButton;
private ImageButton prevButton;
private ImageButton nextButton;
private ImageButton repeatButton;
private ImageButton shuffleButton;
private boolean isStarted = true;
private int currentPosition;
private boolean isMovingSeekBar = false;
private MyRecyclerViewAdapter adapter;
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
private List<Music> musicList;
private boolean isShuffle = false;
private boolean isRepeat = false;
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentPosition);
}
}
break;
case R.id.prev:
startPlay(currentPosition - 1);
break;
case R.id.next:
startPlay(currentPosition + 1);
break;
case R.id.shuffle:
if (isShuffle) {
Collections.shuffle(musicList);
adapter.notifyDataSetChanged();
shuffleButton.setColorFilter(-16776961);
} else {
sortMusicList();
shuffleButton.setColorFilter(-16777216);
}
isShuffle = !isShuffle;
break;
case R.id.repeat: {
if (isRepeat) {
player.setLooping(true);
repeatButton.setImageResource(R.drawable.ic_repeat_black_24dp);
repeatButton.setColorFilter(-16776961);
} else {
player.setLooping(false);
repeatButton.setColorFilter(-16777216);
}
break;
}
}
}
};
private void sortMusicList() {
Collections.sort(musicList, new Comparator<Music>() {
#Override
public int compare(Music o1, Music o2) {
return o1.getArtists().compareTo(o2.getArtists());
}
});
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
startPlay(currentPosition + 1);
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChanged");
} else {
TextView duration = findViewById(R.id.song_duration);
duration.setText(String.valueOf(progress));
long totalSeconds = TimeUnit.MILLISECONDS.toSeconds(progress);
long minss = totalSeconds / 60;
long seconds = totalSeconds % 60;
duration.setText(String.format(Locale.UK, "%02d:%02d", minss, seconds));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
setupUI();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
CALL);
}
}
#Override
protected void onPause() {
super.onPause();
player.getCurrentPosition();
}
private void setupUI() {
selectedFile = findViewById(R.id.selected_file);
selectedArtist = findViewById(R.id.artists);
seekbar = findViewById(R.id.seekbar);
prevButton = findViewById(R.id.prev);
playButton = findViewById(R.id.play);
nextButton = findViewById(R.id.next);
repeatButton = findViewById(R.id.repeat);
shuffleButton = findViewById(R.id.shuffle);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
musicList = new MusicManager().getMusic(getContentResolver());
sortMusicList();
adapter = new MyRecyclerViewAdapter(musicList);
adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
startPlay(position);
}
});
recyclerView.setAdapter(adapter);
prevButton.setOnClickListener(onButtonClick);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
shuffleButton.setOnClickListener(onButtonClick);
repeatButton.setOnClickListener(onButtonClick);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(int position) {
if (position < 0) {
position = 0;
}
if (position >= musicList.size()) {
position = musicList.size() - 1;
}
String file = musicList.get(position).getFile();
String title = musicList.get(position).getTitle();
String artists = musicList.get(position).getArtists();
currentPosition = position;
if (artists != null) {
selectedArtist.setText(artists);
}
if (title != null) {
selectedFile.setText(title);
}
seekbar.setProgress(0);
updatePosition();
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
if (adapter == null) {
return;
}
}
}
this is just the main activity if you need anything else just ask.
To play a list of songs loop continuously, you can define a variable to be used as an index of the number of songs completed. After completion of the of the list, replay the list of songs by calling the index again. An example of this is:
int[] myAudio = {R.raw.audio1, R.raw.audio2, R.raw.audio3};
int mSongFinish = 0;
MediaPlayer mp = MediaPlayer.create(this, myAudio[0]);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mSongFinish++;
mp.reset();
if (mSongFinish < myAudio.length()) {
try {
AssetFileDescriptor asset = getResources().openRawResourceFd(myAudio[mSongFinish]);
if (asset != null) {
mp.setDataSource(afd.getFileDescriptor(), asset.getStartOffset(), asset.getLength());
asset.close();
mp.prepare();
}
} catch (Exception ex) {
// report a crash
}
} else {
mSongFinish=0;
mp.release();
mp = null; // either set counter to 0 and start again or call end of list
}
}
});
mp.start();
To do this on a button click, just use an onClickListener. To loop a single song on button click, use mp.setLooping(true).

Binary XML file line #41: Error inflating class com.facebook.login.widget.LoginButton

Getting an error while runtime how to resolve this plz help me out with as i am stucked in it i am a beginner
getting log cat error
Binary XML file line #41: Error inflating class com.facebook.login.widget.LoginButton
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_below="#id/signInText"
android:background="#drawable/facebook_connect"
/>
Home Activity
package com.styllonz.activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.google.gson.Gson;
import com.styllonz.R;
import com.styllonz.fragments.ForgotPasswordFragment;
import com.styllonz.fragments.LandingFragment;
import com.styllonz.fragments.LoginFragment;
import com.styllonz.fragments.SignUpFragment;
import com.styllonz.models.Response;
import com.styllonz.network.BusNetworkCallback;
import com.styllonz.network.WebserviceApi;
import com.styllonz.utils.Constants;
import com.styllonz.utils.Utilities;
import retrofit.RetrofitError;
public class HomeActivity extends FragmentActivity implements LandingFragment.OnFragmentInteractionListener,SignUpFragment.OnFragmentInteractionListener,
LoginFragment.OnFragmentInteractionListener, ForgotPasswordFragment.OnFragmentInteractionListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress, mSignInClicked;
ConnectionResult mConnectionResult;
ProgressDialog progress;
Context mContext;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_home);
if (savedInstanceState == null)
replaceFragment(LandingFragment.newInstance(), LandingFragment.TAG, false);
mSharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
mEditor=mSharedPreferences.edit();
mContext=this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
public void replaceFragment(Fragment fragment, String fragmentTag, boolean addToBackstack) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (addToBackstack)
fragmentManager.beginTransaction()
.replace(R.id.flFragmentHolder, fragment, fragmentTag).addToBackStack("")
.commit();
else
fragmentManager.beginTransaction()
.replace(R.id.flFragmentHolder, fragment, fragmentTag)
.commit();
}
#Override
public void onHomeFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cfbSignUp:
replaceFragment(SignUpFragment.newInstance(), SignUpFragment.TAG, true);
break;
case R.id.cfbLogin:
replaceFragment(LoginFragment.newInstance(), LoginFragment.TAG, true);
break;
}
}
#Override
public void onSignUpFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cftvSignUpTitle:
getSupportFragmentManager().popBackStackImmediate();
}
}
#Override
public void onLoginFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cftvForgotPassword:
replaceFragment(ForgotPasswordFragment.newInstance(), ForgotPasswordFragment.TAG, true);
break;
case R.id.cfbLogin:
Intent mainActivityIntent = new Intent(this, MainActivity.class);
startActivity(mainActivityIntent);
finish();
break;
case R.id.cftvLoginTitle:
getSupportFragmentManager().popBackStackImmediate();
}
}
#Override
public void onBackPressed() {
if (!getSupportFragmentManager().popBackStackImmediate())
super.onBackPressed();
}
#Override
public void onForgotPasswordFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cftvForgotPasswordTitle:
getSupportFragmentManager().popBackStackImmediate();
}
}
#Override
protected void onStart() {
super.onStart();
//
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
// Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
getProfileInformation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
if(progress!=null&&progress.isShowing())
progress.dismiss();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
resolveSignInError();
}
}
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode,responseCode,intent);
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
/**
* Sign-in into google
*/
public void signInWithGplus() {
if(Utilities.isOnline(this)) {
progress = ProgressDialog.show(this, "",
"Loading...", true);
if (!mSharedPreferences.contains(Constants.SHARED_PREFS_B_GMAIL_SOURCE)||!mGoogleApiClient.isConnected()) {
mSignInClicked = true;
if(mConnectionResult!=null)
resolveSignInError();
else
mGoogleApiClient.connect();
} else if(mGoogleApiClient.isConnected()){
getProfileInformation();
}
else if (mSharedPreferences.getBoolean(Constants.SHARED_PREFS_B_GMAIL_SOURCE, false)) {
login();
}
else {
if(progress!=null)
{
progress.dismiss();
}
}
}
else
{
Toast.makeText(this,"Please connect to internet",Toast.LENGTH_SHORT).show();
}
}
/**
* Method to resolve any signin errors
*/
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
/**
* Fetching user's information name, email, profile pic
*/
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
final Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(getClass().getSimpleName(), "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
final WebserviceApi webserviceApi=Utilities.getWebservice(mContext);
if(webserviceApi!=null)
{
webserviceApi.signupFromSource(email, personName, 'c', "google", "gmail", new BusNetworkCallback<Response>() {
#Override
public void onSuccess(Response obj) {
if (progress != null & progress.isShowing())
progress.dismiss();
Log.d(getClass().getSimpleName(), " success");
if (obj.getResult() != null && obj.getResult().equals("success")) {// Utilities.showAlertDialog(mContext,"Alert","User registered successfully.");
mEditor.putBoolean(Constants.SHARED_PREFS_B_GMAIL_SOURCE, true);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, email);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, currentPerson.getId());
mEditor.commit();
login();
} else if (obj.getError() != null && obj.getError().length() > 0) {
if (obj.getError().contains("Email")) {
mEditor.putBoolean(Constants.SHARED_PREFS_B_GMAIL_SOURCE, true);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, email);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, currentPerson.getId());
mEditor.commit();
login();
} else {
Utilities.showAlertDialog(mContext, "Error", obj.getError());
{
if (progress != null & progress.isShowing())
progress.dismiss();
}
}
} else {
Utilities.showAlertDialog(mContext, "Error", "Some error occured please try later");
{
if (progress != null & progress.isShowing())
progress.dismiss();
}
}
}
#Override
public void onFailure(RetrofitError error) {
if (progress != null & progress.isShowing())
progress.dismiss();
super.onFailure(error);
}
});
}
else
{
if(progress!=null)
{
progress.dismiss();
}
}
} else {
Toast.makeText(getApplicationContext(),
"No information found from google", Toast.LENGTH_LONG).show();
if(progress!=null&progress.isShowing())
progress.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"No information found from google", Toast.LENGTH_LONG).show();
if(progress!=null&progress.isShowing())
progress.dismiss();
}
}
private void login() {
WebserviceApi webserviceApi=Utilities.getWebservice(this);
if(webserviceApi!=null) {
if (mSharedPreferences.contains(Constants.SHARED_PREFS_S_GMAIL_EMAIL))
webserviceApi.loginFromSource(Constants.SHARED_PREFS_S_GMAIL_EMAIL , Constants.SHARED_PREFS_S_GMAIL_ID,
new BusNetworkCallback<Response>() {
#Override
public void onSuccess(Response obj) {
progress.dismiss();
Log.d(getClass().getSimpleName(), " success");
if (obj.getResult() != null && obj.getResult().equals("success")) {
Constants.userDetails = obj.getData();
Gson gson = new Gson();
mEditor.putString(Constants.SHARED_PREFS_S_USER_DETAILS, gson.toJson(Constants.userDetails));
mEditor.commit();
Intent mainActivityIntent = new Intent(mContext, MainActivity.class);
startActivity(mainActivityIntent);
finish();
} else if (obj.getError() != null && obj.getError().length() > 0)
Utilities.showAlertDialog(mContext, "Error", obj.getError());
else
Utilities.showAlertDialog(mContext, "Error", "Some error occurred. Please try again later.");
}
#Override
public void onFailure(RetrofitError error) {
if(progress!=null&progress.isShowing())
progress.dismiss();
super.onFailure(error);
Utilities.showAlertDialog(mContext, "Error", "Some error occurred. Please try again later.");
}
}
);
}
else
{
if(progress!=null&progress.isShowing())
progress.dismiss();
}
}
}

Categories