I have CSV file it contains users time, distance, latitude and longitude other details, i click start button read row by row every 5 seconds and if click pause button it need to pause reading and if i click start again continue from where it paused. Now it displaying all rows.
public class CurrnetActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currnet);
initViews();
}
public void initViews() {
InputStream inputStream = getResources().openRawResource(R.raw.athlete_run);
CSVReader csvFile = new CSVReader(inputStream);
final List<String[]> Row = csvFile.read();
final Handler handlerOne = new Handler();
Runnable runnableOne = new Runnable() {
#Override
public void run() {
for (int i = 0; i < Row.size(); i++) {
Log.i("===dsd", Row.get(i)[0]);
//Log.d(Constants.TAG, String.format("row %s: %s, %s", i, rows.get(i)[0], rows.get(i)[1]));
}
handlerOne.postDelayed(this, 2000);
}
};
handlerOne.postDelayed(runnableOne, 2000);
}
}
CSV READER class
public class CSVReader {
InputStream inputStream;
public CSVReader(InputStream inputStream){
this.inputStream = inputStream;
}
public List<String[]> read(){
List<String[]> resultList = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
I got the exact same result when I tested your example with the following csv file:
Username; Identifier;First name;Last name
booker12;9012;Rachel;Booker
grey07;2070;Laura;Grey
johnson81;4081;Craig;Johnson
jenkins46;9346;Mary;Jenkins
smith79;5079;Jamie;Smith
However, when I changed String[] row = csvLine.split(","); to String[] row = csvLine.split(";"); in CSVReader class it worked.
Seems like your csv file values are not separated with a comma. You were looking for a comma to separate each value, so the whole line is red as a single value.
The csv format is not standardized. According to wikipedia also semicolons, tabs or spaces are used as separation.
It is important to check your csv file for the seperator. Maybe you need to change line String[] row = csvLine.split(","); to different separator.
Related
I have an arraylist that gets inputs from a CSV file and is displayed by a listview. What I'm trying to do is add search functionality to that activity. I've seen a couple of other tutorials but i can't seem to get the code to work.
This is the main java class for the CSV arraylist:
public class games extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_games);
InputStream inputStream = getResources().openRawResource(R.raw."filename");
CSVFile csvFile = new CSVFile(inputStream);
List<String[]> slots = csvFile.read();
MyListAdapter adapter = new MyListAdapter(this, R.layout.list_item, R.id.text_view, filename);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List<String[]> read(){
//
List<String[]> ArrayList = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
ArrayList.add(row);
}
}
catch (IOException e) {
Log.e("Main",e.getMessage());
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
Log.e("Main",e.getMessage());
}
}
return ArrayList;
}
}
}
I found code from another stackoverflow post but i just don't know how to really apply it to my specific case or if it even applies:
ArrayList<String> storedContent = new ArrayList<String>();
ArrayList<String> contentArray = new ArrayList<String>();
String searchText = "sometest";
for(String each : storedContent){
if (each.contains(searchText)){
contentArray.add(each);
}
}
ListView displaySearchResult = (ListView)findViewById(R.id.list_id);
myListAdapter adapter = new myListAdapter(contentArray, this) ;
displaySearchResult.setAdapter(myListAdapter);
Any solution would be greatly appreciated, let me know if I left anything out that you may need to help me, I'm pretty fresh to java scene.
the following is your code... I think it is not right. You need to instantiate the arraylist
public List<String[]> read(){
List<String[]> ArrayList = new ArrayList<String[]>();
}
instead, try this...
public ArrayList<String> read(){
ArrayList<String> objName = new ArrayList<String>();
//create an String type arraylist "objName". you store all the string data from csv file into this "objName"
return objName;
}
I hope it helps...
Requirements:
When the application is executed, it should now check to see if ‘list.txt’ exists. If it does, it should initialize the To Do List with the file contents. If it does not, do not open the stream to list.txt.
And my code is:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,TextToSpeech.OnInitListener {
private ArrayList<String> noteList = new ArrayList<>();
private ArrayAdapter<String> adapter = null;
private EditText input;
private ListView listview;
String noteText; //text of the note
private TextToSpeech speaker;
private int clickedIndex; //starting from 0
private int indexEndPos;
private boolean clicked; // initialized to false
private static final String tag = "Widgets";
private final String file = "list.txt";
private OutputStreamWriter out;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.inputField);
listview = (ListView) findViewById(R.id.list);
listview.setOnItemClickListener(this);
// open stream for reading
//Read text from file
BufferedReader inputStream = null;
try {
inputStream =
new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
int i = 0;
String[] text = new String[20];
try {
while ((line = inputStream.readLine())!= null) {
text[i++] = line;
} inputStream.close();
ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(text));
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, text);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (IOException e) {
e.printStackTrace();
}
try {
out = new OutputStreamWriter(openFileOutput(file, MODE_PRIVATE));
} catch (FileNotFoundException e3) {
e3.printStackTrace();
}
}
File file = new File(<PATH_TO_DIRECTORY>, <FILE_NAME>);
if (file.exists()) {
//Open the stream and get file contents
} else {
//Don't open the stream and do whatever else
}
A few extra tidbits:
If your file is stored in external storage, the directory path should be:
new File(Environment.getExternalStorageDirectory().getAbsolutePath(), <FILE_NAME>);
^^Permissions are required to read from and write to external storage.
If your file is stored in your App's internal storage:
new File(context.getFilesDir().getAbsolutePath(), <FILE_NAME>);
^^No permissions required, Contents not visible anywhere except your app.
If you're trying to read a file from the assets folder, you can get an InputStream of the file directly from AssetManager, which can be accessed with getAssets():
InputStream in = context.getAssets().open("list.txt");
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.
I'm trying to populate a simple listview using an array of strings in ArrayList. Every time I try though it force closes. I know I'm getting the correct strings in the array as I've seen with Logcat. I can't seem to figure out why it is force closing. Maybe I'm forgetting something in ArrayAdapter (it looks correct to me) or maybe I'm putting my populate method in the wrong place... Can someone help me with this?
public class SchedLayout extends Activity {
public ArrayList<String> titleArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sched_layout_layout);
new doParse().execute();
}
private class doParse extends AsyncTask<Void, Void, Void> {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/directory/");
File file = new File(dir, "file.html");
#Override
protected Void doInBackground(Void... params) {
try {
FileInputStream input = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(
input, "UTF-8"));
String line;
titleArray = new ArrayList<String>();
while ((line = br.readLine()) != null) {
String html = line;
Document doc = Jsoup.parse(html);
Elements rels = doc.select("a[rel]");
for (Element title : rels) {
String exclude = "Follow";
if (title.attr("title").contains(exclude)) {
continue;
}
titleArray.add(title.attr("title"));
// Log.v("", title.attr("title")); <--works
}
}
br.close();
input.close();
populate(titleArray); <--does not work
} catch (FileNotFoundException e) {
//Never happens
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void populate(ArrayList<String> array) {
ListView showList = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> shows = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1, array);
showList.setAdapter(shows);
}
}
}
Move your populate call to onPostExecute. You cannot modify the ListView in doInBackground or anything UI related.
#Override
protected void onPostExecute(Void v) {
populate(titleArray);
}
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");
}
}