I need help with csv, I only started learning how to use it yesterday, and I can't find a solution for that problem.
I have a csv file with some array: "name, address, id", using Opencsv.
Now I want to be able to add corresponded strings in the row below it.
For example, if the user press some button, the name "david" will be added the the csv file, and it will look like:
"name,address,id"
"david"
and when the user will press other button, the adress "3 street" will be added, so it will look like:
"name,address,id"
"david, 3 street"
and so on, so in the end there will the a list of names and their address and id. I just can't figured out how to do it and I cant anything similar. Maybe there is another way to do it?
Let me try to understand what you mean,
In scenario 1, you should have only name added,
In scenario 2, you should have name,address added,if that is what I understand?
This is simple and quite achievable.
Firstly I am assuming you have already created the row part in your csv and saved to your sd-card
In the next part it should be using an arraylist to write to your csv, check out the code below
String csv = "C:\\work\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<string[]> data = new ArrayList<string[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Take this arraylist when its your scenario 2.
Also create a separate arraylist which will contain single column data and populate in the same way for scenario 1.
You need to do proper null-checks in scenario 1, else it will throw NullPointer Exception.
Most final approach create two separate methods
Method1- for writing only single column data to your csv.(where you should properly handle the nullchecks)
Method2-the sample code provided
For more reference
http://www.codeproject.com/Questions/491823/Read-fWriteplusCSVplusinplusplusAndroid
Hope this works.
Related
I'm making an Android application and want to create a "Favorites" list for some objects in the app. I wanna make the list accessible and editable in all my activities and I can't really figure out the best way to do this.
Shared preferences? Writing a small txt file to the device? What's the fastest way to do this?
Thanks in advance!
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
Then when you want to save, convert your array into String:
ArrayList<Type> yourData = new ArrayList<Type>();
String dataStr = new Gson().toJson(yourData);
//put this dataStr in your shared preferences as String
To retrieve and convert back to an object is also simple:
String str = "";
//you need to retrieve this string from shared preferences.
Type type = new TypeToken<ArrayList<Type>>() { }.getType();
ArrayList<Type> restoreData = new Gson().fromJson(str, type);
If you want to create a Favorites list, use a SQLite Database.
There's really only four ways to store data.
Shared Preferences
Databases
Local files
Remote Server - Slowest since it depends on network connection, so let's skip this.
Between the remaining 3, SharedPreferences is a great option when used to store a single value. However, it's not a good option for storing a Favorites list, mainly because you can only store a single String.
You can still store it by combining all items in your list into one string, then splitting it each time. However, as your Favorites list gets larger, this single long String will too. Splitting and combining all the time isn't efficient.
SharedPreferences is still a decent option if you only have to store the Favorite's list, but since you want to edit it too, it becomes a less attractive solution.
Local Files and Databases are the better options, however local files require you to read in the file each time you want to use it. This process of reading and writing to a file isn't as efficient as using a Database, especially if you want to edit. For example, let's say you want to remove an item from the middle of your Favorite's list. This would require you to read in the file, edit it, then write the change into the file again. Not too pleasant when compared with the ease of the final solution.
Databases are the best option for this, mainly because it's designed to manage data. You can create a single Favorite's table and add each item as it's own individual row. Fetching the entire table becomes quick and easy. Fetching a single item becomes quick and easy. Adding a new item or removing a new item is also quick and easy.
I want to group all contact in my app by using the first character of contact name. The result looks like deafault Contact Book in Android Phone.
I don't know the name of API which can solve my problem.
Could you give me the name of it?
Picture figures: image
You can use the an object of TreeSet class to sort strings as shown below:
TreeSet mySet = new TreeSet();
mySet.add("java");
mySet.add("C");
mySet.add("Pascal");
mySet.add("ruby");
Log.d("TAG",mySet);//output here will be C,java,Pascal,ruby,
//Now our task is to fetch strings from the sorted strings in `mySet` object
String[] names= mySet.toArray(new String[mySet.size()]);
//Now you will have sorted names in the names[] array
So, as commented if you are able to fetch string/names from your contacts, then you can use the above concept by creating an object of type TreeSet and adding all your contacts to this object and converting it to an array of strings as shown above.
I'm sure this one definitely helps.
I am creating an app that has several Buttons on the first screen. Every Button will parse a separate XML file and is supposed to create a nested list from that information.
All the XML files have this structure:
<blalist>
<house>
<name>Blaname1</name>
<eaddress>195 bla steet</eaddress>
<caddress>195 bla strasse</caddress>
<telephone>123456</telephone>
</house>
<house>
<name>Blaname2</name>
<eaddress>15 bla steet</eaddress>
<caddress>15 bla strasse</caddress>
<telephone>12345685</telephone>
</house>
</blalist>
After clicking the first button i would like to generate a ListView consisting out of only the names from tag "name". So the list should only show Blaname1,Blaname2...
After clicking on one of the names all the other tags should be displayed as content;
tags "eaddress","caddress","telephone" and three extra buttons.
Basically a 3 screens scenario. First page with the main buttons. Second page shows a list generated only with the names. Third screen shows the details of the specific name clicked.
How do i go about that? I found loads of info for parsing xml to ListView and some info about ExpandableListView but i couldnt really wrap my head around of how to go about this one. Please help!
All you need to do is parse your XML and structure the data in the format that is supported by the SimpleExpandableListAdapter class.
1) For groups
List<HashMap<String, String>> lstGroups
2) For sub items of groups
List<ArrayList<HashMap<String, String>>> lstGroupItems
and then you can use SimpleExpandableListAdapter
SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter(
getApplicationContext(), lstGroups,
R.layout.group_row, // Group item layout XML.
new String[] { "Group Item" }, // the key that will identify group in `lstGroups`.
new int[] { R.id.row_name }, // ID of each group item.-Data
lstGroupItems, // childData describes second-level
R.layout.child_row, // Layout for sub-level entries(second level).
new String[] { "Sub Item" }, // Keys that will identify child items in `lstGroupItems`
new int[] { R.id.grp_child }
);
setListAdapter(expListAdapter);
You can refer this example
Expandable ListView in ANDROID using SimpleExpandableListAdapter, a simple example.
Added :
I think you should use SQLiteDatabase if you are having large amount of data or else you can structure your data in the following format
Map<String, Map<String, String>> mapHouses;
Here the key will be the house name and its value will be again the Map which will hold the house properties and the corresponding value.
You will be requiring access to mapHouses accross diffrent activity so you can have the same in your application context i.e the Application class and pass the house name to the activity that neds to display the house details. But you will end up holding large data into the memory and which can be lost if your application is killed by Android.
Based on your comment in response to Vishal your question is actually asking how to build an entire application.
You need to build
a main activity with a button that launches your list activity
a list activity that displays a list of names
a detail activity that can be used to display the details associated with a name
In addition you'll need to decide on a technology you'll use to deserialize the XML and store it somehow. I'd recommend XStream to deserialize but there're loads of options and you may already have a preference.
Then you'll want to store the Name objects you've deserialized. I'd recommend that you use ORMLite or DB4O.
You'll need a way to load a list of all names and a way to load the details of a particular name from whichever persistence technology you've chosen.
Your best bet is to try and do those things and then post new questions about specific problems you have trying to build the application.
Hope that helps... and isn't just teaching grandma to suck eggs
What is the best way to keep a List<String[]> while my application runs? I am having problems with my approach. It most of the time gives me an OutOfMemory Error since the list is too big.
The List<String[]> is the result of parsing a csv file that I have downloaded online. What I do is parse the csv in an activity then save its result in a static class member like:
String url = "http://xxx/pdf/pms/pms_test.csv";
try {
InputStream input = new URL(url).openStream();
CSVReader reader = new CSVReader(new InputStreamReader(input));
SchedController.sched = reader.readAll();
input.close();
}
...then access ClassName.sched on different activities.
I am doing this so that the parsed data will be available in every activity... And I don't have to parse again. What can I do to improve it?
I think you can have 2 approaches.
You save the file and parse it in a lazy loading way
You create a database and save your data.
I suggest you to create a database, this is not difficult and let you to manage well your data. You can do easily lazyLoading with cursor, or use a ORM (ORMLite / Greendao)... I think this is the best way and the fastest to load your data.
Hope this will help you.
Just to add to Paresh's comment.
I can suggest something similar I used in my app.
For example I need to display list of Items in a store. (Each item will have ID, name and cost).
To achieve this I first make a request to server to get number of items, say itemCount.
Now I set a limit to number of items displayed in a page say 100.
If the itemCount is greater than 100, I display an alert saying only 100 items will be displayed and a next button can be added to download next set of items.
Or if it is a search you can ask user to go back and refine the search.
If itemCount is less than 100 then you will not have any issues
This way Paging can be implemented to avoid OutOfMemory issues
I've used arrays in other languages (Python, MATLAB/Octave, C, Visual Basic, BASIC), but I haven't figured out how to use them in Android.
For example, how would I modify the Hello World program at World program at http://developer.android.com/resources/tutorials/hello-world.html to replace "Hello, Android" with the name of a TV show denoted by an index number (tvshow[0], tvshow[1], etc.)? Let's name the array tvshow, and the four values in the array are "Route 66", "The Twilight Zone", "Magnum P.I.", and "MASH".
What method(s) can I use to accomplish this?
There is also ArrayList . So all you have to do to add is call the add method and to read you use the get method.
ArrayList <String> myArrayList = new ArrayList<String>();
//this is how you add the elements you want to.
myArrayList.add("Route 66");
myArrayList.add("The Twitlight Zone");
myArrayList.add("Magnum");
myArrayList.add("P.I.");
myArrayList.add("Mash");
and to read the element you want:
String tvShow= myArrayList.get(2);
The advantage over a normal array (i.e. the one that android developer mentioned) is that you dont need to define an array size and you can add new elements in case the tv shows you have aument by just calling the add method.
well , you are talking about strings , so for an array of strings , you can simply use:
String[] tvshow={"Route 66","The Twilight Zone","Magnum", "P.I.", "MASH"} ;
for using it , use:
String currentTvShow=tvshow[3];
for working with strings , read this:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
strings on java (and on android, since it's based on it) are not mutable (for various reasons) , so they can't be modified. if you wish to modify such a thing , either use StringBuilder or an array of chars .