I cannot for the life of me how to figure out the most simple task of retrieving a text file from a url and reading its contents. All the code I find is 5-12 years old and doesn't work. Since android api 30+ any network request on main thread give a android.os.NetworkOnMainThreadException.
I'm stuck using kotlin for this portion.
I cant use DownloadManager (unless there is a way to store the file temporarily and retrieve contents) as the file doesnt need to be downloaded to the local storage only read.
The closest ive seen is from:
Android - How can I read a text file from a url?
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.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();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
But this code doesn't work.
So after 3 days of wanting to jump off a cliff. I found the answer. Of course it was a few minutes after asking the question here (first question ever so be kind.). The only Issue is you need a SSL cert for HTTPS on the server retrieving the file. My server is http but i can get a cert in there and fix that. to Test i threw up a github repository and linked to the raw text file. Here is my solution if this saves you 3 days pour one out for me.
Thread {
try {
val url = URL("https://raw.githubusercontent.com/USERNAME/NeedHTTPSdontWanaSSL/main/info.txt")
val uc: HttpsURLConnection = url.openConnection() as HttpsURLConnection
val br = BufferedReader(InputStreamReader(uc.getInputStream()))
var line: String?
val lin2 = StringBuilder()
while (br.readLine().also { line = it } != null) {
lin2.append(line)
}
Log.d("The Text", "$lin2")
} catch (e: IOException) {
Log.d("texts", "onClick: " + e.getLocalizedMessage())
e.printStackTrace()
}
}.start()
Credit:
answered Aug 12, 2018 at 9:29
Aishik kirtaniya
Android - How can I read a text file from a url?
Related
How can i read a large text file into my Application?
This is my code but it does not work. My code must read a file called list.txt. The code worked only with a file with only 10.000 lines.
can someone helps me?
Thanks!
My code:(Worked with small files, but not with large files)
private void largefile(){
String strLine2="";
wwwdf2 = new StringBuffer();
InputStream fis2 = this.getResources().openRawResource(R.raw.list);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
if(fis2 != null) {
try {
LineNumberReader lnr = new LineNumberReader(br2);
String linenumber = String.valueOf(lnr);
while ((strLine2 = br2.readLine()) != null) {
wwwdf2.append(strLine2 + "\n");
}
// Toast.makeText(getApplicationContext(), linenumber, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since you are processing a large file, you should process the data in chunks . Here your file reading is fine but then you keep adding all rows in string buffer and finally passing to Toast.makeText(). It creates a big foot-print in memory. Instead you can read 100-100 lines and call Toast.makeText() to process in chunks. One more thing, use string builder instead of string buffer go avoid unwanted overhead of synchronization. You initializing wwwdf2 variable inside the method but looks it is a instance variable which I think is not required. Declare it inside method to make it's scope shorter.
I'm currently working on an android project which allows user to write text using different colors and store them for later use(i.e., editing or reading).
Is their any way to store a file in android with multi color text ??
NOTE: I googled out for the solution but can't find anything useful.
I'm guessing the user has to perform some action to switch color?
If so - you can use that trigger to store the text position/length when switching and save a list of text position - color.
A commenter suggested HTML, and that may be a good choice. You are welcome to try Html.fromHtml() to populate your EditText with the contents of a simple HTML-formatted file, and you are welcome to try Html.toHtml() to generate HTML from the contents of your EditText. However, historically, those methods were not written to do a good job of implementing a "round trip", meaning that the contents of the EditText may wind up changing from its starting point to what it contains after doing Html.toHtml() (to generate and save the HTML) and Html.fromHtml() (to populate the EditText with the previously-saved HTML). If they do not work, you can either fork that Html class and try to modify it as needed, or write your own code to take a Spanned object and convert it to/from HTML, by examining the spans and generating HTML tags from them.
PROBLEM SOLVED:
Code for storing a multi color text from EditText to a txt file:
protected void onDestroy() {
super.onDestroy();
boolean writing_allowed= ExternalStorageWriting.isWritingPossible();
if(writing_allowed)
{
String store= Html.toHtml(et.getEditableText());
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(store.getBytes());
fos.close();
} catch (Exception e) {
Toast.makeText(Notes.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
}
Code for reading that txt file and displaying it in EditText :
private void setNotes()
{
String myData="";
try {
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Spanned htmlText = Html.fromHtml(myData);
et.setText(htmlText);
}
I am trying to get the Logcat (at least last few lines) on a button click but nothing comes up -
view.findViewById(R.id.logdone).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Make file name.
String fullName = "userlogs";
// Extract to file.
File file = new File(fullName);
InputStreamReader reader = null;
FileWriter writer = null;
try
{
// get input stream
String cmd = "logcat -d -v time";
Process process = Runtime.getRuntime().exec(cmd);
reader = new InputStreamReader (process.getInputStream());
// write output stream
writer = new FileWriter (file);
char[] buffer = new char[10000];
do
{
int n = reader.read (buffer, 0, buffer.length);
if (n == -1)
break;
writer.write (buffer, 0, n);
} while (true);
reader.close();
writer.close();
}
catch (IOException e)
{
if (writer != null)
try {
writer.close();
} catch (IOException e1) {
}
if (reader != null)
try {
reader.close();
} catch (IOException e1) {
}
e.printStackTrace();
return;
}
}
}
NOTE:
I do have permissions -
<uses-permission android:name="android.permission.READ_LOGS" />
UPDATE:
My most of the content is in Log.d() then Log.v() then Log.e() then Log.i(). But how to get the last event lines on a button click. My purpose is to get those lines and send them via email to the developer.
I am using the popular third party API known as ACRA to send email which is working fine.
I can use StringBuilder to put all my device logs into it and then to send via email.
But I am unable to get.
Any elegant way that works well effectively ?
Given the comment I made about the READ_LOGS permission no longer being granted to non-system apps, I would instead recommend using a MemoryHandler with a standard Java Logger. On a button click, you can push the messages to a target StreamHandler (which you can use to just dump them into the output buffer of your choice).
Is it possible to get the last few lines of a logcat on a button click?
There has never been a documented and supported way for apps to get anything from LogCat. And, as Turix notes, things were locked down further in Android 4.2.
Any elegant way that works well effectively ?
Log the data yourself to a file that you control, rather than (or in addition to) logging the data to LogCat.
This question already has answers here:
how to faster read text file to ArrayList on android
(2 answers)
Closed 9 years ago.
Here is the code of function:
public void loadTextFile(String textFileName, ArrayList<String> dictionary)
{
AssetManager assetManager = getAssets(); //files manager
//reader = public bufferedReader
//word = public String
//dictionary = public ArrayList<String>
//load file to buffer
try {
reader = new BufferedReader(new InputStreamReader(assetManager.open(textFileName)));
} catch (IOException e1) {
e1.printStackTrace();
}
word = " ";
//loop, save words from buffer to dictionary
while(word != null)
{
try {
word = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
word = null;
}
if (word != null) {
dictionary.add(word);
}
}//end while
//buffer close
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} //end function
If I try load small file <1MB, It works fine and rather fast.
If the files(partialy) are more than 1MB, but less than about 3MB, it works slow (4-6min).
If the files are bigger, it's not working, and I have information in emulator:
"The application app (process processing.test.app) has stopped unexpectedly. Please try again". I don't know what is wrong.
I try: pre-allocated ArrayList, load file to few ArrayList's, but still not working.
I will be grateful for any suggestions.
First off, word can become null somewhere along the file and the loop will exit (since you explicitly set word to null on an exception). Do you get a stack trace?
Try to move the code to a background process using AsyncTask AsyncTask
Execute on real device if you have one
I am prepared code for download images from server and store in sdcard.For that i have prepared code,
URL url;
try {
url = new URL("http://myserver_path/applikaza/appstore/apks/ScrResoluton/scrresolution.jpg");
input = url.openStream();
String storagePath = Environment.getExternalStorageDirectory().toString();
String basepath = storagePath + "/Guayama/" + folderName;
output = new FileOutputStream(basepath + "/home.png");
byte[] buffer = new byte[5000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} catch (MalformedURLException e) { // TODO Auto-generated catch block
e.printStackTrace();
} finally {
output.close();
input.close();
}
but got NullPointerException at output.close().I think done mistake some where .please help me.
The reason you get a NullPointerException at output.close() is because your URL is incorrectly formed. For starters, it doesn't contain a valid protocol. This will cause MalformedURLException to be thrown on the line
url = new URL("E:/Suresh/images/home.png");
and you'll then go straight to the catch block, followed by the finally block which calls output.close(), but output is null since the line
output = new FileOutputStream(basepath + "/home.png");
was never executed.
You need to correct your URL (see the description here) and you need to correct your exception handling, as in the case of MalformedURLException, this will only ever be thrown where you set the value of url, and so you will never have a non-null value for output or input when your "finally" block is executed.
Your URL should probably be of the form "http://something/Suresh/images/home.png" or maybe "file://something/Suresh/images/home.png". If the home.png file is located on another machine to the Android device, try and access it via a web browser and use the URL shown by the web browser complete with "http://".