I'm trying to read in a text file of words into an array or String where I would be able to access each word. Separating the words if it comes in one long String is no issue but I have having some real problems reading the file. I am using Android Studio and the file is under the assets folder (app/app/src/main/assets/wordsEasy.txt)
So far I have the following code:
public String[] getWords(String difficulty){
ArrayList<String> wordList = new ArrayList<String>();
String[] words = new String[wordList.size()];
String wordList = getQuestions() //Location of error
//Haven't finished here but would consist of transferring the words in the String into an array
return words;
}
private static String getQuestions(Context ctx,String file_name) {
AssetManager assetManager = ctx.getAssets();
ByteArrayOutputStream outputStream = null;
InputStream inputStream = null;
try {
inputStream = assetManager.open(file_name);
outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
} catch (IOException e) {
}
return outputStream.toString();
}
I don't know how to get the context in this situation and would appreciate any help. Also if you know an alternative way to read the file to a String or array please share it.
Check this, working for me
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List<String> wordList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wordList = getWordsFromFile("text_file.txt", MainActivity.this);
Toast.makeText(this,"Word Size:"+wordList.size(),Toast.LENGTH_SHORT).show();
TextView textView = (TextView) findViewById(R.id.tv_words);
for(String word : wordList){
textView.append("\n"+word);
}
}
public List<String> getWordsFromFile(String textFileName, Context context){
List<String> wordList = new ArrayList<>();
String textStr = "";
AssetManager am = context.getAssets();
try {
InputStream is = am.open(textFileName);
textStr = getStringFromInputStream(is);
} catch (IOException e) {
e.printStackTrace();
}
if(textStr !=null){
String[] words = textStr.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll("[^\\w]", "");
wordList.add(words[i]);
}
}
return wordList;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
String line;
try {
bufferedReader = new BufferedReader(new InputStreamReader(is));
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuilder.toString();
}
}
Make sure your assets folder is in your "app" project and not the outer project
Then, you can get the file by simply using following code:
InputStream myFile = mContext.getAssets().open("myfile.txt");
Related
Im creating a weight tracking app where the user inputs their weight clicks a save button and then the weight is saved. There is also a load button that loads all the previous inputs. The problem I'am having is that once load is clicked it does load up the weights on the screen but it does it all in one line other than a separate line for each.
I have checked the text file and all the weights are stored in a line each so there's no problem in the function that stores the inputs.
Here is the code for the `weight tracker
package com.example.workouttracker;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class WeightTracking extends AppCompatActivity {
private static final String FILE_NAME = "WeightTracking.txt";
EditText mEditText;
EditText mEditText2;
private Button button_back_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight_tracking);
mEditText = findViewById(R.id.weight);
mEditText2 = findViewById(R.id.weight2);
button_back_home=(Button) findViewById(R.id.button_back_home);
button_back_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homePage();
}
private void homePage(){
startActivity(new Intent(getApplicationContext(),MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
});
}
public void save(View v) {
String text = mEditText.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILE_NAME, MODE_APPEND);
fos.write((text + "kg's\n").getBytes());
mEditText.getText().clear();
Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FILE_NAME,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void load(View v) {
FileInputStream fis = null;
try {
fis = openFileInput(FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text);
sb.append('\n');
}
mEditText2.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Someone know's how to get it to load each weight line by line?
Thanks
`
can you please check your xml file, if you have added property android:inputType="textMultiLine" on the edittext
Try changing your code like this:
String sb = "";
String text;
while ((text = br.readLine()) != null) {
sb = sb + text + "\n";
}
//[(START)File:ThirdActivity.java] -->
package com.example.caleb.splash_screen;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.OutputStream;
public class ThirdActivity extends AppCompatActivity {
//public String text = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt";
public TextView text;
private void writeStream(OutputStream out){
String output = "Hello world";
// out.write(output.getBytes());
//out.flush();
}
/*private String readStream(InputStream is) {
try {`enter code here`
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}*/
//[(START) readStream -->
private String readStream(InputStream in) throws IOException {
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
//temporary
try {
StringBuilder sb = new StringBuilder();
String inputLine;
while ((inputLine = bin.readLine()) != null) {
sb.append(inputLine);
}
return sb.toString();
} finally {
}
}
//[(END) readStream -->
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third2);
text = (TextView)findViewById(R.id.textView);
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
}
}
//[(END)File:ThirdActivity] -->
//[(START)File:JSONTask] -->
package com.example.caleb.splash_screen;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Caleb on 12/17/2017.
*/
public class JSONTask extends AsyncTask<String,String,String> {
//final TextView txt = (TextView)findViewById(R.id.textView);
private Context context;
public JSONTask(Activity ThirdActivity) {
context = ThirdActivity;
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection urlConnection = null;
//{(START)] Working Connection:ALERT! Error within code will cause crash -->
try {
URL url = new URL(params[0]);
Log.w("testing", "test");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(false);
urlConnection.connect();
//urlConnection.setChunkedStreamingMode(0);
//OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//writeStream(out);
/*int a = urlConnection.getResponseCode();
String b = String.valueOf(a);
Log.e(b, "yesssssssssssssssss");*/
InputStream in = urlConnection.getInputStream();
//InputStream in = new BufferedInputStream(urlConnection.getInputStream());
reader = new BufferedReader(new InputStreamReader(in));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
/*String data = readStream(in);
/*final TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("hello");
*/
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//{(END)] Working Connection -->
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView text = (TextView) ((AppCompatActivity) context).findViewById(R.id.textView);
text.setText(result);
}
}
//[(END)File:JSONTask] -->
/Desired Effect/
Blockquote
I would like to pull data from the json file that the url points to and change the TextView within the UI called textView. I don't understand how to access the findviewbyid within the AsyncTask. I've looked all throughout the internet and couldn't find anything :( Any suggestions are greatly appreciated!!
try weak reference to get textview in asynctask
//call async task
new JSONTask(yourTextView).execute();
//in your async task
private final WeakReference<TextView> textViewReference;
public JSONTask (TextView textView){
textViewReference = new WeakReference<TextView>( textView);
}
#Override
protected void onPostExecute() {
TextView textView = textViewReference.get();
//set values to text view
}
I'm using OkHttp to do the same task in my apps
HTTP/2 support allows all requests to the same host to share a socket.
Connection pooling reduces request latency (if HTTP/2 isn’t available).
Transparent GZIP shrinks download sizes.
Response caching avoids the network completely for repeat requests.
Add this dependency
implementation 'com.squareup.okhttp3:okhttp:3.9.1'
Then create/code a new Class named OkHttpHandler
class OkHttpHandler extends AsyncTask<String, String, String> {
OkHttpClient client = new OkHttpClient();
private volatile String data;
public String getResult() {
return data;
}
#Override
protected String doInBackground(String... params) {
try {
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
data = s;
}
}
}
and use it like this way
String str = new OkHttpHandler().execute("http://www.<TEST>.com/json").get();
I also suggest to check whether Wi-fi-Connected/Bluetooth-Connected or PhoneData-Enabled is false if true/else, Proceed to your code
I am trying to have Android Studio read a text file from a URL into a string array. Then, use the URLS within Picasso to display a simple gallery. My attempts at achieving this are below.
My GrabData.java script:
public class GrabData
{
static public String[] LIST = {};
public static void main(String[] args)
{
ReadFile rf = new ReadFile();
// The text file.
String filename = "http://www.example.com/my/website/directory/thefile.txt";
try
{
String[] LIST = rf.readLines(filename);
for (String line : LIST)
{
System.out.println(LIST);
}
}
catch(IOException e)
{
System.out.println("ReadFile : Unable to create "+filename+": "+e.getMessage());
}
}
}
My ReadFile.java script:
public class ReadFile extends Activity
{
public String[] readLines(String filename) throws IOException
{
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
However, when I try to use a URL in the filename string, it doesn't display any images on the gallery, which is able to load from arrays. I am guessing this method can't read URLS. If anyone has any help on how to get this, it is much appreciated.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyAsyncFileReader().execute("http://www.example.com/my/website/directory/thefile.txt");
}
public static class MyAsyncFileReader extends AsyncTask<String, Void,String []>
{
#Override
protected String [] doInBackground(String... params){
String url= params[0];
List<String> lines = new ArrayList<String>();
try{
URL u= new URL(url);
HttpURLConnection conn= (HttpURLConnection) u.openConnection();
InputStream is= conn.getInputStream();
BufferedReader br =new BufferedReader(new InputStreamReader(is));
String line=null;
while((line=br.readLine())!=null){
lines.add(line);
}
br.close();
}catch(Exception e){
}
return lines.toArray(new String[lines.size()]);
}
#Override
protected void onPostExecute(String[] strings) {
//You will get your string array result here .
// do whatever operations you want to do
for(int i=0;i<strings.length;i++){
Log.e("LOG", strings[i]);
}
}
}
}
This is how it looks in My Activity . Use similarly in you activity.
My edits: Made the MyAsyncFileReader class public and static to be read through other activities.
The
mytextview.setText(xyzList[0][0]);
line fails (RED).
I am mixing up everything, I am afraid.
I know it is something simple.
I am trying to write the first instance of the array I filled with the dan_akdag.pgn textfile (with a " " split) on the related TextView.
Can anyone help me?
I'm still a novice.
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager manager;
String line = null;
List<String[]> xyzList = new ArrayList<String[]>();
String[][] xyz;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
manager = getAssets();
is = manager.open("dan_akdag.pgn");
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
xyzList.add(line.split(" "));
}
xyz = (String[][]) xyzList.toArray();
TextView mytextview = (TextView) findViewById(R.id.showarray);
** mytextview.setText(xyzList[0][0]); **
} catch (IOException e1) {
Toast.makeText(getBaseContext(), "Problem!", Toast.LENGTH_LONG).show();
} finally {
try {
//if(reader != null)
// reader.close();
if (br != null)
br.close();
if (isr != null)
isr.close();
if (is != null)
is.close();
} catch (IOException ex) {
// dosomething
ex.printStackTrace();
}
}
}
}
Change
mytextview.setText(xyzList[0][0]);
to
mytextview.setText(xyz[0][0]);
since xyzList is not an array while xyz is.
Also change
xyz = (String[][]) xyzList.toArray();
to
xyz = xyzList.toArray(new String[xyzList.size()][]);
Casting an Object[] to a String[][] will not work. It will throw a ClassCastException.
Change
mytextview.setText(xyzList[0][0]);
to
mytextview.setText(xyz[0][0]);
xyzList refers to your ArrayList, not to an array.
how can I read a text file which I got from uri (size is about 2Mb) in a special way without turning the screen black for a minute and then displaying the whole string ? My problem is that I set the textView text to whole string and that's why it lags. Is there any way to make it read it in small parts and then display them in small parts ? In a way that ES file explorer does.
Here is my actual, not very efficient and lagging code:
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
TextView txt = (TextView)findViewById(R.id.textView);
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null) {
try {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
txt.setText(buf.toString());
}
My first idea would be as follows:
txt.setText("");
if (inputStream!=null) {
try {
while ((str = reader.readLine()) != null) {
txt.append(str + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Consider using a loader.
Loaders are running on a different thread and therefore do not block the UIThread which creates your interface. Because you are loading a lot of data into memory, the system has to wait until it can display your interface. This causes the black screen. The problem can even force the system to shut down your app because it is doing to much work on it's main thread.
http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html
There are different type of loaders.
You may need an AsyncTaskLoader or if you are querying a content provider a CursorLoader.
Update1:
package de.xyaren.fileloader;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends ActionBarActivity implements LoaderManager.LoaderCallbacks<String> {
private TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.textView);
// File on my sd card
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
Uri myUri = Uri.fromFile(file);
Log.i("URI", myUri.toString());
//Create arguments
Bundle args = new Bundle();
args.putParcelable("URI", myUri);
getLoaderManager().initLoader(0, args, this);
}
#Override
public Loader onCreateLoader(int id, Bundle args) {
final Uri uri = args.getParcelable("URI");
Loader loader = new AsyncTaskLoader<String>(this) {
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public String loadInBackground() {
InputStream inputStream = null;
StringBuffer buf = new StringBuffer();
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String str = "";
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return buf.toString();
}
};
return loader;
}
#Override
public void onLoadFinished(Loader<String> loader, String data) {
//Interact with UI Here
if(data != null)
txt.setText(data);
}
#Override
public void onLoaderReset(Loader loader) {
}
}