i am new at android development and i need your help. I was locking at topics that are similar for my development but non of then help me.
So far i create functions that gets me the files from my sdcard and shows me the list of then.
That is working
this is the code for getting the paths on sdcard:
package com.seminarskirad;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class LoadActivity extends ListActivity{
private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }
private final DISPLAYMODE displayMode = DISPLAYMODE.ABSOLUTE;
private List<String> directoryEntries = new ArrayList<String>();
private File currentDirectory = new File("/");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Browse(Environment.getExternalStorageDirectory());
}
private void upOneLevel(){
if(this.currentDirectory.getParent() != null)
this.Browse(this.currentDirectory.getParentFile());
}
private void Browse(final File aDirectory){
if (aDirectory.isDirectory()){
this.currentDirectory = aDirectory;
fill(aDirectory.listFiles());
}
}
private void fill(File[] files) {
this.directoryEntries.clear();
if(this.currentDirectory.getParent() != null)
this.directoryEntries.add("..");
switch(this.displayMode){
case ABSOLUTE:
for (File file : files){
this.directoryEntries.add(file.getPath());
}
break;
case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
for (File file : files){
this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
}
break;
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, R.layout.load, this.directoryEntries);
this.setListAdapter(directoryList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
int selectionRowID = position;
String selectedFileString = this.directoryEntries.get(selectionRowID);
if(selectedFileString.equals("..")){
this.upOneLevel();
}else if(selectedFileString.equals()){ /// what to write here ???
this.readFile(); ///what to write here???
} else {
File clickedFile = null;
switch(this.displayMode){
case RELATIVE:
clickedFile = new File(this.currentDirectory.getAbsolutePath()
+ this.directoryEntries.get(selectionRowID));
break;
case ABSOLUTE:
clickedFile = new File(this.directoryEntries.get(selectionRowID));
break;
}
if(clickedFile.isFile())
this.Browse(clickedFile);
}
}
private void readFile() {
// what to write here???
}
Sorry i cant put the image because i dont have reputation, but when i run it on my emulator a get something like this:
/mnt/sdcard/kuzmanic.c
/mnt/sdcard/text.txt
/mnt/sdcard/DCIM
/mnt/sdcard/LOST.DIR
So what I want to do is when i click on the text.txt or kuzmanic.c file I want to open then in the same layout file, that is my load.xml file:
This is the code for the xml file:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="18sp">
</TextView>
What i need to write in my code and do I have to write anything in the manifest???
Try this code:
package com.javasamples;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
public class FileDemo2 extends Activity {
// GUI controls
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnWriteSDFile
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
finish();
}
}); // btnClose
}// onCreate
}// AndSDcard
the layout file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText
android:id="#+id/txtData"
android:layout_width="fill_parent"
android:layout_height="180px"
android:textSize="18sp" />
<Button
android:id="#+id/btnWriteSDFile"
android:layout_width="143px"
android:layout_height="44px"
android:text="1. Write SD File" />
<Button
android:id="#+id/btnClearScreen"
android:layout_width="141px"
android:layout_height="42px"
android:text="2. Clear Screen" />
<Button
android:id="#+id/btnReadSDFile"
android:layout_width="140px"
android:layout_height="42px"
android:text="3. Read SD File" />
<Button
android:id="#+id/btnClose"
android:layout_width="141px"
android:layout_height="43px"
android:text="4. Close" />
</LinearLayout>
I used this code to read a text file in SD card,
public class ReadFileSDCardActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.fileContent);
File dir = Environment.getExternalStorageDirectory();
//File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
//Get the text file
File file = new File(dir,"text.txt");
// i have kept text.txt in the sd-card
if(file.exists()) // check if file exist
{
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
tv.setText(text);
}
else
{
tv.setText("Sorry file doesn't exist!!");
}
}
}
first you have to give an id to your textview into the load.xml file and define the textview inside a linear layout. like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
<TextView android:id="#+id/tv1
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="18sp"/>
now you have to set the layout of your activity.you can do this in the onCreate() method only.
setContentView(R.layout.load);
now make a TextVew object like this.
TextView tview = (TextView) findViewById(R.id.tv1);
now you have to read the text file using FileInputStream and keep it into a string variable.
after that you can assign the string to the text view.
tview.setText(string variable name);
Related
I am trying to get the address of any file on android and then read its content.
I am getting the location of file as :
uri2.toString() gives string "file:///storage/emulated/0/download/user.txt"
uri2.getEndodedPath() gives string "/storage/emulated/0/download/user.txt"
when passing these value to file it gives file not found exception
Note : I am not reading file from sdcard or asset folder or raw folder and i am testing my app on mobile one plus cyanogen mod
here is my android code
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.nfc.Tag;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
public class MainSpeechActivity extends Activity {
TextToSpeech tts;
Button btn;
private String uri;
private Uri uri2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_speech);
final Intent intent = getIntent();
final String action = intent.getAction();
if(Intent.ACTION_VIEW.equals(action)){
//uri = intent.getStringExtra("URI");
uri2 = intent.getData();
uri = uri2.getEncodedPath() + " complete: " + uri2.toString();
TextView textView = (TextView)findViewById(R.id.textView);
TextView textView2 = (TextView)findViewById(R.id.textView2);
textView.setText(uri);
// now you call whatever function your app uses
String str = uri2.toString();// value is mentioned above
File f = new File(str);
BufferedReader br = null;
String line;
StringBuilder sbr = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
while((line = br.readLine()) != null) {
sbr.append(line);
sbr.append("\n");
}
br.close();
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"FileNotFound",Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"InputError",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if(sbr.toString().isEmpty())
textView2.setText("Blah blah");
else
textView2.setText(sbr.toString());
} else {
Log.d("know", "intent was something else: " + action);
}
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if( i != TextToSpeech.ERROR) {
tts.setLanguage(Locale.ENGLISH);
}
}
});
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String toSpeak = "My friend is very good programmer do you aggree";
Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
tts.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_speech, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If reading file from android is not possible then how to copy that file to sdcard or at location where reading and writing is possible
I am trying to get the address of any file on android and then read its content.
I am not reading file from sdcard
Then your options are fairly limited. The only way you can read a file from internal storage is if your app is allowed to access that part of internal storage.
However, seeing that you're trying to read from downloads, it should be fine. I think the problem is your file path is badly formatted:
file:///storage/emulated/0/download/user.txt
Should just be
/storage/emulated/0/download/user.txt
which you have the value of, you just need to set your str variable to getEncodedPath instead of toString
I have an android app which is basically a form to accept user input. This input is stored in a database. But I want to create a pdf file with the information a user enters and and display it so that the user can print the file or save the file to their android note tab. What is the best way to go about it. I have seen iText around but this does not render the file. I found this code online and I tested it to understand the concept of pdf creation. This uses Lowagie 2.1.7
package com.example.sweetiean.androidpdfdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
private Button createPDF , openPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createPDF = (Button)findViewById(R.id.button1);
createPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
createPDF();
}
});
openPDF = (Button)findViewById(R.id.button2);
openPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openPdf();
}
});
}
public void createPDF()
{
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "demo.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
/* Create Paragraph and S`enter code here`et Font */
Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");
/* Create Set Font and its Size */
Font paraFont= new Font(Font.HELVETICA);
paraFont.setSize(16);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
/* You can also SET FONT and SIZE like this */
Font paraFont2= new Font(Font.COURIER,14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
/* Inserting Image in PDF */
/*ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);*/
//set footer
Phrase footerText = new Phrase("This is an example of a footer");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally
{
doc.close();
}
}
void openPdf()
{
Intent intent = new Intent(Intent.ACTION_VIEW);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File file = new File(path, "demo.pdf");
intent.setDataAndType( Uri.fromFile(file), "application/pdf" );
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the main activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="100dp"
android:text="Open PDF" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="44dp"
android:text="Generate PDF" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/hello_world" />
Do it this way:
import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DynamicPDFHelloWorld extends Activity {
private static String FILE = Environment.getExternalStorageDirectory()
+ "/HelloWorld.pdf";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a document and set it's properties
Document objDocument = new Document();
objDocument.setCreator("DynamicPDFHelloWorld.java");
objDocument.setAuthor("Your Name");
objDocument.setTitle("Hello World");
// Create a page to add to the document
Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
54.0f);
// Create a Label to add to the page
String strText = "Hello World...\nFrom DynamicPDF Generator "
+ "for Java\nDynamicPDF.com";
Label objLabel = new Label(strText, 0, 0, 504, 100,
Font.getHelvetica(), 18, TextAlign.CENTER);
// Add label to page
objPage.getElements().add(objLabel);
// Add page to document
objDocument.getPages().add(objPage);
try {
// Outputs the document to file
objDocument.draw(FILE);
Toast.makeText(this, "File has been written to :" + FILE,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this,
"Error, unable to write to file\n" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
Also check these links. They will help you to fulfill your requirement.
http://www.dynamicpdf.com/Blog/post/2012/06/15/Generating-PDFs-Dynamically-on-Android.aspx
https://github.com/JoanZapata/android-pdfview
How to create PDFs in an Android app?
Render a PDF file using Java on Android
you'll find the correct code that actually works right.for creating a pdf file, putting some content in it, saving in and the opening the newly created file.
For this you'll need to add the jar of iTextG to your project:
OR
if you WANT TO convert your layout or view into pdf then you have to create image from your layout and then add into pdf.Perfect tutorial of that Go Through this Link . Hope this will help you guys.Thank you.
For Simple Create and Open pdf:
// Method for creating a pdf file from text, saving it then opening it for display
public void createandDisplayPdf(String text) {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "mypdffile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph(text);
Font paraFont= new Font(Font.FontFamily.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
viewPdf("mypdffile.pdf", "PDF");
}
// Method for opening a pdf file
private void viewPdf(String file, String directory) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
Uri path = Uri.fromFile(pdfFile);
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
}
Check this link,it requires you to download a jar file.(more description in the link).Here is a part of code to generate pdf.
package com.cete.androidexamples.dynamicpdf.helloworld;
import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DynamicPDFHelloWorld extends Activity {
private static String FILE = Environment.getExternalStorageDirectory()
+ "/HelloWorld.pdf";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a document and set it's properties
Document objDocument = new Document();
objDocument.setCreator("DynamicPDFHelloWorld.java");
objDocument.setAuthor("Your Name");
objDocument.setTitle("Hello World");
// Create a page to add to the document
Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
54.0f);
// Create a Label to add to the page
String strText = "Hello World...\nFrom DynamicPDF Generator "
+ "for Java\nDynamicPDF.com";
Label objLabel = new Label(strText, 0, 0, 504, 100,
Font.getHelvetica(), 18, TextAlign.CENTER);
// Add label to page
objPage.getElements().add(objLabel);
// Add page to document
objDocument.getPages().add(objPage);
try {
// Outputs the document to file
objDocument.draw(FILE);
Toast.makeText(this, "File has been written to :" + FILE,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this,
"Error, unable to write to file\n" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i am trying to download this file from url in android and also save file in SD card ....
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private ProgressBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar=(ProgressBar)findViewById(R.id.progressBar1);
new DownloadFileFromURL().execute("http://hrdevcontentapi.spanunit.com/000132/538/HCDocument/the_hatha_yoga_pradipika.docx");
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.docx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
bar.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
File targetFile = new File("/sdcard/downloadedfile.docx");
Uri targetUri = Uri.fromFile(targetFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/*");
startActivityForResult(intent, 100);
}
}
}
This is the activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.test.MainActivity" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
And this is the activity_main.xml
Don't forget to add the following permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For further details check this link:http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
Try using DownloadManager, it's very easy to use and good at long running download tasks.
import java.io.FileInputStream;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ImageView;
public class Test extends Activity
{
private static final String DL_ID = "downloadId";
private SharedPreferences prefs;
private DownloadManager dm;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageView = new ImageView(this);
setContentView(imageView);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
}
#Override
public void onResume() {
super.onResume();
if(!prefs.contains(DL_ID)) {
Uri resource = Uri.parse("http://asdf.com/big.jpg");
DownloadManager.Request request = new DownloadManager.Request(resource);
request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
request.setAllowedOverRoaming(false);
request.setTitle("Download Sample");
long id = dm.enqueue(request);
prefs.edit().putLong(DL_ID, id).commit();
} else {
queryDownloadStatus();
}
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
queryDownloadStatus();
}
};
private void queryDownloadStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(prefs.getLong(DL_ID, 0));
Cursor c = dm.query(query);
if(c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
Log.d("DM Sample","Status Check: "+status);
switch(status) {
case DownloadManager.STATUS_PAUSED:
case DownloadManager.STATUS_PENDING:
case DownloadManager.STATUS_RUNNING:
break;
case DownloadManager.STATUS_SUCCESSFUL:
try {
ParcelFileDescriptor file = dm.openDownloadedFile(prefs.getLong(DL_ID, 0));
FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(file);
imageView.setImageBitmap(BitmapFactory.decodeStream(fis));
} catch (Exception e) {
e.printStackTrace();
}
break;
case DownloadManager.STATUS_FAILED:
dm.remove(prefs.getLong(DL_ID, 0));
prefs.edit().clear().commit();
break;
}
}
}
}
Ckeck Out This Link
I'm new user in android and I try to view a pdf file using itext jar file.
My code is:
package com.example.pdfone;
public class MainActivity {
public static final String RESULT = "Workspace/one.pdf";
public static void main(String[] args) throws DocumentException, IOException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(RESULT));
document.open();
document.add(new Paragraph("Hello World!"));
document.close();
}
}
But when I run this program it gives me Error: Could not find or load main class com.example.pdfone.MainActivity error in console
What can I do? Please help me. Thank you in advance
You need to learn Android first.
Your class needs to extend Activity class.
And iText can only create pdf file, viewing is not possible. Reading is possible. Use Adobe Acrobat or any other PDF tools in Android to view it.
Sample Solutions is as below for PDF Read and Write in Android
100% Working Code Screenshots as below,
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAlignment="center"
android:text="Android Read/Write File" />
<EditText
android:id="#+id/fname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="File Name"
android:text="sample_pdf_file" />
<EditText
android:id="#+id/ftext"
android:layout_width="fill_parent"
android:layout_height="100px"
android:hint="File Text"
android:text="Hello World" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/btnwrite"
android:text="Write File" />
<EditText
android:id="#+id/fnameread"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="File Name"
android:text="sample_pdf_file" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/btnread"
android:text="Read File" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/filecon" />
</LinearLayout>
FileOperations.java
package com.example.readwrite;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import android.util.Log;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
public class FileOperations {
public FileOperations() {
}
public Boolean write(String fname, String fcontent) {
try {
String fpath = "/sdcard/" + fname + ".pdf";
File file = new File(fpath);
// If file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// step 1
Document document = new Document();
// step 2
PdfWriter.getInstance(document,
new FileOutputStream(file.getAbsoluteFile()));
// step 3
document.open();
// step 4
document.add(new Paragraph("Hello World!"));
document.add(new Paragraph("Hello World2!"));
// step 5
document.close();
Log.d("Suceess", "Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
public String read(String fname) {
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/" + fname + ".pdf";
PdfReader reader = new PdfReader(new FileInputStream(fpath));
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
StringWriter strW = new StringWriter();
TextExtractionStrategy strategy;
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
strategy = parser.processContent(i,
new SimpleTextExtractionStrategy());
strW.write(strategy.getResultantText());
}
response = strW.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}
}
MainActivity.java
package com.example.readwrite;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText fname, fcontent, fnameread;
Button write, read;
TextView filecon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fname = (EditText) findViewById(R.id.fname);
fcontent = (EditText) findViewById(R.id.ftext);
fnameread = (EditText) findViewById(R.id.fnameread);
write = (Button) findViewById(R.id.btnwrite);
read = (Button) findViewById(R.id.btnread);
filecon = (TextView) findViewById(R.id.filecon);
write.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String filename = fname.getText().toString();
String filecontent = fcontent.getText().toString();
FileOperations fop = new FileOperations();
fop.write(filename, filecontent);
if (fop.write(filename, filecontent)) {
Toast.makeText(getApplicationContext(),
filename + ".pdf created", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "I/O error",
Toast.LENGTH_SHORT).show();
}
}
});
read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String readfilename = fnameread.getText().toString();
FileOperations fop = new FileOperations();
String text = fop.read(readfilename);
if (text != null) {
filecon.setText(text);
} else {
Toast.makeText(getApplicationContext(), "File not Found",
Toast.LENGTH_SHORT).show();
filecon.setText(null);
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.readwrite"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.readwrite.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Make sure you have the itextpdf-5.5.1.jar in the right location as below,
This question already has answers here:
Install Application programmatically on Android
(18 answers)
Closed 9 years ago.
In my android app i have 1 button to download the .apk and and then im adding another to install the .apk, when you click the download button it downloads the .apk from my website and puts it in the root of your sdcard storage! what do i have to add so when the user clicks the button named "install" it takes them to the install screen??
MainActvity.java
package cydia.jb.download;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path = "http://diordnakclab.net23.net/cydia/Cydia.apk";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showProgress(dwnload_file_path);
new Thread(new Runnable() {
public void run() {
downloadFile();
}
}).start();
}
});
}
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"Cydia.apk");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) * 100;
cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
showError("Error : Please check your internet connection " + e);
}
}
void showError(final String err){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, err, Toast.LENGTH_LONG).show();
}
});
}
void showProgress(String file_path){
dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.myprogressdialog);
dialog.setTitle("Download Progress");
TextView text = (TextView) dialog.findViewById(R.id.tv1);
text.setText("Downloading file from ... " + file_path);
cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
cur_val.setText("Starting download...");
dialog.show();
pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
pb.setProgress(0);
pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));
}
}
CydiaManafest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cydia.jb.download"
android:versionCode="4"
android:versionName="4.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="cydia.jb.download.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
here is the code
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener()
{
public void onClick(View v1)
{
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("file:///path/to/your.apk"))
.setType("application/vnd.android.package-archive");
startActivity(promptInstall);
}
}