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...
Related
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.
I tried many ways but I got blank layout.I changed lots of lines but the result is always the same. Should I rewrite the code and try something different. I followed some videos on youtube but nobody has the proper solution.I don't think it is caused because array got null result. Anybody knows what might be wrong:
AirportTransportActivity
public class AirportTransportActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data = new String[0];
JSONObject jsonObject = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
//Adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}
In your original post you have set the adapter before you have added the data. But I also suspect that you are having issues with:
String[] data = new String[0];
So I changed it to
ArrayList<String> data = new ArrayList<>();
I also changed your AsyncTask a bit. Now you can do most of your parsing in the background thread. When the doInBackground is successful just notify the adapter of the changes in onPostExecute.
You will also need to check if the ArrayList<String> fits to your Adapter class. If not just change it as needed.
Do this instead:
public class AirportTransportActivity extends AppCompatActivity {
private static final String TAG = AirportTransportActivity.class.getSimpleName();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return toString();
}
#Override
protected void onPostExecute(String result) {
if(result.isEmpty()) return;
try{
ArrayList<String> data = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
JSONArray jsonArray = new JSONArray(result);
int len = jsonArray.length();
Log.e(TAG, "Lenth of json array = " + len)
for (int i = 0; i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// I add the optString variation just in case the data is corrupt
String s = jsonObject.optString("airporttransportname", "?");
data.add(s);
}
listView.setAdapter(adapter);
}
catch(JSONException e){
e.printStackTrace();
}
}
}
Disclaimer I did this in a text editor and wasn't able to count on "auto-correct" for some of the syntax or method names--so you will need to check it.
There are some other things I would change in your code, but I wanted to leave it as close to the original as I could.
You're setting the data array and calling notifyDataSetChanged() before your async task has a chance to finish. You need to set your adapter and notifyDataSetChanged() from within the onPostExecute() method in your async task.
Just to be clear, when you call asyncTask.execute(), it starts the async task and then immediately keeps executing the rest of the code. So when you set your data array in your list view adapter, the asyncTask hasn't even finished and your array items are still null.
No need to change anything just add adapter.notifyDataSetChanged(); after storing all values into your array
Remove this line adapter.notifyDataSetChanged();in Oncreate ,You
have to use notifyDataSetChanged() when your arraylist values is getting
changed.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
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 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");
}
}