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);
}
}
Related
I'd like to make a program which connects Python code with Android Studio.
But there has been a problem on android studio which is not showing any UI that I'd like to show on Emulator Screen. I think it is due to "StrictMode". But If I except the StrictMode Code. The Program is stopped. What should I do? Here is the codes.
Python Code(Server)
import socket
import random as r
HOST = "localhost"
PORT = 9999
x = ['10', '20', '30', '40', '50']
y = ['-10', '-20', '-30','-40', '-50']
rssi = ['1.5', '2.5', '3.5', '4.5', '5.5']
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
s.bind((HOST, PORT))
except socket.error as err:
print('Bind failed. Error Code : ' .format(err))
s.listen(10)
print("Socket Listening")
conn, addr = s.accept()
while(True):
i = r.randint(0, 4)
conn.send(bytes("x : " + x[i] + " y : "+ y[i] + " rssi : " +
rssi[i] + "\r\n", 'UTF-8'))
print("Message sent in python")
data = conn.recv(1024)
print(data.decode(encoding='UTF-8'))
Android Studio(Client) - AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yangseungchan.socketwithpython">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
3.Android Studio(Client) - MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
private Socket clientSocket;
private BufferedReader socketIn;
private PrintWriter socketOut;
private int port = 9999;
private final String ip = "222.99.99.14";
private MyHandler myHandler;
private MyThread myThread;
static String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
clientSocket = new Socket(ip, port);
socketIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
socketOut = new PrintWriter(clientSocket.getOutputStream(), true);
}catch(Exception e){
e.printStackTrace();
}
myHandler = new MyHandler();
myThread = new MyThread();
myThread.start();
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*socketPython.Datastack.printStack();
textView.setText((String)SocketwithPython.Datastack.Peek(0));*/
socketOut.println(123);
}
});
}
class MyThread extends Thread{
#Override
public void run() {
while(true){
try{
System.out.println("Trying to read...");
String data = socketIn.readLine();
Message msg = myHandler.obtainMessage();
msg.obj = data;
myHandler.sendMessage(msg);
System.out.println(data);
socketOut.print("Try"+"\r\n");
socketOut.flush();
System.out.println("Message sent");
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
class MyHandler extends Handler {
public void handleMessage(Message msg){
textView.setText(msg.obj.toString());
}
}
}
I Write a code to download a file with circle progress bar. But file is not downloading into external storage and progress bar does not display any progress number. No error is shown in logcat. I don't no what is wrong in my code. Help me to solve this problem. Here is my code. I have added all the permission and activity classes in manifest file. Thanks in advance.
package com.example.skr.downloader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
public class DownloaderClass extends Activity {
EditText txturl;
int progress=0;
public ProgressDialog progressDialog;
public DownloaderClass(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_download);
}
public void onDownload(View v){
txturl=(EditText)findViewById(R.id.txtURL);
progressDialog=new ProgressDialog(DownloaderClass.this);
final AsyncDownloaderClass asyncDownloaderClass=new AsyncDownloaderClass();
asyncDownloaderClass.execute("http://pinnest.net/newpinnest/wp-content/uploads/2013/08/1377250577ea43d.jpg");
}
class AsyncDownloaderClass extends AsyncTask<String,Integer, String>
{
private PowerManager.WakeLock mWakeLock;
Context context;
String filename, basename;
int fileLength;
DownloaderClass downloaderClass;
public AsyncDownloaderClass(){
downloaderClass=new DownloaderClass();
context=downloaderClass;
/*PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,getClass().getName());*/
}
protected void onPreExecute(){
// super.onPreExecute();
progressDialog.setMessage("Downloading....");
progressDialog.setTitle("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
//progressDialog.setIndeterminate(false);
progressDialog.setProgress(progress);
//progressDialog.setMax(100);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new AsyncDownloaderClass().cancel(true);
}
}
);
//mWakeLock.acquire();
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
//return null;
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
Log.v("Do in background","calling.....");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
input = connection.getInputStream();
BufferedInputStream bufferedInputStream=new BufferedInputStream(input);
fileLength = connection.getContentLength();
filename=url.getPath();
filename=filename.substring(filename.lastIndexOf('/') + 1);
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"download.jpg");
byte data[] = new byte[1024];
long total = 0;
int count=0;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
Log.v("Error","Error");
}
if (connection != null)
connection.disconnect();
}
return null;
}
protected void onProgressUpdate(Integer... values){
progressDialog.setProgress(values[0]);
progressDialog.setMessage("Downloading... " + values[0] + "%");
}
protected void onPostExecute(String... result){
progressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
}
}
Manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.skr.downloader">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<application android:allowBackup="true" android:label="#string/app_name"
android:icon="#drawable/download" android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity android:name="com.example.skr.downloader.LauncherClass">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity>
<activity android:name=".DownloaderClass">
<intent-filter>
<action android:name="my.android.download"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</activity>
</application>
</manifest>
The signature of onPostExecute is wrong. Change
protected void onPostExecute(String... result){
to
#Override
protected void onPostExecute(String result){.
As now it is never called. And change
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"download.jpg");
to
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/download.jpg");
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,
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);