StackOverflowers!
I load some text from a webpage. Everything works fine, and shows up in the TextViews. But, when the blogs on the webpage have some words with special characters like an: é or something. My Textview show characters like these: Á©..
Can anybody tell what I need to import, call or something like that to show everything tidy?
Thanks,
UPDATE 1 + 2:
TextView intro_text = (TextView) item_view.findViewById(R.id.item_intro);
intro_text.setText(Html.fromHtml(current_post.get_intro()));
current_post.get_intro() is the adres where the loaded text is. :-) Because I use a listview with many rows..
EDIT:
public class connectTask extends AsyncTask<String, String, String> {
#SuppressWarnings({ "deprecation" })
#Override
protected String doInBackground(String... message) {
Log.v("Correct Load", "Starting ");
URL u;
InputStream is = null;
DataInputStream dis;
String s;
try {
Log.v("Connecting...");
u = new URL("http://.......");
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
Log.v("Connected");
try {
while ((s = dis.readLine()) != null) {
if (s.contains("post_wrapper")) {
for (int i = 0; i < j; i++) {
while ((s = dis.readLine()) != null) {
if (s.contains("post_intro")) {
break;
}
}
if (s != null) {
s = dis.readLine();
Log.v("Intro", s); intro[i] = s.substring(s.indexOf("<p>") + 3, s.indexOf("</p>"));
Log.e("Intro", "Found intro:" + intro[i]);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (MalformedURLException mue) {
System.out.println("Ouch - a MalformedURLException happened.");
mue.printStackTrace();
System.exit(1);
} catch (IOException ioe) {
System.out.println("Oops- an IOException happened.");
ioe.printStackTrace();
System.exit(1);
} finally {
try {
if (is != null)
is.close();
} catch (IOException {
}
}
return null;
}
This is the read/received part.
Replace
DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
With
BufferedReader dis = new BufferedReader(new InputStreamReader(is, "UTF-8"));
Because DataInputStream.readLine() is deprecated and is discouraged for the following reason:
This method cannot be trusted to convert bytes to characters correctly.
BufferedReader also has a readLinemethod, so the rest of your code should be pretty much unchanged.
Also, whenever you use #SuppressWarnings({ "deprecation" }) I strongly suggest that you be extra careful and make sure you can use the deprecated method despite the warning.
tricky but worked for me: use Html.fromHtml() twice , I mean:
text.setText(Html.fromHtml(Html.fromHtml(your_html_text).toString()));
EDIT .
Your problem is not in this TextView because you are getting broken encoding even in your logcat,
so you should know when exactly , the encoding is broken ; this get_intro() is returning a bad string, so you should show us , what is this get_intro() doing ? how is it taking the string ? from what ? you should share the code of this get_intro() else nobody can help you...
Related
In java, after getting root permissions, how can I open files with it? Can I open them with File class or do I have to use a command?
You will have to use the su command.
I suggest you have a look at how to use su
Sample code to read a file ( I haven't tested it but it should give you an idea ):
public static void runAsRoot(String[] cmds){
try {
Process p = Runtime.getRuntime().exec("su");
BufferedReader reader = new BufferedReader(p.getInputStream());
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line); // add everything to StringBuilder
// here you can have your logic of comparison.
if(line.toString().equals(".")) {
// do something
}
}
} catch(IOException e) {
e.printStackTrace();
} catch(InterruptedException e) {
e.printStackTrace();
}
after some research I figured out the easiest way for me to download an image and store it into a file.
This is my code so far:
public boolean descargarArchivo(String url, String outputDirectory) {
try {
File img = new File(outputDirectory);
URLConnection conn = new URL(url).openConnection();
conn.connect();
try (InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(img)) {
int b = 0;
while (b != -1) {
b = in.read();
if (b != -1) {
out.write(b);
}
}
}
return true;
} catch (IOException ioe) {
ioe.printStackTrace();
}
return false;
}
The issue with this code, is that it sometimes performs a wrong download of the picture. Let me clear the idea with an example:
While the first picture is the original image (and the output file should be like that), the second picture is the real output file of the image, performed by that code, which is, clearly wrong (ignore the resolution, I'm just talking about this "wrong pixels"). Is there any way to improve this? Should I change the way to download images from the web?
This is how I read images from a URL:
try {
final InputStream inputStream = createInputStream(new URL(getImgUrl()));
try {
return ImageIO.read(inputStream);
} finally {
inputStream.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
//e.printStackTrace(); in case of error, will try again
} catch (IOException e) {
e.printStackTrace();
}
using
protected InputStream createInputStream(URL url) throws IOException {
URLConnection con = url.openConnection();
con.setConnectTimeout(500);
con.setReadTimeout(200);
return con.getInputStream();
}
I have an app which should execute some root commands.
SuperSU version is 1.04.
Su version is 1.02.
Android 4.1.1.
Device is Samsung Galaxy S3 - rooted.
The problem is I cannot get a permission prompt from SuperSU.
I've tried many things, but prompt never shows up.
For RootChecker basic, ADB and other apps it shows up.
Here is my procedure - maybe I'm doing something wrong.
private static String runShellCommand(String command) {
DataOutputStream os = null;
Process process = null;
try {
String [] env = {"PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin"};
process = Runtime.getRuntime().exec("su", env, Environment.getExternalStorageDirectory() );
os = new DataOutputStream(process.getOutputStream());
InputStreamHandler err = new InputStreamHandler(process.getErrorStream(), false);
InputStreamHandler out = new InputStreamHandler(process.getInputStream(), false);
os.writeBytes(command + "\n");
os.flush();
os.writeBytes(EXIT);
os.flush();
os.close();
Log.d(LOGTAG, "Waiting on: " + process.waitFor());
String errOut = err.getOutput();
String stdOut = out.getOutput();
Log.d(LOGTAG, "Exit code: " + process.exitValue());
Log.d(LOGTAG, command + " erroutput: [" + errOut + "]");
Log.d(LOGTAG, command + " output: [" + stdOut + "]");
if (errOut != null && !errOut.equals(""))
return errOut;
else if (stdOut != null&& !stdOut.equals(""))
return stdOut;
else
return null;
} catch (Exception e) {
Log.e(LOGTAG, "runShellCommand error: ", e);
return null;
} finally {
try {
if (os != null) {
os.close();
}
if (process != null) {
Log.d(LOGTAG, "Exit val: " + process.exitValue());
process.destroy();
}
} catch (Exception ignored) {}
}
}
InputStream handler is:
private static class InputStreamHandler extends Thread {
private final InputStream stream;
private final boolean devNull;
StringBuffer output;
public String getOutput() {
return output.toString();
}
InputStreamHandler(InputStream stream, boolean devNull) {
this.devNull = devNull;
this.stream = stream;
output = new StringBuffer();
start();
}
#Override
public void run() {
try {
if (devNull) {
while (stream.read() != -1) {}
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while (true) {
String line = br.readLine();
if (line == null) {
Log.d(LOGTAG, "Ended with reading!");
br.close();
return;
}
output.append(line);
}
}
} catch (IOException ignored) {
Log.e(LOGTAG, "Error", ignored);
}
}
}
Anyone have an idea why does it block so it doesn't show permission window?
Thanks.
I'm not exactly sure why this wouldn't work. The first thing that strikes me as odd is passing Environment.getExternalStorageDirectory() to exec. Maybe this (path) is not allowed (to execute from) ?
Why not simply use libsuperuser, written specifically to perform this very task ? It is open source, tiny, fully commented, has an example project, and even a document detailing the common problems you may encounter when trying to do this very operation.
I finally figured it out. The trick is to create a process (execute Runtime.getRuntime().exec("su");) separately in another thread. I'm not sure why this works, but it does.
Similar way is used in RootTools.
This has solved my problem.
I had posted a question in regards to this code. I found that JTextArea does not support the binary type data that is loaded.
So my new question is how can I go about detecting the 'bad' file and canceling the file I/O and telling the user that they need to select a new file?
class Open extends SwingWorker<Void, String>
{
File file;
JTextArea jta;
Open(File file, JTextArea jta)
{
this.file = file;
this.jta = jta;
}
#Override
protected Void doInBackground() throws Exception
{
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null)
{
publish(line);
line = br.readLine();
}
}
finally
{
try
{
br.close();
} catch (IOException e) { }
}
return null;
}
#Override
protected void process(List<String> chunks)
{
for(String s : chunks)
jta.append(s + "\n");
}
}
You could cover the most by sniffing the mime type based on the file extension or, even better, the actual file content. You can do that with help of among others jMimeMagic (Maven coords here). If the mime type does not start with "text", then it's certainly not a text file.
String mimeType = Magic.getMagicMatch(file, false).getMimeType();
boolean text = mimeType.startsWith("text");
I found that MIME types can really help with this!
JAF
For those who read this and are curious as to what I have done to fix the File reading problem.... I have instead implemented a FileReader and have experienced no problems on Windows. I have however noticed on Linux that there are some problems which tends to lead to a crash. Also I noticed when running through an IDE such as Netbeans I receive various runtime errors when trying to load a binary file and massive slow-down; but when I execute the .jar as an executable and not from the IDE it works fine.
Here is relevant code that I have had no problem with (even when loading binary file types such as .mp3, .exe, etc.)
/*...*/
#Override
protected Void doInBackground() throws Exception {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
int ch = br.read();
while(ch != -1) {
publish(ch);
ch = br.read();
}
}
finally {
try {
br.close();
} catch (IOException e) {}
}
System.gc();
return null;
}
/*...*/
I'm trying to enter some value in external application using Java.
Java application looks like this:
Runtime runtime = Runtime.getRuntime();
// ... str build ...
proc = runtime.exec(str);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
bw.write(value);
bw.flush();
bw.close();
if (proc.waitFor() != 0)
// error msg
// the end
Application hangs at waitFor method.
External application looks like this:
welcome banner
please enter 8 character input:
Welcome banner is printed using printf and input is taken with SetConsoleMode/ReadConsoleInput. ReadConsoleInput reads one char and they are masked with * character.
Help
you can use:
proc.getOutputStream().write("some date".getBytes())
keep in mind that you HAVE to read everything the app send to stdout and stderr, else it might get stuck writing there.
I use a generic class to read it in a different thread.
usage is like:
InputStreamSucker inSucker = new InputStreamSucker(proc.getInputStream());
InputStreamSucker errSucker = new InputStreamSucker(proc.getErrorStream());
proc.waitFor();
int exit = process.exitValue();
inSucker.join();
errSucker.join();
InputStreamSucker code is here:
public class InputStreamSucker extends Thread
{
static Logger logger = Logger.getLogger(InputStreamSucker.class);
private final BufferedInputStream m_in;
private final ByteArrayOutputStream m_out;
private final File m_outFile;
public InputStreamSucker(InputStream in) throws FileNotFoundException
{
this(in, null);
}
public InputStreamSucker(InputStream in, File outFile) throws FileNotFoundException
{
m_in = new BufferedInputStream(in, 4096);
m_outFile = outFile;
m_out = new ByteArrayOutputStream();
start();
}
#Override
public void run()
{
try
{
int c;
while ((c = m_in.read()) != -1)
{
m_out.write(c);
}
}
catch (IOException e)
{
logger.error("Error pumping stream", e);
}
finally
{
if (m_in != null)
{
try
{
m_in.close();
}
catch (IOException e)
{
}
}
try
{
m_out.close();
}
catch (IOException e)
{
logger.error("Error closing out stream", e);
}
if (m_outFile != null)
{
byte data[] = m_out.toByteArray();
if (data.length > 0)
{
FileOutputStream fo = null;
try
{
fo = new FileOutputStream(m_outFile);
fo.write(data);
}
catch (IOException e)
{
logger.error("Error writing " + m_outFile);
}
finally
{
try
{
if (fo != null) fo.close();
}
catch (IOException e)
{
logger.error("Error closing " + m_outFile);
}
}
}
}
}
}
public String getOutput()
{
return new String(m_out.toByteArray());
}
}
Got the answer! The trick is to use WriteConsoleInput() API because program expects keyboard event, not text ... That's why the waitFor() waited forever! :)