Browse pdf from phone in Android Studio - pdf

I need to create an app that involves browsing pdf from phone and then reading it (which will be executed later, once the browsing part is done) and I'm having trouble with it's code. I have gone through the following link I found on stackoverflow, but unfortunately it is not working,
Browse and upload pdf or word file in Android
Here is my MainActivity.java class
import java.io.File;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
Button btnAttach;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAttach = (Button) findViewById(R.id.button1);
//button1 is the id of the only button I have in my activity_main.xml
// view products click event
btnAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button1_OnClick(view);
// Launching All products Activity
}
});
}
public void button1_OnClick(View view) {
getDocument();
}
private void getDocument() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/msword,application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
}
protected void onActivityResult ( int req, int result, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(req, result, data);
if (result == RESULT_OK) {
Uri fileuri = data.getData();
String docFilePath = getFileNameByUri(this, fileuri);
}
}
// get file path
private String getFileNameByUri(Context context, Uri uri) {
String filepath = "";//default fileName
File file;
if (uri.getScheme().toString().compareTo("content") == 0) {
Cursor cursor = context.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION}, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String mImagePath = cursor.getString(column_index);
cursor.close();
filepath = mImagePath;
} else if (uri.getScheme().compareTo("file") == 0) {
try {
file = new File(new URI(uri.toString()));
if (file.exists())
filepath = file.getAbsolutePath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
filepath = uri.getPath();
}
return filepath;
}
}

As #CherryDT pointed out, startActivityForResult(intent, REQUEST_CODE_DOC); was missing. Added it and fixed the issue.

Related

latitude and longitude are returning a null poinbter exception

package com.example.myapplicationlocation;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
FusedLocationProviderClient fusedLocationProviderClient;
Button getLocation;
TextView longitude;
TextView latitude;
private final static int REQUEST_CODE = 100;
List <Address> addresses = null;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocation = (Button) findViewById(R.id.button);
longitude = (TextView) findViewById(R.id.textView);
latitude = (TextView) findViewById(R.id.textView2);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
getLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getlastLocation();
latitude.setText("Latitude = "+addresses.get(0).getLatitude());
longitude.setText("Longitude" + addresses.get(0).getLongitude());
}
});
}
private void getlastLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null ){
Toast.makeText(MainActivity.this, "app working", Toast.LENGTH_SHORT).show();
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
Toast.makeText(MainActivity.this, "aint working", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
});
}else{
askPermission();
}
}
private void askPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE){
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
getlastLocation();
}else{
Toast.makeText(this, "Required Permission", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
when I try setting the textviews as longtideu and latitude, i get a null pointer exception, not sure why. I get the first toast message so the location definitely isnt null. When i try setting my text in the try catch, Nothing works either.
I was expecting the app to return the longitude and latitude of the emulator

React Native, Native Modules returns empty object - {}

I've written native module for React Native, everything was done according to official documentation, but something went wrong, and Native Modules returns only empty object.
importing Native Modules in Component Home.js
All Module code was writen according to official docs
import {
NativeModules
} from 'react-native';
const { OptionsPackage } = NativeModules;
console.log(NativeModules) // {}
MainApplication.java file
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new OptionsPackage());
return packages;
}
OptionsPackage.java file
package package.name;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OptionsPackage implements ReactPackage {
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new OptionsModule(reactContext));
return modules;
}
}
OptionsModule.java
package com.downloadmanager;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.io.InputStream;
...
public class OptionsModule extends ReactContextBaseJavaModule {
ActivityManager activityManager;
int currentSDK;
ReactApplicationContext context;
OptionsModule(ReactApplicationContext context) {
super(context);
this.activityManager = ((ActivityManager) context.getSystemService(ReactApplicationContext.ACTIVITY_SERVICE));
context = context;
currentSDK = android.os.Build.VERSION.SDK_INT;
}
#Override
public String getName() {
return "123";
}
private Map packageInfoToMap(PackageInfo pi) {
PackageManager pm = this.context.getPackageManager();
long longVersionCode;
Map<String, Object> AppInfo = new HashMap<String, Object>();
if(Build.VERSION.SDK_INT >= 28) {
longVersionCode = pi.getLongVersionCode();
} else
{
longVersionCode = pi.versionCode; }
AppInfo.put("packageName", pi.packageName);
AppInfo.put("versionName", pi.versionName);
AppInfo.put("getLongVersionCode", longVersionCode);
AppInfo.put("lastUpdateTime", (pi.lastUpdateTime));
AppInfo.put("firstInstallTime", pi.firstInstallTime);
String title = pi.applicationInfo.loadLabel(pm).toString();
String description = pi.applicationInfo.loadDescription(pm).toString();
Drawable icon = pi.applicationInfo.loadIcon(pm);
AppInfo.put("title", title);
AppInfo.put("description", description);
AppInfo.put("icon", icon);
//get folder
String apkDir = pi.applicationInfo.publicSourceDir;
File file = new File(apkDir);
double size = file.length();
AppInfo.put("filePath", apkDir);
AppInfo.put("size", size);
return AppInfo;
}
#ReactMethod
public List listOfApps(String type) {
List<PackageInfo> packages = this.context.getPackageManager().getInstalledPackages(0);
List<Map<String, Object>> listOfApps = new ArrayList();
for (PackageInfo isPackage : packages) {
boolean isSystem = (isPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM;
if(type == "systemOnly" && isSystem) {
listOfApps.add(this.packageInfoToMap(isPackage));
} else if (type == "nonSystem" && !isSystem) {
listOfApps.add(this.packageInfoToMap(isPackage));
} else {
listOfApps.add(this.packageInfoToMap(isPackage));
}
}
return listOfApps;
}
}
Your getName() override method in OptionsModule is returning "123"
#Override
public String getName() {
return "123";
}
This is how react native gets the name of your module that should show up on react native side.
Try changing it to "OptionsModule" and then in your Home.js do
const {OptionsModule} = NativeModules
Also try calling your #ReactMethod in js to see if it works, don't rely on console logging NativeModules.

Unable to Configure Log4j2 using java.util.Properties

I am unable to configure log4j2 with java.util.properties. I always get this message "tatusLogger No Log4j 2 configuration file found". Please see my logger class. I am reading the log4j2 properties from two files.
I will be attaching my code to this post.
package my.common.logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
import org.apache.logging.log4j.util.PropertiesUtil;
public class MyLogger {
private static boolean configured = false;
private static Logger logger;
static {
System.setProperty("log4j.configurationFactory", "my.common.logger.JCFLog4JConfigurationFactory");
}
private static void readConfiguration() throws Exception {
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = ConfigurationFactory.getInstance().getConfiguration(context, createConfigurationSource());
configuration.start();
Configurator.reconfigure();
configured = true;
}
public static Logger getLogger(String className) {
try {
if (!configured) readConfiguration();
return org.apache.log4j.LogManager.getLogger(className);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static ConfigurationSource createConfigurationSource()
{ Properties p = new Properties();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = null;
try {
p.putAll(<Read from File 1>);
p.putAll(<Read from File 2>);
p.store(out, null);
} catch (IOException e) {
e.printStackTrace();
}
in = new ByteArrayInputStream(out.toByteArray());
ConfigurationSource configSrc = null;
try {
configSrc = new ConfigurationSource(in);
}
catch (IOException i)
{
i.printStackTrace();
}
return configSrc;
}
}
Here is Config Factory Code:
package nj.aoc.ito.cmfw.common.logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
public class MyLog4JConfigurationFactory extends ConfigurationFactory {
public MyLog4JConfigurationFactory() {
}
#Override
public Configuration getConfiguration(LoggerContext ctx, ConfigurationSource source) {
PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory();
return factory.getConfiguration(ctx, source);
}
#Override
protected String[] getSupportedTypes() {
return new String[]{".properties", "*"};
}
}
Any idea what I might be doing wrong?
Thanks
Nags

NullPointerException on FragmentActivity.onBackPressed()

I have a problem on up back icon toolbar, when i click twice to go back app crash on nullpointer exception recalling the error on my getActivity().onBackPressed();
this is the fragment:
package com.example.android.evilsecretgallery;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.TransitionInflater;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.chrisbanes.photoview.PhotoView;
public class ImageDetailFragment extends Fragment {
private static final String EXTRA_IMAGE = "image_item";
private static final String EXTRA_TRANSITION_NAME = "transition_name";
public ImageDetailFragment() {
// Required empty public constructor
}
public static ImageDetailFragment newInstance(ImageModel image, String transitionName) {
ImageDetailFragment fragment = new ImageDetailFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_IMAGE, image);
args.putString(EXTRA_TRANSITION_NAME, transitionName);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postponeEnterTransition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(getActivity(), R.style.EvilTextAppearance);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ImageModel image = getArguments().getParcelable(EXTRA_IMAGE);
String transitionName = getArguments().getString(EXTRA_TRANSITION_NAME);
final PhotoView imageView = view.findViewById(R.id.detail_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView.setTransitionName(transitionName);
}
Glide.with(getActivity())
.asBitmap()
.load(image.getUrl())
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
startPostponedEnterTransition();
imageView.setImageBitmap(resource);
}
});
}
}
that go back in this activity:
package com.example.android.evilsecretgallery;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class PagesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
if (getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, RecyclerViewFragment.newInstance())
.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
then if I go back again to this activity below it gives me the error:
package com.example.android.evilsecretgallery;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView cover;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
cover = findViewById(R.id.cover_id);
cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create a new intent to open the PagesActivity
Intent intent = new Intent(MainActivity.this, PagesActivity.class);
// Start the new activity
startActivity(intent);
}
});
Button siteButton = findViewById(R.id.site_button);
siteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://www.evilsecret.it";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
}
I have made some experiment and if i go back from pages activity it has no problem. I have to use different method in the fragment?
try clean and rebuild your project
It worked for me.

React Native UI Component

When react native require this native ui component multiple time, starting from the second one, the previous became black.
Any ideas?
#Override
public String getName()
{
return "JWPlayer";
}
#Override
public JWPlayerView createViewInstance(ThemedReactContext context)
{
PlayerConfig playerConfig = new PlayerConfig.Builder().build();
playerView = new JWPlayerView(context.getCurrentActivity(), playerConfig);
playerView.setFullscreen(false, false);
playerView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
playerView.addOnFullscreenListener(this);
playerView.addOnPauseListener(this);
playerView.addOnPlayListener(this);
playerView.addOnSetupErrorListener(this);
playerView.addOnErrorListener(this);
return playerView;
}
I also met this question.
I solved the problem.
see same question ,
this
JWView.java :
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.longtailvideo.jwplayer.JWPlayerView;
import com.longtailvideo.jwplayer.configuration.PlayerConfig;
public class JWView extends FrameLayout {
private final Context _context;
private Activity activity = null;
public JWView(Context context) {
super(context);
this._context = context;
this.activity = ((ReactContext) getContext()).getCurrentActivity();
PlayerConfig playerConfig = new PlayerConfig.Builder()
.file("http://img.ksbbs.com/asset/Mon_1605/25d705200a4eab4.mp4")
.autostart(false)
.build();
JWPlayerView playerView = new JWPlayerView(this.activity, playerConfig);
addView(playerView);
}
private final Runnable measureAndLayout = new Runnable() {
#Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
#Override
public void requestLayout() {
super.requestLayout();
// The spinner relies on a measure + layout pass happening after it calls requestLayout().
// Without this, the widget never actually changes the selection and doesn't call the
// appropriate listeners. Since we override onLayout in our ViewGroups, a layout pass never
// happens after a call to requestLayout, so we simulate one here.
post(measureAndLayout);
}
}
JWPlayerViewManager.java:
import java.util.List;
import java.util.ArrayList;
import android.app.Activity;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.longtailvideo.jwplayer.JWPlayerView;
import com.longtailvideo.jwplayer.configuration.PlayerConfig;
public class JWPlayerViewManager extends SimpleViewManager<JWView>
{
#Override
public String getName()
{
return "Jwplayer";
}
#Override
public JWView createViewInstance(ThemedReactContext context)
{
return new JWView(context);
}
}