I have Text can someone please tell me how do i convert text to pdf and how do i show it in my android application. i saw there are many libraries which do the same can some one give me the sample code for that. thanks
i have used pdfviewer lib but still didnt get the pdf.
hear is my code -
File images = Environment.getExternalStorageDirectory();
imagelist = images.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return ((name.endsWith(".pdf")));
}
});
pdflist = new String[imagelist.length];
for(int i = 0;i<imagelist.length;i++)
{
pdflist[i] = imagelist[i].getName();
}
this.setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, pdflist));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String path = imagelist[(int)id].getAbsolutePath();
openPdfIntent(path);
}
private void openPdfIntent(String path)
{
try
{
final Intent intent = new Intent(this, Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
add PDFViewer as library in your project, copy its resources in your as guided in Here. This is working code for me. I am reading pdf from assets folder. Do customization as your requirement.
Download pdf reader project from above link.
copy all resources in your project.
extend your activity (in which you want to display pdf) from PdfViewerActivity.
copy all methods from pdfreader project in yourpdfview activity.
Run.
Happy Coding
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "ABC.pdf");
try {
in = assetManager.open("ABC.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(this, YourNextActivityName.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, getFilesDir() + "/ABC.pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
The methods of yourpdfview activity are:
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
Related
I wrote a code which takes picture from android device and then upload it on server.Can also upload pic from gallery. Uploading from gallery works perfectly.It is able to intent to mobile camera when clicked on capture button but when i return i didn't got any image and when i checked the gallery no image was captured.
Got menifest permission also
android.permission.WRITE_EXTERNAL_STORAGE"
android.permission.READ_EXTERNAL_STORAGE"
android.permission.CAMERA"
This is code in my Fragments onCreateView() class:
mTakePhoto = (Button) rootView.findViewById(R.id.take_photo);
mselectPhoto = (Button) rootView.findViewById(R.id.select_photo);
mImageView = (ImageView) rootView.findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
TAKE_PICTURE);
}
});
mselectPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,
IMAGE_PICKER_SELECT);
}
});
In the above code i think intents works perfectly
In bellow code, the (requestCode == IMAGE_PICKER_SELECT) condition works perfectly. But it seems like i didn't get any data when i took PICTURE
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICKER_SELECT
&& resultCode == Activity.RESULT_OK) {
Bitmap bitmap = getBitmapFromCameraData(data, getActivity());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(bitmap);
}
if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK
&& data != null) {
// get bundle
Bundle extras = data.getExtras();
// get bitmap
cameraBitmap = (Bitmap) extras.get("data");
int nh = (int) (cameraBitmap.getHeight() * (512.0 / cameraBitmap
.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(cameraBitmap, 512, nh,
true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(cameraBitmap);
// setPic();
}
}
I m also giving the Code of my Multipartentity class
public class MultipartEntity implements HttpEntity {
enter code here
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
I m stuck for almost the fullday. Help!!
Open your camera with below code and check with it:
private Uri mImageCaptureUri;
mImageCaptureUri = Uri.parse("content://YOUR PACKAGE NAME/");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent,TAKE_PICTURE);
I created a method to call whn button is clicked
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
takePhoto();
}
});
method to intent and getTempFile() to keel temporary file..
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getActivity())) );
startActivityForResult(intent, TAKE_PICTURE);
}
private File getTempFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
this link help me
http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html
i want to Convert My Activity To fragment can any One help to Convert Activity to Fragment..i have created Pdf
reader (Click On Button It Will Open Pdf File In Another Activty using pdfviwer.jar library..and I want When I click On Button Pdf Open On Same Screen on Right Side )
i need Help please Solve My Problem
i m posting my Activity
maiinActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn =(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "ABC.pdf");
try
{
in = assetManager.open("ABC.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(getApplicationContext(), MyPdfViewerActivity.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, getFilesDir()+"/ABC.pdf");
startActivity(intent);
/*
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/ABC.pdf"),
"application/pdf");
startActivity(intent);*/
}
});
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
PdfviwerActivty.java
public class MyPdfViewerActivity extends PdfViewerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
}
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
}
Try "extends FragmentActivity" instead of "extends Activity"..
You should use FragementActivity instead of Activity and paste your ui-components into the fragment's onCreateView()-Method. For further information look at this tutorial: http://www.vogella.com/tutorials/AndroidFragments/article.html
i'm developing my first Android app and i created a class (not Activity) that downloads a JSON file and writes content to SQLite database at every start-up of the application.
I then use an instance of this class in the main activity class.
If the download takes few seconds the home page of my app hangs on a blank screen.
Do you think i should use service instead of a class to handle download and writing of the db?
Could it be a good idea? If it could, what are the advantages?
If you are writing to a database I would recommend using an IntentService
The intent service runs in it's own thread.
When the download is complete you can use LocalBroadcastManager to notify the activity.
It could also work with ContentProvider and Loaders.
I also wanted to download the list of images in background so I used Services with SharedPreferences and I also Used AQuery With the Service.Here the ConnectionDetector is my Java class which checks the Internet Connection is available or not. It works for me. I hope it will give u some help.
public class MyService extends Service {
String f;
String path;
File file;
Bitmap bm;
String url1;
ArrayList<String> url_img;
AQuery aq;
int count = 1;
String val;
ArrayList<String> completed_url_list;
ArrayList<Integer> _index;
FileOutputStream out;
static ArrayList<String> list;
private Thread updateTask = new Thread(new Runnable() {
#Override
public void run() {
while (count < url_img.size()) {
try {
Log.e("Counter", "" + count);
val = url_img.get(count).toString();
final AjaxCallback<Bitmap> cb = new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap bm,
AjaxStatus status) {
try {
System.out.println("url is" + url);
String urll = url.substring(url
.lastIndexOf("/") + 1);
Log.e("Image name", "" + urll);
System.out.println("url111" + urll);
File f = new File(path + urll);
f.createNewFile();
System.out.println(f.getAbsolutePath());
try {
out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.JPEG, 40,
out);
if (out != null) {
out.flush();
out.close();
Log.e("download", "Complete");
completed_url_list.add(url);
System.out
.println("Completed Dowmload Image"
+ completed_url_list);
}
} catch (Exception e) {
boolean del_file = f.delete();
if (del_file == true){
Log.e("File", "deleted");
System.out.println("exception");
}
else{
System.out.println("file not deleted");
}
} finally {
out.close();
if (bm != null) {
bm.recycle();
bm = null;
}
System.gc();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (Exception e) {
}
}
};
final AQuery aq = new AQuery(getApplicationContext());
aq.ajax(val, Bitmap.class, 0, cb);
} catch (Exception e) {
}
count++;
}
}
});
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
url_img = getArrayList();
completed_url_list = new ArrayList<String>();
_index = new ArrayList<Integer>();
aq = new AQuery(MyService.this);
System.out.println("I am in super");
if (url_img.size() > 0) {
updateTask.start();
}
} catch (Exception e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void onCreate() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate();
try {
System.out.println("Service Creating");
f = Environment.getExternalStorageDirectory().getAbsolutePath();
path = f + "/HRI3mages/";
file = new File(path);
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
try {
for (int index = 0; index < completed_url_list.size(); index++) {
for (int index1 = 0; index1 < url_img.size(); index1++) {
if (completed_url_list.get(index).equals(
url_img.get(index1))) {
_index.add(index1);
}
}
}
Collections.sort(_index, new MyIntComparable());
System.out.println("next_download" + _index);
for(int index=0;index<_index.size();index++){
url_img.remove(index);
}
System.out.println("After_Deletion_of_Image"+url_img);
_addArray(url_img);
updateTask.interrupt();
} catch (Exception e) {
}
System.out.println("Service destroy");
super.onDestroy();
}
public class MyIntComparable implements Comparator<Integer>{
#Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
public ArrayList<String> getArrayList() {
ArrayList<String> list_url = new ArrayList<String>();
SharedPreferences SharedPref = getSharedPreferences("SSO", MODE_PRIVATE);
int size = SharedPref.getInt("list_size", 0);
for (int i = 0; i < size; i++) {
list_url.add(SharedPref.getString("list_" + i, ""));
}
System.out.println(list_url);
return list_url;
}
public void _addArray(ArrayList<String> list) {
SharedPreferences SharedPref = getSharedPreferences("SSO", 0);
SharedPreferences.Editor editor = SharedPref.edit();
int size = list.size();
editor.putInt("list_size", size);
for (int i = 0; i < size; i++) {
editor.putString("list_" + i, list.get(i));
}
editor.commit();
}
}
You might want to use an AsyncTask.
This will do the work in a background thread, so if it takes long your screen won't hang.
While the work is in progress, you can show a ProgressDialog (optional) to inform the user. You can also add a button to that ProgressDialog to cancel the task if needed.
See this: http://developer.android.com/intl/es/reference/android/os/AsyncTask.html
In this case I prefer an AsyncTask and not a Service so it seems easier and simpler to do what you want.
Good luck =)
I want to set on button click events backup my applications data on SD-Card.
This is my code :
shv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(SecondActivity.this, "backup Button press",Toast.LENGTH_LONG).show();
boolean rc = MyDatabaseTools.backup();
System.out.println(rc);
if(rc==true)
{
Toast.makeText(SecondActivity.this, "backup Successfully",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(SecondActivity.this, "backup error",Toast.LENGTH_LONG).show();
}
}
});
I proceed like this :
public class MyDatabaseTools {
private String appName = "";
private String packageName = "";
public static boolean backup() {
boolean rc = false;
boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/<com.example.judgedetail>/databases/ado.db");
File fileBackupDir = new File(Environment.getExternalStorageDirectory(), "ADOBOOK" + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}
if (file.exists()) {
File fileBackup = new File(fileBackupDir, "ado.db");
try {
fileBackup.createNewFile();
/*Files.copyFile(file, fileBackup);*/ //got error here dis line not work
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}
return rc;
}
private static boolean isSDCardWriteable() {
boolean rc = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}
return rc;
}
public MyDatabaseTools(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
}
Files.copyFile(file, fileBackup);
This line got error.
How shall I solve this ?
Please help.
Try this:
public void writeToSD() throws IOException {
File f=new File("/data/data/com.YourPackageName/databases/DBName");
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis=new FileInputStream(f);
fos=new FileOutputStream("/mnt/sdcard/dump.db");
while(true){
int i=fis.read();
if(i!=-1){
fos.write(i);
}
else{
break;
}
}
fos.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
fos.close();
fis.close();
}
catch(IOException ioe){
System.out.println(ioe);
}
}
}
I don't know where you copied that code from, but either you or the poster missed something. Files.copyFile() is no existing Android API function, and I guess that's what you describe as the line being not working.
You'll have to copy your file using another method, I'd suggest one like this:
https://stackoverflow.com/a/9293885/1691231
I'm creating a Fake Camera/Gallery app that just automatically return a random image. I tied it to the ACTION_PICK & IMAGE_CAPTURE intent filters.
However for the Gallery (PICK) code, after calling finish, it doesn't seem to be returning to the calling app.
Here's my code:
public class MainActivity extends Activity {
final static int[] photos = { R.drawable.android_1, R.drawable.android_2,
R.drawable.android_3 };
static int lastPhotoIndex = -1;
private final static String TAG = "FakeCameraGallery";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = getIntent().getAction();
if (action.contains("PICK")) {
//Act as Gallery
InputStream in = getResources().openRawResource(getNextPhoto());
Bitmap bm = BitmapFactory.decodeStream(in);
Bundle extras = new Bundle();
extras.putParcelable("data", bm);
Intent result = getIntent().putExtras(extras);
if (getParent() == null) {
setResult(Activity.RESULT_OK, result);
} else {
getParent().setResult(Activity.RESULT_OK, result);
}
} else {
//act as Camera
prepareToSnapPicture();
}
finish();
}
private void prepareToSnapPicture() {
checkSdCard();
Intent intent = getIntent();
if (intent.getExtras() != null) {
snapPicture(intent);
setResult(RESULT_OK);
} else {
Log.i(TAG, "Unable to capture photo. Missing Intent Extras.");
setResult(RESULT_CANCELED);
}
}
private void checkSdCard() {
if (!Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
Toast.makeText(this, "External SD card not mounted",
Toast.LENGTH_LONG).show();
Log.i(TAG, "External SD card not mounted");
}
}
private void snapPicture(Intent intent) {
try {
this.copyFile(getPicturePath(intent));
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.i(TAG, "Can't copy photo");
e.printStackTrace();
}
}
private File getPicturePath(Intent intent) {
Uri uri = (Uri) intent.getExtras().get(MediaStore.EXTRA_OUTPUT);
return new File(uri.getPath());
}
private void copyFile(File destination) throws IOException {
InputStream in = getResources().openRawResource(getNextPhoto());
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
if (in != null) {
Log.i(TAG, "Input photo stream is null");
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
}
out.close();
}
private int getNextPhoto() {
if (lastPhotoIndex == photos.length - 1) {
lastPhotoIndex = -1;
}
return photos[++lastPhotoIndex];
}
}
Your code looks fine: are you calling it using startActivityForResult?