Im doing Download All of files. What I did was for loop, unfortunately my for loop does not finish my async task it continues doing all the loop regardless if it finished the first file that was downloading. Help please.
Here is my for loop
for (int i = 0; i < id.length; i++) {
Element e = (Element)nodes.item(i);
id[i] = ""+CategoriesXMLfunctions.getValue(e, "id");
name[i] = ""+CategoriesXMLfunctions.getValue(e, "name");
image[i] = ""+CategoriesXMLfunctions.getValue(e, "image");
simage[i] = ""+CategoriesXMLfunctions.getValue(e, "simage");
download[i] = ""+CategoriesXMLfunctions.getValue(e, "download");
author[i] = ""+CategoriesXMLfunctions.getValue(e, "author");
genre[i] = ""+CategoriesXMLfunctions.getValue(e, "genre");
size[i] = ""+CategoriesXMLfunctions.getValue(e, "size");
price[i] = ""+CategoriesXMLfunctions.getValue(e, "price");
mylist.add(map);
id_all = id[i];
image_all = image[i];
dload_all = download[i];
size_all = size[i];
name_all = name[i];
String response = null;
String resstring = null;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("devid", "devid"));
String devid=null;
try {
devid = URLEncoder.encode(Global.getMac(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String nURL = "http://....url";
response = CustomHttpClient.executeHttpPost(nURL, postParameters);
resstring=response.toString();
String credit = resstring;
String priiice = price[i];
float money = Float.parseFloat(credit);
float pri = Float.parseFloat(priiice);
if(pri>money){
final AlertDialog.Builder alert = new AlertDialog.Builder(MainStore.this);
alert.setMessage("Credits not enough.");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}else{
File sd = getDir("xml",MODE_PRIVATE);
File todel = new File(sd,id[i]+".xml");
todel.delete();
String filecreat= "/"+id[i]+".xml";
File newfil = new File(sd+ filecreat);
if(newfil.exists()){
todel.delete();
}
try{
if(!newfil.exists()){
newfil.createNewFile();
}}catch(IOException e1){
}
try{
FileWriter fileWritter = new FileWriter(newfil);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("<xml>");
bufferWritter.write("<books>");
bufferWritter.write("<id>"+id[i]+"</id>");
bufferWritter.write("<name>"+name[i]+"</name>");
bufferWritter.write("<download>"+download[i]+"</download>");
bufferWritter.write("<size>"+size[i]+"</size>");
bufferWritter.write("<author>"+author[i]+"</author>");
bufferWritter.write("<genre>"+genre[i]+"</genre>");
bufferWritter.write("<new>0</new>");
bufferWritter.write("</books>");
bufferWritter.write("</xml>");
bufferWritter.close();
Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_LONG).show();
}catch(IOException e1){
e1.printStackTrace();
Toast.makeText(getApplicationContext(), "error wrting xml "+e1.toString(), Toast.LENGTH_LONG).show();
}
downloadallStarted();
downloadallfiles();
//checkdownloadall();
//downloadallFinished();
}
}catch (Exception e1){
Toast.makeText(getApplicationContext(), "Error in downloadall: " +e1.toString(), Toast.LENGTH_LONG).show();
}
}
And here is my async task
private void startDownloadall() {
String fileURL = dload_all;
fileURL = fileURL.replace(" ", "%20");
new DownloadFileAsync1().execute(fileURL);
Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
}
class DownloadFileAsync1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String fileURL = dload_all;
fileURL = fileURL.replace(" ", "%20");
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = getDir("ebook", MODE_PRIVATE).toString();
String ebookfile = "";
//String filename = id[index];
String filename = id_all;
if(fileURL.endsWith("pdf"))
ebookfile = filename+".pdf";
else
ebookfile = filename+".epub";
bookfile = ebookfile;
Global.setBookfile(bookfile);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, ebookfile);
FileOutputStream fos = new FileOutputStream(outputFile);
lenghtOfFilee = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
//publishProgress("" + (int)((total*100)/lenghtOfFilee));
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
// Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// Log.d("ANDRO_ASYNC",progress[0]);
//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
Global.setBookfile(bookfile);
Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
checkdownloadall();
//dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
An asynchronous task runs on a background thread, so you directly access variable dload_all in function doInBackground() that is not thread safe. Maybe you can try:
private void startDownloadall() {
//String fileURL = dload_all;
//fileURL = fileURL.replace(" ", "%20");
new DownloadFileAsync1().execute(dload_all, id_all);
Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
}
class DownloadFileAsync1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String fileURL = args[0];
fileURL = fileURL.replace(" ", "%20");
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = getDir("ebook", MODE_PRIVATE).toString();
String ebookfile = "";
//String filename = id[index];
String filename = args[1];
if(fileURL.endsWith("pdf"))
ebookfile = filename+".pdf";
else
ebookfile = filename+".epub";
bookfile = ebookfile;
Global.setBookfile(bookfile);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, ebookfile);
FileOutputStream fos = new FileOutputStream(outputFile);
lenghtOfFilee = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
//publishProgress("" + (int)((total*100)/lenghtOfFilee));
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
// Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// Log.d("ANDRO_ASYNC",progress[0]);
//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
Global.setBookfile(bookfile);
Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
checkdownloadall();
//dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Related
I want to download zip file from server by using ksoap liabry.I am getting data in base64 please give solution that how to convert base64 and save it as zip file
byte[] bytes;
byte[] data = result.getBytes("UTF-8");
File outputFile = new File(mediaStorageDir.getAbsolutePath(), + "filename.zip");
new FileOutputStream(outputFile);
bytes = Base64.decode(data, Base64.DEFAULT);
File filepath = new File(Environment.getExternalStorageDirectory(), "Folder/" + "filename.zip");
OutputStream pdffos = new FileOutputStream(filepath);
pdffos.write(bytes);
pdffos.flush();
pdffos.close();
This Code help me to downlad apk and store to sd card.
This may help you also..
public class SaveInBackground extends AsyncTask<String,Integer,String> {
View v;
OutputValue ov;
Boolean isError= false;
public SaveInBackground(View v,OutputValue ov){
this.v = v;
this.ov = ov;
}
#Override
protected void onPreExecute(){
Message.setText("Downloading...");
isToLoop =true;
new Thread(new Runnable() {
#Override
public void run() {
while (isToLoop) {
SystemClock.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
int count = bar.getProgress() + 1;
bar.setProgress(count);
}
});
if(isToLoop)
break;
}
}
}).start();
}
#Override
protected void onProgressUpdate(Integer... values) {
bar.setProgress(values[0]);
}
#Override
protected String doInBackground(String... params) {InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(Globle.Infosoft_serverLink.replace("/Service.asmx/","")+ov.url);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
isError = true;
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
//publishProgress(80);
String path = Environment.getExternalStorageDirectory()+"/"+ov.Name+".apk";
output = new FileOutputStream(path );
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
return path;
}
catch (Exception e) {
isError =true;
Snackbar.make(v,"Error while accessing storage.",Snackbar.LENGTH_LONG).show();
return null;
}finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
#Override
protected void onPostExecute(String result){
if(!isError) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(result)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Message.setText("Downloaded");
reset(v);
}
}
I simply want to download mp4 or .3gp files from server to android device. I have tried multiple ways to achieve but in some cases it gives IOException and some time give ProtocolException
First Method to download Video using DownloadVideoTask.class
public class DownloadVideoTask extends AsyncTask<String, Integer, Boolean>
{
String nameOfSong;
Context context;
Boolean flage = true;
ProgressDialog progressDialog2;
#SuppressLint("InlinedApi")
public DownloadVideoTask(Context context,String trackTitle)
{
this.context = context;
nameOfSong = trackTitle;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
progressDialog2 = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
}
else
{
progressDialog2 = new ProgressDialog(context);
}
progressDialog2.setIndeterminate(false);
progressDialog2.setMax(100);
progressDialog2.setTitle("Please wait...");
try
{
progressDialog2.setMessage("Downloding.. " + nameOfSong.substring(0, 20));
}
catch (Exception e)
{
progressDialog2.setMessage("Downloding Song...." );
}
progressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog2.show();
}
#Override
protected Boolean doInBackground(String... params)
{
/* String trackTitle = params[0];
nameOfSong = trackTitle;
*/
String trackUrl = params[0];
try
{
File root;// = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
root = Environment.getExternalStorageDirectory();
}
else
{
root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
File dir = new File(root.getAbsolutePath() + "/XarDownloder");
if (dir.exists() == false)
{
dir.mkdirs();
}
URL url = new URL(trackUrl);
File file = new File(dir, nameOfSong);
URLConnection urlConnection = url.openConnection();
int fileLength = urlConnection.getContentLength();//ye statement inputStream k bad likhi thi
InputStream inputStream = urlConnection.getInputStream();
OutputStream outputStream = new FileOutputStream(
root.getAbsolutePath() + "/XarDownloder/" + nameOfSong
+ ".mp4");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
try
{
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
else
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))));
}
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.fromFile(file)));
}
catch (Exception e)
{
}
return true;
}
catch (IOException e)
{
flage = false;
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if (result)
{
try
{
Toast.makeText(context,
nameOfSong.substring(0, 30) + "Downloaded...",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(context,
"Song Downloaded...",
Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(context, "Sorry, song is not downloadable",
Toast.LENGTH_LONG).show();
}
progressDialog2.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progressDialog2.setProgress(values[0]);
}
}
Second Method using DownloadFile
public class DownloadFile extends AsyncTask<String, Integer, String>
{
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
public DownloadFile()
{
}
#Override
protected String doInBackground(String... params)
{
int count;
try
{
mp4load(videoToDownload);
}
catch (Exception e)
{
// TODO: handle exception
}
/*try
{
URL url = new URL(videoToDownload);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/xarwere/firstdownload.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
return null;
}
public void mp4load(String urling)
{
try
{
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
//Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "test.mp4";
File outputFile = new File(file, fileName);
if (!outputFile.exists())
{
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();//my doctory
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (ProtocolException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
Where videoToDownload in DownloadFile.class is the URLi want to download. but at inputStream it gives exception.
And I call these AsyncTask like
new DownloadFile().execute();
new DownloadVideoTask(TestingActivity.this, "nameofsong").execute("http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4");
I slighthly modified your code, but it downloads the file well. Did you add the internet permission?
public class DownloadFile extends AsyncTask<String, Integer, String> {
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
#Override
protected String doInBackground(String... params) {
int count;
try {
mp4load(videoToDownload);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
public void mp4load(String urling) {
try {
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "test.mp4";
File outputFile = new File(downloadsPath, fileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm trying to figure out why my inputstream isn't working correctly. I am trying to connect to a server and get a JSON string and save it into the variable inputJSON. However inputJOSN is empty because my inputstream isn't working correctly. This line of code:
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
doesn't seem to be working properly and I'm not sure why?
public class AndroidClient extends ProfileActivity {
private TextView textIn;
public Thread rt;
public Socket socket = null;
public PrintWriter outputstrwr;
public OutputStream out = null;
public DataOutputStream dataOutputStream = null;
public DataInputStream dataInputStream = null;
public InputStream inputStr = null;
private final static String LOG_TAG = AndroidClient.class.getSimpleName();
private final Handler handler = new Handler();
private List<Profile> serviceInfoList = new ArrayList<Profile>();
// Map between list position and profile
private Map<Integer, Profile> posMap = new HashMap<Integer, Profile>();
private Map<String, Integer> addressMap = new HashMap<String, Integer>();
private static String profilePicBase64Str="";
private String inputJSON = "";
private String outputJSON = "";
private String outputJSONserv = "";
private Profile p;
//String urlInputStream = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e(LOG_TAG, "Before OnCreate() Try");
try {
Log.e(LOG_TAG, "In OnCreate() Try");
socket = new Socket("23.23.175.213", 9000); //Port 1337
Log.e(LOG_TAG, "Created Socket");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Log.e(LOG_TAG, "Created DataOutputStream");
dataInputStream = new DataInputStream(socket.getInputStream());
Log.e(LOG_TAG, "Created DataInputStream");
//out = new OutputStream();
out = socket.getOutputStream();
inputStr = socket.getInputStream();
//Thread readjsonthrd = new Thread(new ReadJSONThread());
//inputstrrd = new InputStreamReader(socket.getInputStream());
p = new Profile();
Log.e(LOG_TAG, "Created Profile Instance");
//Gets the local profile via JSON and converts into Profile type
Gson gson = new Gson();
Log.e(LOG_TAG, "Created Gson Instance" + "GetProfileJSONStr:" + p.getProfileJSONStr());
p = gson.fromJson(p.getProfileJSONStr(), Profile.class);
setProfile(p);
Log.e(LOG_TAG, "Converted Profile to JSON");
//Gson gson = new Gson();
Log.e(LOG_TAG, "Before: outputJSON = gson.toJson(p);");
outputJSON = gson.toJson(p).toString();
outputJSON = removeExcessStr(outputJSON);
Log.e(LOG_TAG, "ProfilePicStr Base64:"+p.getProfilePicStr());
outputJSON = outputJSON.replace("Name","name");
outputJSON = outputJSON.replace("TagLine","message");
outputJSON = outputJSON.replace("Title","title");
outputJSON = outputJSON.replace("Company", "company");
outputJSON = outputJSON.replace("Industry","industry");
outputJSON = outputJSON.replace("WhatIDo","whatido");
outputJSON = outputJSON.replace("WhoDoIWantToMeet","meetwho");
outputJSON = outputJSON.replace("WHOOZNEAR_PROFILEPIC","photo");
outputJSON = outputJSON.replaceAll("[c][o][n][t][e][n][t][:][/][/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+", getPicBase64Str()); /*"helloworld2"*/
if (!outputJSON.contains(",\"photo\":")) {
outputJSON = outputJSON.replace("}",",\"photo\":"+"\"IconnexUs\"}");
outputJSON = outputJSON.replace("}",",\"photo\":"+"\""+getPicBase64Str()+"\"}");
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"}");
}
else {
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"");
}
outputJSONserv = "{\"to\":\"broadcast\",\"type\":\"1\",\"payload\":"+outputJSON+"}";
Log.e(LOG_TAG, "Created outputJSON:" + outputJSON);
Log.e(LOG_TAG, "Created outputJSON Server:" + outputJSONserv);
JSONObject outObject = new JSONObject();
try {
outObject.put("photo", "hello");
outObject.put("type", "50");
outObject.put("payload", outputJSON);
outputJSON = gson.toJson(outObject).toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Value of PROFILEPIC STRING FROM PROFILEMAP: "+profileMap.get("WHOOZNEAR_PROFILEPIC"));
p.setProfilePicStr(ConvertandSetImagetoBase64(profileMap.get("WHOOZNEAR_PROFILEPIC")));
//String headerJSON = gson.toJson(outObject).toString();
outputJSON = outputJSON.substring(nthOccurrence(outputJSON, '{', 2)-1, nthOccurrence(outputJSON, '}', 1)-1);
String input = "["+"Ryan"+"[";
//"[foo".replaceAll(Pattern.quote("["), "\"");
String result = input.replaceAll(Pattern.quote("["), "\"");
Log.e(LOG_TAG, "REGEX REPLACEALL:"+result);
outputstrwr = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
outputstrwr.write(outputJSONserv);
Log.e(LOG_TAG, "Base64 String:"+p.getProfilePicStr());
Log.e(LOG_TAG, "Sent dataOutputStream");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Before initEventHandlers");
initEventHandlers();
Log.e(LOG_TAG, "After initEventHandlers");
//refreshViewModels();
Log.e(LOG_TAG, "Start Repeat Thread");
rt = new Thread(new RepeatingThread());
rt.start();
Log.e(LOG_TAG, "Started Repeat Thread");
}
#Override
public void onDestroy() {
super.onDestroy();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPause(){
super.onPause();
rt.stop();
}
#Override
public void onResume(){
super.onResume();
if (rt.isAlive() == false) {
//rt.start();
}
}
#Override
public void onStop(){
super.onStop();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String removeExcessStr(String json_excess) {
//String myString = myString.replace("=\"ppshein\"", "");
String json_excess1 = json_excess.replace("\"nameValues\":{", "");
String myString = json_excess1.replace(",\"profileId\":1,\"valid\":false}", "");
return myString;
}
public static String adddblquotattr(String attr) {
String result = attr.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static String adddblquotval(String val) {
String result = val.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static int nthOccurrence(String str, char c, int n) {
int pos = str.indexOf(c, 0);
while (n-- > 0 && pos != -1)
pos = str.indexOf(c, pos+1);
return pos;
}
public void setPicBase64Str(String profilePicBase64Str) {
this.profilePicBase64Str = profilePicBase64Str;
}
public String getPicBase64Str() {
return profilePicBase64Str;
}
public String ConvertandSetImagetoBase64(String imagePath) {
String base64 = null;
byte[] input = null;
try{
FileInputStream fd = new FileInputStream(imagePath);
Bitmap bmt = BitmapFactory.decodeFileDescriptor(fd.getFD());
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap tmp = ProfileActivity.scaleDownBitmap(bmt, 10, this);
tmp.compress(Bitmap.CompressFormat.JPEG, 10, stream);
input = stream.toByteArray();
base64 = Base64.encodeToString(input, Base64.DEFAULT);
//LocalProfileActivity.input = input;
}catch(Exception e){
Log.e(LOG_TAG,"[ONACTIVITYRESULT] Could not bind input to the bytearray: " + e.getMessage());
}
}
catch (Exception e){
Log.e("LocalProfile", "ConvertandSetImagetoBase64: Could not load selected profile image");
}
return base64;
}
public String getStringFromBuffer(InputStreamReader inputstrread){
BufferedReader bRead = new BufferedReader(inputstrread);
String line = null;
StringBuffer jsonText = new StringBuffer();
try {
while((line=bRead.readLine())!=null){
jsonText.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonText.toString();
}
public String ConvertByteArrayToString(byte[] b) {
// byte[] to string
String input = new String(b);
return input;
}
public byte[] ConvertStringToByteArray(String str) {
// string to byte[]
byte[] bytes = str.getBytes();
return bytes;
}
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely stream ");
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static String writeFile(Bitmap finalBitmap) {
String filePath = "";
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream outFile = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath = root+"/saved_images/"+fname;
return filePath;
}
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
private int len = 0;
private byte[] input = new byte[len];
public RepeatingThread() {
//try {
Log.e(LOG_TAG, "Before inputJSON String");
//inputJSON = dataInputStream.readUTF();
//URL url = new URL("tcp://23.23.175.213:1337");
//inputJSON = dataInputStream.readUTF();
//inputstrrd = new InputStreamReader(socket.getInputStream());
String hello = "hello world";
//String inputJSON = getStringFromBuffer(new InputStreamReader(socket.getInputStream()));
//Convert
Log.e(LOG_TAG, "After inputJSON String:" + inputJSON);
/*}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//LOOK HERE FIRST
//inputJSON is what is received back from the server - Take the inputJSON
//String and use regular expressions HERE to remove all the other characters in the
//string except the payload JSON.
//refreshViewModels(inputJSON);
}
#Override
public void run() {
try {
//outputstrwr.write(outputJSONserv); //UNCOMMENT IF NEED TO SEND DATA TO GET JSON BACK
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "IN REPEATINGTHREAD-INPUTJSON:" + inputJSON);
refreshViewModels(inputJSON);
mHandler.postDelayed(this, 3000);
}
}
public void refreshViewModels(String inputJSON) {
try {
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
String[] from = new String[] { "profilePic", "neighborName",
"tagLine" };
int[] to = new int[] { R.id.avatar, R.id.username, R.id.email };
// prepare the list of all records
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
List<Profile> profiles = new ArrayList<Profile>();
// Clear the position mapping list and reset it
this.posMap.clear();
Log.i(LOG_TAG, "NEW inputJSON: " + inputJSON);
inputJSON = getPayloadStr(inputJSON);
Log.i(LOG_TAG, "NEW inputJSON2: " + inputJSON);
JSONArray profileArray = new JSONArray(inputJSON);
for (int i=0; i<profileArray.length(); i++) {
JSONObject jsonObject = profileArray.getJSONObject(i);
Gson gson = new Gson();
Profile p = gson.fromJson(gson.toJson(jsonObject).toString(), Profile.class);
profiles.add(p);
}
int pos = 0;
// Creates the fillMaps list for the listAdapter
Log.i(LOG_TAG, "Profiles size: " + profiles.size());
//showToast("Profiles size: " + profiles.size());
for (Profile p : profiles) {
// Create mapping for list adapter
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profilePic",
p.getAttributeValue("photo")== null? "Not Set" : p
.getAttributeValue("photo"));
map.put("neighborName",
p.getAttributeValue("Name") == null? "Not Set" : p
.getAttributeValue("Name"));
map.put("tagLine",
p.getAttributeValue("TagLine") == null? "Not Set" : p
.getAttributeValue("TagLine"));
fillMaps.add(map);
// Reset the postion mapping
this.posMap.put(pos++, p);
}
ListAdapter servicesListAdapter = new myAdapter(this, fillMaps,
R.layout.listitem, from, to);
servicesListView.setAdapter(servicesListAdapter);
} catch (Exception e) {
Log.e(LOG_TAG, "Error making list adapter: " + e.getMessage());
}
}
public String getPayloadStr(String profileString) {
Log.e("LOG_TAG", "Profile Str:"+profileString);
Pattern pattern = Pattern.compile(".*?payload\":(.*)\\}");
Log.e("LOG_TAG", "I got here 1");
Matcher matcher = pattern.matcher(profileString);
Log.e("LOG_TAG", "I got here 12");
//Matcher m = responseCodePattern.matcher(firstHeader);
matcher.matches();
matcher.groupCount();
//matcher.group(0);
Log.e("LOG_TAG", "I got here 2"+matcher.group(1));
return matcher.group(1);
}
private class myAdapter extends SimpleAdapter {
public myAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.listitem,
null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.username))
.setText((String) data.get("neighborName"));
((TextView) convertView.findViewById(R.id.email))
.setText((String) data.get("tagLine"));
// Convert a string representing an image back to an image
String base64 = ((String)data.get("profilePic"));
byte[] picBytes = Base64.decode(base64, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(picBytes, 0, picBytes.length);
//THE IF AND THE ELSE NEED TO BE SWITCHED
if (bitmap==null){
((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.btn_whooznear);
}else{
((ImageView) convertView.findViewById(R.id.avatar)).setImageBitmap(bitmap);
}
return convertView;
}
}
public void callProfileActivity(int position)
{
// Catch the case when service info is empty
if(serviceInfoList.size()==0){
return;
}
Profile profClick = posMap.get(position);
String b64Str = profClick.getAttributeValue("photo");
Intent startViewActivity = new Intent();
startViewActivity.putExtra("TransProfile", (Profile)posMap.get(position));
startViewActivity.putExtra("PhotoBase64", b64Str);
if(serviceInfoList.size()>position){
//DO SOMETHING HERE
}else{
Log.e(LOG_TAG,"Profile doesn't exist in sevice infoList? Selecting first one");
}
startViewActivity.setClass(this, ViewProfileActivity.class);
startActivity(startViewActivity);
}
/**
* Initialize the event handlers
*/
public void initEventHandlers() {
// Service List View
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
servicesListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Profile clickedProfile = posMap.get(position);
//showToast("Clicked Pos: " + position);
/*Intent intent = new Intent(ConnectActivity.this, ViewProfileActivity.class);
intent.putExtra("ClickProfile", posMap.get(position));*/
callProfileActivity(position);
}
});
}
/*#Override
public void onBackPressed() { // do something on back.
super.onBackPressed();
Intent myIntent = new Intent(AndroidClient.this, ProfileActivity.class);
startActivity(myIntent);
return;
}*/
}
Your code is rather long, so I cannot be sure of what exactly is the problem, but there is definitely an issue here:
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
If you are calling this right after sending your URL request, the server may not have had time to send the result back, so is.available() may return zero or another value less than the actual number of bytes you would hope would be available. Try code like this for reading in the file.
As the title says I am trying to get help simplifing my code. I have multiple buttons, now only three while I test this out but I plan on having approximately thirty button choices. Currently I have a very long section of code and I think it can be shortened drastically maybe using an array? But I'm not sure how to implement it correctly. IF anyone has done this before or has an idea please share! Thanks to everyone!
public class myDL extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filechoice);
mProgressDialog = new ProgressDialog(myDL.this);
mProgressDialog.setMessage("The file is now downloading, it will be saved on the SD card for future use. Please use WiFi to avoid operator charges.");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Button section = (Button) findViewById(R.id.section);
section.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent section = new Intent(view.getContext(),
section.class);
startActivity(section);
}
});
Button back = (Button) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_OK);
finish();
}
});
secOne = (Button) findViewById(R.id.secOne);
secOne.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startSecOne();
}
});
}
private void startSecOne() {
StartSecOne secOne = new StartSecOne();
secOne
.execute("www.website.com/document.pdf");
}
class StartSecOne extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
String isFileThere = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.pdf";
File f = new File(isFileThere);
if (f.exists()) {
showPdf();
} else {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(
url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mProgressDialog.dismiss();
showPdf();
} catch (Exception e) {
}
}
return null;
}
}
secTwo = (Button) findViewById(R.id.secTwo);
secTwo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startSecTwo ();
}
});
}
private void startSecTwo () {
StartSecTwo secTwo = new StartSecTwo ();
secTwo
.execute("www.website.com/document2.pdf");
}
class StartSecTwo extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
String isFileThere = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test2.pdf";
File f = new File(isFileThere);
if (f.exists()) {
showPdf();
} else {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(
url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test2.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mProgressDialog.dismiss();
showPdf();
} catch (Exception e) {
}
}
return null;
}
}
secThree = (Button) findViewById(R.id.secThree);
secThree.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startSecThree ();
}
});
}
private void startSecThree () {
StartSecThree secThree = new StartSecThree ();
secThree
.execute("www.website.com/document3.pdf");
}
class StartSecThree extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
String isFileThere = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test3.pdf";
File f = new File(isFileThere);
if (f.exists()) {
showPdf();
} else {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(
url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test3.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mProgressDialog.dismiss();
showPdf();
} catch (Exception e) {
}
}
return null;
}
}
private void showPdf() {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
final OnClickLisener listener = new OnClickListener() {
public void onClick(View v){
switch(v.getId()){
case R.id.zero:
break;
case R.id.one:
break;
case R.id.two:
break;
}
}
}
final int[] btnIds = new int[]{R.id.one, R.id.two, R.id.zero};
for(int i = 0; i < btnIds.length; i++) {
final Button btn = (Button)findViewById(btnIds[i]);
btn.setOnClickListener(listener);
}
I am using http://www.siegmann.nl/epublib to read epub file. My code is mentioned below.
try {
book = epubReader.readEpub(new FileInputStream("/sdcard/EpubTesting.epub"));
Resource res;
Spine contents = book.getSpine();
List<SpineReference> spinelist = contents.getSpineReferences();
StringBuilder string = new StringBuilder();
String line = null;
int count = spinelist.size();
for (int i=0;i<count;i++){
res = contents.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = (string.append(line+"\n")).toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(linez);
s1.loadDataWithBaseURL("/sdcard/",linez, "text/html", "UTF-8",null);
}catch (FileNotFoundException e) {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(mContext, "IO Exception.", Toast.LENGTH_SHORT).show();
}
Also tried
s1.loadDataWithBaseURL("",linez, "text/html", "UTF-8",null);
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
But result is sifar. Please tell me what I have to do to show the contained images in file. I have gone through FAQ says Make a subclass of android.webkit.WebView that overloads the loadUrl(String) method in such a way that it loads the image from the Book instead of the internet. But till I don't where they extract the file how can I locate the path. Please tell me. I am very confused. Thanks in advance.
public class EpubBookContentActivity extends Activity{
private static final String TAG = "EpubBookContentActivity";
WebView webview;
Book book;
int position = 0;
String line;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
AssetManager assetManager = getAssets();
String[] files;
try {
files = assetManager.list("books");
List<String> list =Arrays.asList(files);
if (!this.makeDirectory("books")) {
debug("faild to make books directory");
}
copyBookToDevice(list.get(position));
String basePath = Environment.getExternalStorageDirectory() + "/books/";
InputStream epubInputStream = assetManager.open("books/"+list.get(position));
book = (new EpubReader()).readEpub(epubInputStream);
DownloadResource(basePath);
String linez = "";
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
linez = linez.replace("../", "");
// File file = new File(Environment.getExternalStorageDirectory(),"test.html");
// file.createNewFile();
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// fileOutputStream.write(linez.getBytes());
// fileOutputStream.close();
webview.loadDataWithBaseURL("file://"+Environment.getExternalStorageDirectory()+"/books/", linez, "text/html", "utf-8", null);
} catch (IOException e) {
Log.e("epublib exception", e.getMessage());
}
}
public boolean makeDirectory(String dirName) {
boolean res;
String filePath = new String(Environment.getExternalStorageDirectory()+"/"+dirName);
debug(filePath);
File file = new File(filePath);
if (!file.exists()) {
res = file.mkdirs();
}else {
res = false;
}
return res;
}
public void debug(String msg) {
// if (Setting.isDebug()) {
Log.d("EPub", msg);
// }
}
public void copyBookToDevice(String fileName) {
System.out.println("Copy Book to donwload folder in phone");
try
{
InputStream localInputStream = getAssets().open("books/"+fileName);
String path = Environment.getExternalStorageDirectory() + "/books/"+fileName;
FileOutputStream localFileOutputStream = new FileOutputStream(path);
byte[] arrayOfByte = new byte[1024];
int offset;
while ((offset = localInputStream.read(arrayOfByte))>0)
{
localFileOutputStream.write(arrayOfByte, 0, offset);
}
localFileOutputStream.close();
localInputStream.close();
Log.d(TAG, fileName+" copied to phone");
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
Log.d(TAG, "failed to copy");
return;
}
}
private void DownloadResource(String directory) {
try {
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
Log.d(TAG, rs.getHref());
File oppath1 = new File(directory, rs.getHref().replace("OEBPS/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
System.out.println("Path : "+oppath1.getParentFile().getAbsolutePath());
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, rs.getHref());
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
}
}
}
For that you have to download all resources of epub files (i.e. images,stylesheet) in location where you downloaded .epub file in sdcard. please check below code to download images and css files from .epub files itself using epublib.
for that u have to send parameter of File objects where you want to store those images.
private void DownloadResource(File FileObj,String filename) {
try {
InputStream epubis = new FileInputStream(FileObj);
book = (new EpubReader()).readEpub(epubis);
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
File oppath1 = new File(directory, "Images/"
+ rs.getHref().replace("Images/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, "Styles/"
+ rs.getHref().replace("Styles/", ""));
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
Log.v("error", e.getMessage());
}
}
after this use this your code to set path of images in webview.
if stored in sd card then
s1.loadDataWithBaseURL("file:///sdcard/",linez, "text/html",null,null);
or
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
if in internal storage then
s1.loadDataWithBaseURL("file:///data/data/com.example.project/app_mydownload/",linez, "text/html",null,null);