I am unable to figure out why I am stuck at this point although there is no error is my coding. My problem is actually, it doesn't print out my epub, as well as it just hangs there, till the not responding dialog comes up.
My code is as below:
package com.epub;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.Spine;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.epub.EpubReader;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;
public class EpubReaderActivity extends Activity {
WebView webView;
Book book;
TextView tv;
String line;
String linez;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = new TextView(this);
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
AssetManager am = getAssets();
try {
InputStream epubInputStream = am.open("testbook.epub");
book = (new EpubReader()).readEpub(epubInputStream);
} catch (IOException e) {
Log.e("epublib", e.getMessage());
}
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
tv.setText(Integer.toString(count));
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();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
webView.loadData(linez, "text/html", "utf-8");
}
}
Mind helping me out on this point?
An ANR(Application Not Responding) happens generally when you do a heavy job. In Android, if the OS can't execute one code line within about 5 seconds, the ANR dialog wil pop up. From your codes, it seems that you are reading and parsing an .epub file from your asset folder. I am not familiar with epub files, but I suspect this is a heavy task which blocks your app.
How about start a Thread or AsyncTask to read the file so the main thread would not be blocked?
Pu this code inside a thread as this takes time to write the data and load a web view
Thread is a different part of execution and you will have to wait for few sconds if yor file is large
you can also put a progress dialog to show loading of webview
new Thread(){
public void run() {
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();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
};
}.start();
More your file reading code form onCreaate() to onResume(). As data will be read once the UI show to user
Related
I'm trying to read website data with my Android app. What's strange is that it works on my Android 2.3.4 phone, but not my brand new 2nd Gen Nexus 7 Tablet that's running Android 4.3. I'm not getting any errors in LogCat, there's just nothing displayed on the Tablet. Has anyone else run into this? If so, clue me in to a fix so that it'll run on both my devices. Here's my whole Activity:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class WCBCCalendar extends Activity {
Button back_BTN;
TextView urlTest_TV;
String about_url_Str = "http://www. url to read";
String returned;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
back_BTN = (Button) findViewById(R.id.backCal_btn);
sunDate_TV = (TextView) findViewById(R.id.sunDate_TV);
npDate_TV = (TextView) findViewById(R.id.npDate_TV);
urlTest_TV = (TextView) findViewById(R.id.urlTest_tv);
GetWebInfo test = new GetWebInfo();
try {
returned = test.getInternetData();
urlTest_TV.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// --- END onCreate
// --- Classes, Methods
public class GetWebInfo {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI(about_url_Str);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity ().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) !=null ){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}//--- END class
// --- END all Classes, Methods
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
}
I'm a android noob on programming, but with some help of a few programms I can learn the basics. I would like to do a basic http get request to an arduino ethernetshield.
For this I've found some code, but I can't get it to work.
I'm allways stuck on the getResponse part with the code I've tried from several pages.
I've found the following page which gave me readable code:
How to work with an image using url in android?
Now I've created the following:
Press on a button and do a get to an url:
package adhttpget.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AdhttpgetActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pushbutton1(View view) {
Toast.makeText(getBaseContext(), "button press", Toast.LENGTH_SHORT).show();
Log.e("button", "pressed");
URL connectURL = new URL("http://192.168.0.48/?out=13&status=2");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn); // <-- THIS IS MY PROBLEM
}
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e("http", "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
}
Where can I find information to learn how to write the code correctly?
Or do you happen to have the answer in some kind of hint so I can learn from it?
You must create a BufferedReader passing the InputStream, then you can read strings
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then I recommend you make the connection (or read/write file) with a separeted thread from the Thread UI (use Thread, AsyncTask, Handler, etc) because that will improve your app.
http://developer.android.com/intl/es/guide/components/processes-and-threads.html
is there a way to change the urls without compiling the app or deployment once i pushed to the market? the url might change in future or point to different urls.
currently i am hardcoding the urls somethign like this:
try {
url = "http://ofertaweb.ro/android/sleepandlovemusic/" + songs_array[counter] + ".mp3";
mediaPlayer.setDataSource(url);
}
Do not hardcode your URL at project build time, consider writing code that dynamically resolve it at application run time. for example, you can create a static html page (contains a list of actual mp3 URLs), hardcode this static html page URL at project build time, every time your application starting running, query this static html page to get the up-to-date mp3 URL at application run time. there are many alternative way to achieve this, just give you some clue, hope this helps.
here is what i found a way to read the html file:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Get_Webpage {
public String parsing_url = "";
public Get_Webpage(String url_2_get){
parsing_url = url_2_get;
}
public String get_webpage_source(){
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(parsing_url);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
String html = "";
InputStream in = null;
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e) {
} catch (IOException e) {
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
try {
while((line = reader.readLine()) != null)
{
str.append(line);
}
} catch (IOException e) {
}
try {
in.close();
} catch (IOException e) {
}
html = str.toString();
return html;
}
}
then you read like this:
try {
Get_Webpage obj = new Get_Webpage("http://ofertaweb.ro/android/sleepandlovemusic/list_files.php");
directory_listings = obj.get_webpage_source();
} catch (Exception e) {
}
//Log.d("director listing", directory_listings);
songs_array = directory_listings.split(":::");
I would like to display Log.i results in my application. Is it possible? If so, how can I do it?
Here's a blogpost that does exactly what you need it to do. It has a complete code example on how to display the contents of the Logcat log. Here's the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
class ReadLogDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
} catch (IOException e) {
}
}
}
I have gone through all the examples and I can not seem to get this to work.
This is my current code:
package hello.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(str);
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
}
}
Assuming your Android device is online and you've granted your app the INTERNET permission, try this:
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder(100);
while ((str = in.readLine()) != null) {
sb.append(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(sb.toString());
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
Let me know if that works: you are currently looping until str is null, then using that null value.
A follow up on the answer, it worked after adding
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}