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.
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";
}
I am asking here as all other solutions have not worked. I want to read a text file from the web and have this string put into a textview. I am just testing at the moment and the only thing in the text file is the value "223". My app is crashing on start can anyone please help?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.StringBuilderPrinter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private StringBuilder text = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader reader = null;
try {
URL url = new URL("http://something.uk/pmt/status.txt");
reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while ((str = reader.readLine()) != null) {
text.append(str);
text.append('\n');
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error reading file.", Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (MalformedURLException e) {
}
catch (IOException e) {
}
}
TextView output = (TextView) findViewById(R.id.textView);
output.setText((CharSequence) text);
}
}
}
STACKTRACE:
https://pastebin.com/YSCB9RBg
Probably because you are using StringBuilder which is not a CharSequence. Use output.setText(text.toString()); instead of output.setText((CharSequence) text);
TextView.setText() expects a CharSequence as an argument. String is a CharSequence, but StringBuilder is not. To get a String you gave to call StringBuilder.toString()
You should look at the crash though. And post it next time you ask a question on stackoverflow.
The crash log you provided clearly states the reason for crash: android.os.NetworkOnMainThreadException. It means that you are trying to do a network operation on the main thread and the Android OS does not let you. It is a rule since Honeycomb. The solution is to use AsyncTask, for example. Here is an article about network ops and AsyncTask.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.StringBuilderPrinter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private StringBuilder text = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader reader = null;
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://something.uk/pmt/status.txt");
reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while ((str = reader.readLine()) != null) {
text.append(str);
text.append('\n');
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error reading file.", Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (MalformedURLException e) {
}
catch (IOException e) {
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
TextView output = (TextView) findViewById(R.id.textView);
output.setText(text.toString());
}
}.execute(null,null,null);
}
}
}
I am trying to populate spinner from darabase but the application crashes, "Unfortunately, "Application" has stopped." and in the logcat I have got this error "
at com.exemple.user.modele.Categorie.onCreate(Categorie.java:43)"
when I remove all the try catch code the activity works, but I copied this code from another activity in the same application to populate a listView and it worked, so please if anyone could help me, thank you !
package com.exemple.user.modele;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
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;
import java.util.ArrayList;
public class Categorie extends AppCompatActivity {
Spinner spinner1;
String result = null;
String line = null;
InputStream is = null;
String cat_url = "http://10.0.2.2/webapp/categories_spinner.php";
ArrayList<String> list1=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorie);
spinner1 = (Spinner) findViewById(R.id.sSelect);
try {
URL url=new URL(cat_url);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
if(br != null) {
while ((line=br.readLine()) != null) {
sb.append(line+"\n");
}
}
result = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(result);
//CREATE JO OBJ TO HOLD A SINGLE ITEM
JSONObject jo = null;
list1.clear();
//LOOP THRU ARRAY
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
//RETRIOEVE NAME
String name = jo.getString("name");
//ADD IT TO OUR ARRAYLIST
list1.add(name);
}
spinner_fn();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void spinner_fn() {
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(Categorie.this,
android.R.layout.simple_spinner_item, list1);
spinner1.setAdapter(dataAdapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner1.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
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");
I'm currently developing an android application with makes some user data while running which is saved in two ArrayList. Once the application closes, I need to save the datas on to the internal memory but in my logcat I'm always getting the error IOException file not found.
I'm confused about why it always happen. The following is my code for my activity. Please help me!
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static ArrayList<String> myArrayList=new ArrayList<String>();
public static ArrayList<String> myArrayListwr=new ArrayList<String>();
static int close=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
close=1;
System.out.println("Oncreate called");
try{
final File dir = new File(getApplicationContext().getFilesDir() + "/file");
if(!(dir.exists()))
{
dir.mkdirs(); //create folders where write files
}
final File file = new File(dir+ "/lines.txt");
if(!(file.exists())) {
file.createNewFile();
}
BufferedReader br = new BufferedReader(new FileReader(file));
if (br.readLine() == null) {
close=0;
}
br.close();
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayList.size()==0 && close!=0)
{
System.out.println("retriving data from file lines");
FileInputStream input =openFileInput("lines.txt"); // Open input stream
DataInputStream din = new DataInputStream(input);
int sz = din.readInt(); // Read line count
for (int i=0;i<sz;i++) { // Read lines
String line = din.readUTF();
myArrayList.add(line);
}
din.close();
}
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayListwr.size()==0 && close!=0)
{
System.out.println("retriving data from file lineswr");
final File dirwr = new File(getApplicationContext().getFilesDir() + "/file");
if(!dirwr.exists())
dirwr.mkdirs(); //create folders where write files
final File filewr = new File(dirwr+ "/lineswr.txt");
if(!filewr.exists()) {
filewr.createNewFile();
}
FileInputStream inputwr = openFileInput("lineswr.txt"); // Open input stream
DataInputStream dinwr = new DataInputStream(inputwr);
int szwr = dinwr.readInt(); // Read line count
for (int iwr=0;iwr<szwr;iwr++) { // Read lines
String linewr = dinwr.readUTF();
myArrayListwr.add(linewr);
}
dinwr.close();
}
}
catch (IOException exc) { exc.printStackTrace(); }
Button phy = (Button) findViewById(R.id.button3);
Button mat = (Button) findViewById(R.id.button1);
Button bio = (Button) findViewById(R.id.button2);
Button chem = (Button) findViewById(R.id.button4);
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
if(myArrayList.size()!=0)
{
System.out.println("inside on back pressed saving data to lines");
//Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
String fileName = getApplicationContext().getFilesDir()+"/file/"+ "lines.txt";
FileOutputStream output = openFileOutput("lines.txt",MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(myArrayList.size()); // Save line count
for(String line : myArrayList) // Save lines
dout.writeUTF(line);
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
}
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayListwr.size()!=0)
{
System.out.println("inside on back pressed saving data to lineswr");
//Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
String fileNamewr = getApplicationContext().getFilesDir()+"/file/"+ "lineswr.txt";
FileOutputStream outputwr = openFileOutput("lineswr.txt",MODE_PRIVATE);
DataOutputStream doutwr = new DataOutputStream(outputwr);
doutwr.writeInt(myArrayListwr.size()); // Save line count
for(String linewr : myArrayListwr) // Save lines
doutwr.writeUTF(linewr);
doutwr.flush(); // Flush stream ...
doutwr.close(); // ... and close.
}
}
catch (IOException exc) { exc.printStackTrace(); }
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
}