I would like to open a pdf file ( which is available in Downloads folder in Android phone) during on click on the 'pdfButton'
While performing the action, nothing happens, there are either no errors logged or pdf file is displayed. Could some one please help ?
package com.mycompany.myfirstglapp;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceView;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.File;
/**
* Created by admin on 1/11/2016.
*/
public class PdfActivity extends Activity {
private SurfaceView surface;
Button pdfButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
surface = (SurfaceView) findViewById(R.id.pdfSurface);
pdfButton = (Button) findViewById(R.id.pdfView);
pdfButton .setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// On click will call the showPdf method to display the pdf file in sd card or downloads
showPdf(view);
}
});
}
public void showPdf(View view) {
// The pdf file [LawsofthegamewebEN_Neutral.pdf] is avaialble in Android > Downloads folder.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/LawsofthegamewebEN_Neutral.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(PdfActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
}
If you step through the code with your debugger, or put more logging statements in, I suspect that you will find that file.exists() returns false. And, at the moment, you do not do anything in that case.
I would like to open a pdf file ( which is available in Downloads folder in Android phone)
That is not where your code is looking. Replace:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/LawsofthegamewebEN_Neutral.pdf");
with:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "LawsofthegamewebEN_Neutral.pdf");
Also note that your file.exists() call means that you will need to hold the READ_EXTERNAL_STORAGE permission.
Related
This the code :
package app.nepaliapp.bscfree.Utility;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import androidx.appcompat.widget.AppCompatButton;
import app.nepaliapp.bscfree.R;
public class NetworkChangeListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (!Common.isConnectedToInternet(context)) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View layout_dialog = LayoutInflater.from(context).inflate(R.layout.check_internet_dialog, null);
builder.setView(layout_dialog);
AppCompatButton btnRetry = layout_dialog.findViewById(R.id.btnRetry);
//show dialog
AlertDialog dialog = builder.create();
dialog.show();
dialog.setCancelable(false);
dialog.getWindow().setGravity(Gravity.CENTER);
btnRetry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
onReceive(context, intent);
}
});
}
}
}
This code work good at emulator and Fuction as expected but when published run in other device like android it doesn't works.
The error seen in my console panel is this:
Caused by android.view.WindowManager$BadTokenException
Unable to add window -- token android.os.BinderProxy#21ba88d is not valid; is your activity running?
android.view.ViewRootImpl.setView (ViewRootImpl.java:1068)
android.app.Dialog.show (Dialog.java:340)
app.nepaliapp.bscfree.Utility.NetworkChangeListener.onReceive (NetworkChangeListener.java:32)
android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args (LoadedApk.java:1556)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:947)
I am trying to read a file as inputstream to fill in the file with additional data. This data is then supposed to be sent over to a second activity which unwraps the data and displays it on the screen. this is my code
package com.example.daniel.finalproject;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class Secondactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
public void Proceed(View view) {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
}
}
However this line: InputStream is = am.open("madlibsimple.txt");
returns the error. madlibsimple.txt is in the assetsfolder, but I
don't know what goes wrong. Any help would be much appreciated.
open(String file) can throw an error (i expect IOException) that you have to catch with an
try {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
} catch (Exception e) {
e.printStacktrace();
}
statement.
This whole topic is not about what goes wrong, but what COULD go wrong
For more information on the topic of exceptions and errorhandling you can click here
So I looked around a little bit to find a good PDF APIs for android and I've discovered PDFBox. I started to play with this library and mainly I'm looking for manipulating specific pdf form.
Now I am loading the file successfuly from my assets folder, but when I try to call
getAcroForm();
It turns me a null object, Thus I can't get into the fields and start to insert some data.
Here is the code where I load the pdf file, copy it to the sdcard and load it to an PDDocument object:
package com.silverfix.pdfpractice;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDFieldTreeNode;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
public class MainActivity extends AppCompatActivity{
private final String FORM_NAME = "dgc.pdf";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AssetManager assetManager = getAssets();
File file = createFileFromInputStream(assetManager.open(FORM_NAME));
PDDocument form = PDDocument.load(file);
PDDocumentCatalog catalog = form.getDocumentCatalog();
catalog.getPages().getCount();
Toast.makeText(this, "Loaded! " + catalog.getPages().getCount(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Loading has failed", Toast.LENGTH_LONG).show();
}
}
private File createFileFromInputStream(InputStream inputStream) {
try{
OutputStream outputStream = new FileOutputStream("/sdcard/PDFPractice/" + FORM_NAME);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
File result = new File("/sdcard/PDFPractice/" + FORM_NAME);
return result;
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
How can I manipulate a pdf file without acroform? Or, can I add an somesort of acroform to this pdf file by myself?
Ok so I finally solved this problem. I downloaded Foxit PhantomPDF and it turns out you can define text fields and align them for your needs. I don't know if there is another software that does that but this one did the job for me
After two days of tests we were able to partially work.
I downloaded the file, but I have no idea where to store it.
I tried to download a picture and the picture appears in the folder /all_downloads
I do not know how to store it in /sdcard/update.
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class Upgrade extends ActionBarActivity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrade);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://android.vrt.ro/tv-update/v1.apk"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///sdcard/download/v1.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
}
}
Use this
request.setDestinationInExternalPublicDir("/updates", "update.apk");
Added in API level 9
public DownloadManager.Request setDestinationInExternalPublicDir (String dirType, String subPath)
Set the local destination for the downloaded file to a path within the
public external storage directory (as returned by
getExternalStoragePublicDirectory(String)).
The downloaded file is not scanned by MediaScanner. But it can be made
scannable by calling allowScanningByMediaScanner().
Parameters dirType the directory type to pass to
getExternalStoragePublicDirectory(String)` subPath the path within the
external directory, including the destination filename Returns this
object Throws IllegalStateException If the external storage directory
cannot be found or created.
You can also use this version
String updatePath = Environment.getExternalStorageDirectory() + File.separator + "Updates" + File.separator + "update.apk";
request.setDestinationUri(Uri.fromFile(new File(updatePath)))
There is a strange behaviour of assigning/modifying instance variable of the class inside Button OnClick() handlers.
As shown below, the instance variable "CurrentFile" is modified inside imgBtn.setOnClickListener() handlers. But when this variable is accessed in onActivityResult() method, this variable contains the value "null".
According to my understanding, the activity "GetPicActivity" will not be destroyed till the Camera activity returns. So, the instance variable "CurrentFile" should not be null.
Please help, if I am missing some basics.
import java.io.File;
import java.io.IOException;
import com.favoritepics.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class GetPicActivity extends Activity {
protected static final int ID_REQ_IMAGE_CAPTURE = 1;
protected static final int ID_REQ_PICK_PHOTO = 0;
protected File currentFile = null; /// Goal is "to modify this variable inside Button onClick handlers"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.DKGRAY));
setContentView(R.layout.activity_get_pic);
// set handler image gallery
ImageButton imgBtn = (ImageButton) findViewById(R.id.imgGallery);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
// create intent to take picture on camera
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, ID_REQ_PICK_PHOTO);
}
});
// set handler for camera image
imgBtn = (ImageButton) findViewById(R.id.imgCamera);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempDir = Environment.getExternalStorageDirectory();
File tempFile = null;
try {
currentFile = File
.createTempFile("_jpeg_", ".jpg", tempDir);
} catch (IOException exception) {
Toast.makeText(
GetPicActivity.this,
"Problem occured during creation of temp file! "
+ exception.getMessage(),
Toast.LENGTH_SHORT).show();
}
if (currentFile != null) {
takePicture.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(currentFile));
startActivityForResult(takePicture, ID_REQ_IMAGE_CAPTURE);
}
}
});
// set handler for cancel button
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ID_REQ_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
Intent newIntent = new Intent();
newIntent.putExtra("TYPE", requestCode);
newIntent.putExtra("PATH", currentFile.getAbsolutePath());
setResult(RESULT_OK, newIntent);
finish();
}
break;
default:
break;
}
}
}
click here to see Logcat messages
Steps what I intend to do:
1, Create a temporary file in External storage for the destination of Camera picture
2, Start Camera to take a picture by passing the URI of temporary file
3, OnActivityResult() from camera, return the (temporary) File path to previous activity for further process
But here what I see is,
As soon as the Camera is started & picture is taken, the GetPicActivity is created again. Because of this, the instance variable "CurrentFile" will be null & in OnActivityResult() , I could not get the File path of temporary file.
Why is the GetPicActivity destroyed after starting Camera?
When the camera is started, the Camera appears in the screen orientation "Landscape".
Even the orientation of already existing activity stack is changed to "Landscape" itseems.
So, When the result of Camera is returned to GetPicActivity method OnActivityResult(), the GetPicActivity is created again. But now, the instance variable "CurrentFile" is null. This, gives a NullPointerException.