Not Reading text from server - java

I am trying to read all the text from server, I think that my code is not retrieving text from server will you please help me how can I fix this problem, I am new to android development. Thanks in advance
public class TestActivity 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.my_text);
try {
URL url = new URL("http://www.google.com:80/");
StringBuilder content = new StringBuilder();
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
content.append(line +"\n");
}
tv.setText(content.toString());
setContentView(tv);
in.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
};
}

Take these lines
tv.setText(line);
setContentView(tv);
out of while loop
Use StringBuilder object (declared before loop) in while loop and append the strings in that.
After while loop take string from StringBuilder and do tv.setText(string)

May be you can try like this, just a thought only :
StringBuilder content = new StringBuilder();
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(new URL("http://www.google.com:80/").openConnection().getInputStream()));
String line;
while ((line = in.readLine()) != null) {
content.append(line +"\n");
}
tv.setText(content.toString());
setContentView(tv);

Related

Reading a text file into ListView (app adds to ListView twice)?

I'm relatively new to Android Studio. Basically what I'm trying to do is create a sort of a history file for a QR scanner. Anything I scan goes into a History.txt file. It's working but not the way I intended. This was the result of checking the history after the first scan:
And this is what happens when I check the second scan:
This is my OutputWriter code:
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("History.txt", Context.MODE_APPEND));
outputStreamWriter.write(rawResult.getText()); // the scan result
outputStreamWriter.append("\n\r");
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
And this is the Activity that displays the history:
public class ResultsActivity extends AppCompatActivity {
ListView ResultsListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
ResultsListView = (ListView) findViewById(R.id.ResultsListView);
readFromFile();
}
private String readFromFile() {
String ret = "";
ArrayList<String> lines = new ArrayList<>(); // stores lines from text file.
try {
InputStream inputStream = openFileInput("History.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine() ) != null ) {
stringBuilder.append(receiveString);
lines.add(stringBuilder.toString());
}
inputStream.close();
// put results in ListView
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, lines);
ResultsListView.setAdapter(adapter);
}
} catch (FileNotFoundException e) {
Log.e("Exception", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("Exception", "Can not read file: " + e.toString());
}
return ret;
}
}
I'm not sure why things are appearing twice in the ListView. Looked at it for sometime but didn't see anything. My apologies if this happens to be a simple error. I'm still getting familiar with Android Studio. Any bit of help would be greatly appreciated. Thank you very much.
I'm looking at this code:
while ( (receiveString = bufferedReader.readLine() ) != null ) {
stringBuilder.append(receiveString);
lines.add(stringBuilder.toString());
}
You are appending a line to stringBuilder, then adding the entire string to the adapter so some lines will get added multiple times. I think you mean to do this:
while ( (receiveString = bufferedReader.readLine() ) != null ) {
stringBuilder.append(receiveString);
lines.add(receiveString);
}
Maybe you don't really need stringBuilder.

Java: Can't convert string to array

I can't convert a string to an array!
String text = "";
String[] textsplit = {};
//Stuff
The app set the content of an online txt file in a string:
The online txt file contain: hello,my,name,is,simone
[...] //Downloading code
text = bo.toString(); //Set the content of the online file to the string
Now the string text is like this:
text = "hello,my,name,is,simone"
Now i have to convert the string to an array that must be like this:
textsplit = {"hello","my","name","is","simone"}
so the code that i use is:
textsplit = text.split(",");
But when i try to use the array the app crash! :(
For example:
textview.setText(textsplit[0]); //The text of the textview is empity
textview.setText(textsplit[1]); //The app crash
textview.setText(textsplit[2]); //The app crash
etc...
where am I wrong? thanks!
EDIT: This is the code:
new Thread() {
#Override
public void run() {
String path ="http://www.luconisimone.altervista.org/ciao.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
text = bo.toString();
testo.setText("(" + text + ")");
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// Here all variables became empity
textsplit = text.split(",");
datisplittati.setText(textsplit[0]);
Try :
String text = "hello,my,name,is,simone";
String[] textArr = text.split(Pattern.quote(","));
You can get string using AsyncTask
private class GetStringFromUrl extends AsyncTask<String, Void, String> {
ProgressDialog dialog ;
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog when downloading
dialog = ProgressDialog.show(MainActivity.this, null, "Downloading...");
}
#Override
protected String doInBackground(String... params) {
// #BadSkillz codes with same changes
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(entity);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String result = total.toString();
Log.i("Get URL", "Downloaded string: " + result);
return result;
} catch (Exception e) {
Log.e("Get Url", "Error in downloading: " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO change text view id for yourself
TextView textView = (TextView) findViewById(R.id.textView1);
// show result in textView
if (result == null) {
textView.setText("Error in downloading. Please try again.");
} else {
textView.setText(result);
}
// close progresses dialog
dialog.dismiss();
}
}
and use blow line every time that you want:
new GetStringFromUrl().execute("http://www.luconisimone.altervista.org/ciao.txt");
You're using new thread to get data from an url. So in runtime, data will be asynchronous.
So when you access text variable (split it), it's still not get full value (example reason: network delay).
Try to move the function split after text = bo.toString(); , I think it will work well.

Problems understanding context and contextwrapper

I'm not able to understand these classes. I've been trying to create a new file in a new directory on my internal storage, put some text in it and then to read it out. This does not seem to work without the ContextWrapper. So I tried this:
public class DownloadActivity extends Activity {
...
class Download extends AsyncTask<String, Void, String>{
....
private void searchAndSave(String s) throws IOException {
....
ContextWrapper cw = new ContextWrapper(getBaseContext());
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
File fileInFolder = new File(folder, "fileInFolder");
String string = "Hello world!";
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
File fl = new File(cw.getDir("folder", Context.MODE_PRIVATE)+"/fileInFolder");
FileInputStream fin = new FileInputStream(fl);
BufferedReader reader = new BufferedReader(
new InputStreamReader(fin));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
reader.close();
fin.close();
}
}
Creating the file does not work without the ContextWrapper. I've been reading a lot, but I still have problems to understand, what the Context and the Contextwrapper actually do and why I need them to create a file. Additionally in my code the creating of the FileInputStream does not work. When the program reaches
FileInputStream fin = new FileInputStream(fl);
I always get the error:
05-21 11:18:25.721: W/System.err(7344): java.io.FileNotFoundException:
/data/data/com.example.dice/app_folder/fileInFolder: open failed:
ENOENT (No such file or directory)
I really would appreciate some help with understanding and solving this problem.
UPDATE: I made a more spare Activity, maybe now it's easier to reconstruct the whole thing. (Should I have done this in a new answer, or is it okay to edit my first posting?) Even though I don't get an error message when trying to create a file, is doesn't seem to work. Here I try reading the "Hello world" string, but I get a FileNotFoundException (EISDIR). Just for you to know :)
public class FolderActivity extends Activity {
public final static String TAG = "FolderActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_folder);
Button button = (Button) findViewById(R.id.button_folder);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
folder();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void folder() throws IOException{
Log.d(TAG, "folder");
ContextWrapper cw = new ContextWrapper(getBaseContext());
Log.d(TAG, "cw = new ContextWrapper");
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
Log.d(TAG, "folder = cw.getDir");
File fileInFolder = new File(folder, "fileInFolder");
Log.d(TAG, "fileInFolder = new File");
/*Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());*/
String string = "Hello world!";
// Aksioms suggestion
if (!fileInFolder.exists() && !fileInFolder.mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder);
} else { Log.d(TAG, "file created"); }
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());
String s = fileInFolder.getAbsolutePath();
try {
getStringFromFile(s);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
}
You are trying to open a file which does not exists.
Make sure that you check and create the file if it does not exsist:
if (!fl.exists() && !fl.mkdirs()) {
Log.e("file", "Couldn't create file " + fl);
}
EDIT:
Yes the getDir creats the folder if it is not created.
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
But the problem is here
File fileInFolder = new File(folder, "fileInFolder");
String string = "Hello world!";
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
In here you try to open a file that does not exsist, you just constructed a new file named fileInFolder, but you actually do not have that folder yet.
Try to use the code that I wrote at the first place, before the openFileOutput("fileInFolder", Context.MODE_PRIVATE); :
if (!fileInFolder.exists() && !fileInFolder.mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder);
}
Try this and tell me how it goes.
EDIT 2:
OK I found the problem it was so obvious. The mistake was that we created the fileInFolder as a directory, and you can not write anything there :D
What we should have done is this:
Remove my code for creating the fileInFolder.
if (!fileInFolder .exists() && !fileInFolder .mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder );
} else {
Log.d(TAG, "file created");
}
we do not need to create it because we will use it as a file. So the change I have made in your code is this:
FileOutputStream outputStream = new FileOutputStream(fileInFolder);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream));
out.write(string);
out.close();
Add this between the line String string = "Hello world!"; and the first Log.d... This is the correct way to write in a file.
The whole code:
public class MainActivity extends Activity {
public final static String TAG = "FolderActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button_folder);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
folder();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void folder() throws IOException {
Log.d(TAG, "folder");
ContextWrapper cw = new ContextWrapper(getBaseContext());
Log.d(TAG, "cw = new ContextWrapper");
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
Log.d(TAG, "folder = cw.getDir");
File fileInFolder = new File(folder, "fileInFolder");
Log.d(TAG, "fileInFolder = new File");
/*
* Log.d(TAG, "fileInFolder.getAbsolutePath()" +
* fileInFolder.getAbsolutePath());
*/
String string = "Hello world!";
FileOutputStream outputStream = new FileOutputStream(fileInFolder);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream));
out.write(string);
out.close();
Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());
String s = fileInFolder.getAbsolutePath();
try {
getStringFromFile(s);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getStringFromFile(String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
// Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}}
Check if you have this permission in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I hope everything is clear now.

Java Reading Text File And Saving Each Line As a New String Array

I'm trying to build an app that will read a text file , then store each line of text as an array list.
this is my text file:
1 , Where is the white house? , Paris , Amsterdam , New York , Washington
2 , The Sopranos Is a..? , Italian Food , Tv series , Kind of Knife , A Book
3 , The Capital City Of Brazil is? , Rio de Janeiro, Amsterdam , Brazilia , Washington
4 ,Who Invanted The Phone ?, Alexander Graham Bell, Albert Einstein , Pinokio , Snoop Doog
i'm basically trying to build an trivia app that will choose each line from the text file, then split the selected line into string array ,and finally print on the screen one question and four answers.
this is my code so far:
public class QuestionSql extends Activity {
private String[] value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
readFile();
}
private void readFile() {
// TODO Auto-generated method stub
AssetManager manger;
String line = null;
try {
manger = getAssets();
InputStream is = manger.open("text.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
value = line.split(",");
//System.out.print(value);
}
br.close();
} catch (IOException e1) {
System.out.println("not good");
}
}
}
the problem is that the app only print the last line of the text file
thank you for the answers, it really helped me!
this is my code so far:
public class QuestionSql extends Activity {
private String[] value;
private List<String[]> collection;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
readFile();
convertListToString()
}
private void convertListToString() {
value = collection.toArray(new String[collection.size()]);
}
private void readFile() {
// TODO Auto-generated method stub
AssetManager manger;
String line = null;
collection = new ArrayList<String[]>();
try {
manger = getAssets();
InputStream is = manger.open("text.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
value = line.split(",");
collection.add(value);
}
br.close();
} catch (IOException e1) {
System.out.println("not good");
}
}
}
now, i need to convert the :collection = new ArrayList();
into string[] so i could set the text on my app buttons. any ideas?
If you want to store each line into string array you need to create "structure of string arrays"
So the most efficient choice is to create List<String[]> that will hold your string arrays.
Reason why your approach didn't work was that you assigned for each line new values to same string array(which were rewritten, always) and after loop your string array contained values of last line.
List<String[]> collection = new ArrayList<String[]>();
String[] temp;
while ((line = br.readLine()) != null) {
temp = line.split(",");
if (temp.length > 0) {
collection.add(temp);
}
}
But if you want to create List that will contain only your values(i'm little confused) you can use:
List<String> collection = new ArrayList<String>();
String[] temp;
while ((line = br.readLine()) != null) {
temp = line.split(",");
if (temp.length > 0) {
for (String s: temp) {
collection.add(s);
}
}
}
You could store all split lines into an ArrayList :
private ArrayList<String[]> values;
#Override
protected void onCreate(Bundle savedInstanceState) {
values = new ArrayList<String[]>();
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
readFile();
}
private void readFile() {
// TODO Auto-generated method stub
AssetManager manger;
String line = null;
try {
manger = getAssets();
InputStream is = manger.open("text.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
values.add(line.split(","));
//System.out.print(value);
}
br.close();
} catch (IOException e1) {
System.out.println("not good");
}
}
Can you try this
private void readFile() {
// TODO Auto-generated method stub
AssetManager manger;
String line = null;
try {
manger = getAssets();
InputStream is = manger.open("text.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String[] value = line.split(",");
for(int i=0;i<value.length;i++)
System.out.print("*************************************************"+value[i]);
}
br.close();
} catch (IOException e1) {
System.out.println("not good");
}
}

Can't get runtime.exec working on android

I can't seem to get runtime.exec working in my android app. I've tried it with a host of shell utilities, here's the code I'm using:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
filesPrinter = (Button) findViewById(R.id.print_files);
filesPrinter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
Process proc = Runtime.getRuntime().exec("ls");
out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.println("Done reading");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
I don't get an error, but also do not get anything in logcat.
The problem ended up being a bug with the eclipse logcat. Using adb logcat, I could see everything that was supposed to be outputted. For some reason, logcat on eclipse showed that it was connected but was not receiving any application level output from the emulator.
Maybe your current working directory (which is what ls scans without any parameters) simply contains no files. Try providing a path as a command argument.
Think you're missing a proc.waitFor()....
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
filesPrinter = (Button) findViewById(R.id.print_files);
filesPrinter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
Process proc = Runtime.getRuntime().exec("ls");
out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.println("Done reading");
//
proc.waitFor(); // THIS!!!
//
} catch (IOException e) {
e.printStackTrace();
}
}
});
}

Categories