Android - Fill string array with urls - java

I have a url "yyyyyyy.com/test.txt", which is a text file.
It contains urls of .mp3 audios.
yyyyyyy.de/1.mp3
yyyyyyy.de/2.mp3
yyyyyyy.de/3.mp3 //exactly like that
My intention was to read each line of this text file and store it in an array like
urls[0]=yyyyyyy.de/1.mp3
urls[1]=yyyyyyy.de/2.mp3 ...
this.
String[] urls;
int i=0;
Random rand;
int min=0;
int max=5; // I have 6 Urls in the text file
int randomNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rand = new Random();
randomNum = rand.nextInt((max - min) + 1) + min; //generates integer between 0-5
try {
// Create a URL for the desired page
URL url = new URL("yyyyy.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
urls[i]=str;
i++;
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
boolean isPLAYING = false;
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(urls[randomNum]);
mp.prepare();
mp.start();
} catch (IOException e) {
}
} else {
isPLAYING = false;
}
}
I have already add in Manifest.xml the android:permission.
I don't know where the problem is...the app closes itself and tells me
that this line " mp.setDataSource(urls[randomNum]);" is wrong
Here LogCat : http://textuploader.com/5iw5b
Thanks in advance !!

Your array is NULL
put this code after super.onCreate
urls=new String[max]
Update 3:
try this:
ArrayList<String> urls=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Create a URL for the desired page
URL url = new URL("yyyyy.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Log.i("test","url count="+urls.size());
boolean isPLAYING = false;
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
int randomPos = new Random().nextInt(urls.size());
mp.setDataSource(urls.get(randomPos));
mp.prepare();
mp.start();
} catch (IOException e) {
}
} else {
isPLAYING = false;
}
}

Related

change text color with spannable

In the below code which is for bluetooth messaging with arduino i am trying to change color on some static strings.
1.On the start button listener i have a message"Connection opened" which i am changing color using the xml file and creating there a string with specific color. This method works only there.
2. i tried another method with spannable string on the send button listener but is not working at all the message comes in black.
what i want to to do is that when i send a message on my textview i see the "send data: "+ string(msg i send) and i want this send data to be red for examle and the same for the receive one.
What i tried untill now is on the code.If there is any idea to try i will be grateful.
public class MainActivity extends Activity {
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
//Thread thread;
byte[] buffer;
//int bufferPosition;
boolean stopThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = findViewById(R.id.buttonStart);
sendButton = findViewById(R.id.buttonSend);
clearButton = findViewById(R.id.buttonClear);
stopButton = findViewById(R.id.buttonStop);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
textView.setMovementMethod(new ScrollingMovementMethod());
setUiEnabled(false);
startButton.setOnClickListener(v -> {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
//textView.append("Connection Opened!");
String greenString = getResources().getString(R.string.Connection_Opened);
textView.append(Html.fromHtml(greenString));
}
}
});
sendButton.setOnClickListener(v -> {
String t = "Send Data: ";
SpannableString spannableString = new SpannableString(t);
ForegroundColorSpan green = new ForegroundColorSpan(getResources().getColor(R.color.private_green));
spannableString.setSpan(green, 0, 9, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
String string = editText.getText().toString();
String str = string.concat("\n");
try {
outputStream.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append(spannableString + str);
});
stopButton.setOnClickListener(v -> {
try {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("Connection Closed!");
}catch (IOException e){
e.printStackTrace();
}
});
clearButton.setOnClickListener(v -> textView.setText(""));
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(bluetoothAdapter !=null)
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
assert bluetoothAdapter != null;
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
//private final String DEVICE_NAME="ArduinoBT";
String DEVICE_ADDRESS = "98:DA:C0:00:2C:E2";
if(iterator.getAddress().equals(DEVICE_ADDRESS))
{
device=iterator;
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(() -> {
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes, StandardCharsets.UTF_8);
handler.post(() -> textView.append("Receive data: " + string));
}
}
catch (IOException ex)
{
stopThread = true;
}
}
});
thread.start();
}
}
Try like this;
Spannable text = new SpannableString("Send Data:");
text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.private_green)), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

java.lang.nullpointer error in android

I am making an app which will display the images of celebrities and 4 names out of which one is correct.
I have added a button "change" to change the celebrity in the image, but on pressing that button my app is crashing showing null java.lang.null pointer exception.
I have the the code for loading the image and four names in the oncreate method which loads the image and four names when the app is first started, but on pressing the button when the function is invoked , error is generated although i have that same code in it.
public class MainActivity extends AppCompatActivity {
//declaring all the widgets to be used
Bitmap celebimg;
Random rand;
ImageView img;
Button btn0, btn1, btn2, btn3;
int optionnum, imgnum;
ArrayList<String> celebnames = new ArrayList<String>();
ArrayList<String> celebimages = new ArrayList<String>();
ArrayList<String> buttonoptions = new ArrayList<String>();
//Invoked when one out of the four options is clicked
public void row(View view) {
if (view.getTag().toString().equals(Integer.toString(optionnum))){
Toast.makeText(this, "correct Answer", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "wrong Answer, It was" +
celebnames.get(imgnum), Toast.LENGTH_SHORT).show();
}
}
//Class for downloading of image
public class Imagedownload extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
Bitmap myimage = BitmapFactory.decodeStream(in);
return myimage;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
/**
* Class for downloading the website html code
*/
public class Download extends AsyncTask<String, Void, String > {
#Override
protected String doInBackground(String... strings) {
String result = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL(strings[0]);
connection = (HttpURLConnection)url.openConnection();
InputStream input = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int data = reader.read();
while(data != -1) {
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Code to execute when the change button is clicked
public void change(View view) {
rand = new Random();
imgnum = rand.nextInt(celebimages.size());
Imagedownload image = new Imagedownload();
try {
celebimg = image.execute(celebimages.get(imgnum)).get();
if (celebimg == null)
Log.i("its", "null douchebag");
img.setImageBitmap(celebimg);
} catch (InterruptedException e) {
if (celebimg == null)
Log.i("its", "null douchebag");
e.printStackTrace();
} catch (ExecutionException e) {
if (celebimg == null)
Log.i("its", "null douchebag");
e.printStackTrace();
}
optionnum = rand.nextInt(4);
for(int i = 0;i < 4;i++){
if(i == optionnum)
buttonoptions.add(celebnames.get(imgnum));
else {
int random = rand.nextInt(celebnames.size());
while (celebnames.get(imgnum) == celebnames.get(random)){
random = rand.nextInt(celebnames.size());
}
buttonoptions.add(celebnames.get(random));
}
}
btn0.setText(buttonoptions.get(0));
btn1.setText(buttonoptions.get(1));
btn2.setText(buttonoptions.get(2));
btn3.setText(buttonoptions.get(3));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.celeb);
btn0 = (Button)findViewById(R.id.btn0);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
String data = "";
Download load = new Download();
try {
data = load.execute("http://www.posh24.se/kandisar").get();
String[] splitdata = data.split("<div class=\"title\">Lista:</div>");
// seperating out the required img src from the html code
Pattern p = Pattern.compile("src=\"(.*?)\"");
Matcher M = p.matcher(splitdata[1]);
while (M.find()){
//adding all the img src values to celebimages arraylist
celebimages.add(M.group(1));
}
Pattern pi = Pattern.compile("alt=\"(.*?)\"");
Matcher Mi = pi.matcher(splitdata[1]);
while (Mi.find()) {
// adding all the alt values to celebnames arraylist
celebnames.add(Mi.group(1));
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Random rand = new Random();
imgnum = rand.nextInt(celebimages.size());
Imagedownload image = new Imagedownload();
Bitmap celebimg;
try {
//downloading the image from stored img src values from celebimages
//arraylist
celebimg = image.execute(celebimages.get(imgnum)).get();
img.setImageBitmap(celebimg);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//Setting the correct value in one button and random values in other
//three
optionnum = rand.nextInt(4);
for(int i = 0;i < 4;i++){
if(i == optionnum)
buttonoptions.add(celebnames.get(imgnum));
else {
int random = rand.nextInt(85);
while (celebnames.get(imgnum) == celebnames.get(random)){
random = rand.nextInt(celebnames.size());
}
buttonoptions.add(celebnames.get(random));
}
}
btn0.setText(buttonoptions.get(0));
btn1.setText(buttonoptions.get(1));
btn2.setText(buttonoptions.get(2));
btn3.setText(buttonoptions.get(3));
}
Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
The problem is because you're creating another variable for the image instead reusing the previous variable:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.celeb);
...
}
it should be
img = (ImageView)findViewById(R.id.celeb);
The problem usually happens because not using a readable naming convention such as the following:
Bitmap celebimg;
Random rand;
ImageView img;
Button btn0, btn1, btn2, btn3;
Use something like this for class scope variables:
Bitmap mBmpCeleb;
Random mRndSomeId;
ImageView mImvCeleb;
Button mBtnImageOne, mBtnImageTwo, mBtnImageThree, mBtnImageThree;
where the m character is an abbreviation of member which is telling that the variable is member of the class.
Use something like the following for a method scope variable:
ImageView imvCeleb = (ImageView) findViewById(R.id.celeb);

how to convert a .execute to just display right away on textview instead

adminpage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.dataList);
Button button = (Button) findViewById(R.id.rf);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
}
});
}
public static class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String movieName = finalObject.getString("movie");
int year = finalObject.getInt("year");
finalBufferedData.append(movieName + " - " + year + "\n");
}
//JSONObject finalObject = parentArray.getJSONObject(0);
return finalBufferedData.toString();
//return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mTextView.setText(result);
}
}
So base on this what i can conclude is.
1) JSONTASK will take the url and break them in to different string and link them together and return finalBufferedData.toString();
2) The onPostExecute will take the result and set it to mTextView.
3) onclicklistener will run the function and perform step 2 and display.
Question!
I don't see anywhere in the code that call the function onPostExecute(String result) <-- what is the result?? is it the return finalBufferedData.toString()?
I am running the same function in another activity, how do i display in TextView without the onClicklistener to execute it.
1. Yes.. it is the return value(finalBufferedData.toString()).It is the output (result/return) of doInBackground method.
2. Call in onCreate or onResume for executing without onClick. eg:-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// put the AsyncTask call here

Reading a text document's contents from a URL is always equal to null

Whenever I try to get a text document from Dropbox containing a version string, it says that it equals null even though it is supposed to equal 0.6.48. I've tried many different ways of getting the file, but its always returning null. Code:
new Thread() {
public void run() {
try {
URL textUrl = new URL(UPDATE_API); // UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1"
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
Soundboard.REMOTE_VERSION = stringText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
What am I missing? I'm building for API 23. I have put <uses-permission android:name="android.permission.INTERNET"/> in my Android manifest.
Your code worked for me with few changes:
String UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1";
private BufferedReader bufferReader = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
public void run() {
try {
URL textUrl = new URL(UPDATE_API);
bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer = "";
StringBuilder stringText = new StringBuilder();
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText.append(StringBuffer);
}
Log.d("--->", stringText.toString());
Soundboard.REMOTE_VERSION = stringText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
Try to close the BufferedReader in try..finally.
Use StringBuilder rather than String for concatenation

Android: Epub file not showing images in emulator/android device

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);

Categories