In my app I am retrieving records from a server. The records are in an xml file. I'm able to get the file down and parse it without any trouble. I'm storing the results in a HashMap and I'd like to be able to put those results into my app's SQLite database.
Here's the code for the HashMap
ArrayList<HashMap<String, String>> StudentDownloads = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML(target);
Document doc = XMLfunctions.XMLfromString(xml);
if(XMLfunctions.XMLfromString(xml)==null){
Toast.makeText(this, "Badly Formed File", Toast.LENGTH_LONG).show();
finish();
}
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(this, "There Were No Student Results To Show", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("Students");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("Student Id", "Student Id " + XMLfunctions.getValue(e, "StudentId"));
map.put("Student Type", "Student Type" + XMLfunctions.getValue(e, "StudentType"));
map.put("Student Location", "Student Location" + XMLfunctions.getValue(e, "StudentLocation"));
map.put("Student Mother", "Student Mother" + XMLfunctions.getValue(e, "StudentMother"));
StudentDownloads.add(map);}
};
Now in my app, I have already created a data entry form that uses a class called StudentRecord, in my entry form I use this function to update the file
private void addStudent(StudentRecord newRecord){
mDB.beginTransaction();
try {
ContentValues StudentRecordToAdd = new ContentValues();
StudentRecordToAdd.put(Students.STUDENT_ID, newRecord.getStudentName());
StudentRecordToAdd.put(Student.STUDENT_TYPE, newRecord.getStudentType());
StudentRecordToAdd.put(Student.STUDENT_LOCATION, newRecord.getStudentLocation());
StudentRecordToAdd.put(Student.STUDENT_MOTHER, newRecord.getStudentMother());
mDB.insert(Student.STUDENT_TABLE_NAME,Student.STUDENT_ANIMALID, StudentRecordToAdd);
mDB.setTransactionSuccessful();
Toast.makeText(this,"Recorded Added ",0).show();
} finally {
mDB.endTransaction();
}
What's the best way to get my values from the HashMap to my NewRecord function? I've been looking at so long I think I've gone brain dead.
Thank you
If i'm reading you right, it sounds like you need to move your addStudent function from the form/activity where it lives right now into some kind of "helper" class:
private class dbHelper {
Database mDB; // set this up however you are doing it already
private void addStudent(StudentRecord newRecord){
mDB.beginTransaction();
try {
ContentValues StudentRecordToAdd = new ContentValues();
StudentRecordToAdd.put(Students.STUDENT_ID, newRecord.getStudentName());
StudentRecordToAdd.put(Student.STUDENT_TYPE, newRecord.getStudentType());
StudentRecordToAdd.put(Student.STUDENT_LOCATION, newRecord.getStudentLocation());
StudentRecordToAdd.put(Student.STUDENT_MOTHER, newRecord.getStudentMother());
mDB.insert(Student.STUDENT_TABLE_NAME,Student.STUDENT_ANIMALID, StudentRecordToAdd);
mDB.setTransactionSuccessful();
Toast.makeText(this,"Recorded Added ",0).show();
} finally {
mDB.endTransaction();
}
}
}
And then just make calls to that helper when you've parsed your XML
ArrayList<StudentRecord> StudentDownloads = new ArrayList<StudentRecord>();
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element)nodes.item(i);
int id = Integer.valueOf(XMLfunctions.getValue(e, "StudentId")));
int type = Integer.valueOf(XMLfunctions.getValue(e, "StudentType")));
String location = XMLfunctions.getValue(e, "StudentLocation"));
String mother = XMLfunctions.getValue(e, "StudentMother"));
StudentRecord newRecord = new StudentRecord(id, type, location, mother);
StudentDownloads.add(newRecord);
}
And then when you're done processing:
for (StudentRecord s : StudentDownloads) {
mDBHelper.addStudent(s);
}
Related
I have a categorized Notes view, let say the first categorized column is TypeOfVehicle the second categorized column is Model and the third categorized column is Manufacturer.
I would like to collect only the values for the first category and return it as json object:
I am facing two problems:
- I can not read the value for the category, the column values are emptry and when I try to access the underlying document it is null
the script won't hop over to the category/sibling on the same level.
can someone explain me what am I doing wrong here?
private Object getFirstCategory() {
JsonJavaObject json = new JsonJavaObject();
try{
String server = null;
String filepath = null;
server = props.getProperty("server");
filepath = props.getProperty("filename");
Database db;
db = utils.getSession().getDatabase(server, filepath);
if (db.isOpen()) {
View vw = db.getView("transport");
if (null != vw) {
vw.setAutoUpdate(false);
ViewNavigator nav;
nav = vw.createViewNav();
JsonJavaArray arr = new JsonJavaArray();
Integer count = 0;
ViewEntry tmpentry;
ViewEntry entry = nav.getFirst();
while (null != entry) {
Vector<?> columnValues = entry.getColumnValues();
if(entry.isCategory()){
System.out.println("entry notesid = " + entry.getNoteID());
Document doc = entry.getDocument();
if(null != doc){
if (doc.hasItem("TypeOfVehicle ")){
System.out.println("category has not " + "TypeOfVehicle ");
}
else{
System.out.println("category IS " + doc.getItemValueString("TypeOfVehicle "));
}
} else{
System.out.println("doc is null");
}
JsonJavaObject row = new JsonJavaObject();
JsonJavaObject jo = new JsonJavaObject();
String TypeOfVehicle = String.valueOf(columnValues.get(0));
if (null != TypeOfVehicle ) {
if (!TypeOfVehicle .equals("")){
jo.put("TypeOfVehicle ", TypeOfVehicle );
} else{
jo.put("TypeOfVehicle ", "Not categorized");
}
} else {
jo.put("TypeOfVehicle ", "Not categorized");
}
row.put("request", jo);
arr.put(count, row);
count++;
tmpentry = nav.getNextSibling(entry);
entry.recycle();
entry = tmpentry;
} else{
//tmpentry = nav.getNextCategory();
//entry.recycle();
//entry = tmpentry;
}
}
json.put("data", arr);
vw.setAutoUpdate(true);
vw.recycle();
}
}
} catch (Exception e) {
OpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
}
return json;
}
What you're doing wrong is trying to treat any single view entry as both a category and a document. A single view entry can only be one of a category, a document, or a total.
If you have an entry for which isCategory() returns true, then for the same entry:
isDocument() will return false.
getDocument() will return null.
getNoteID() will return an empty string.
If the only thing you need is top-level categories, then get the first entry from the navigator and iterate over entries using nav.getNextSibling(entry) as you're already doing, but:
Don't try to get documents, note ids, or fields.
Use entry.getColumnValues().get(0) to get the value of the first column for each category.
If the view contains any uncategorised documents, it's possible that entry.getColumnValues().get(0) might throw an exception, so you should also check that entry.getColumnValues().size() is at least 1 before trying to get a value.
If you need any extra data beyond just top-level categories, then note that subcategories and documents are children of their parent categories.
If an entry has a subcategory, nav.getChild(entry) will get the first subcategory of that entry.
If an entry has no subcategories, but is a category which contains documents, nav.getChild(entry) will get the first document in that category.
Before i used an ArrayList for this, but because of duplicate Album issues (which i resolved before API29 by using DISTINCT and GROUP BY statements) which are not allowed anymore to use inside a query.
I got values like this in my RecyclerViews Adapter: myArrayList.get(position).getAlbum();
But now that i'm using a HashMap, how can i get a value by position which i get from the adapter?
Code for adding values in Hashmap
HashMap<Integer, Album> albums = new HashMap<>();
String[] projection2 = { MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_MUSIC};
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
String sort = MediaStore.Audio.Media.ALBUM + " COLLATE NOCASE ASC";
cursor = resolver.query(musicUri, projection2, selection, null, sort);
try {
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int columnAlbumId = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int columnAlbumName = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
String albumId = cursor.getString(columnAlbumId);
String albumName = cursor.getString(columnAlbumName);
if(albums.containsKey(albumId) == false){
Album album = new Album(albumId, albumName);
albums.put(albumId, album);
}
cursor.moveToNext();
}
}
}catch (Exception e){
Log.e(TAG, "Exception caught when creating ALBUM!", e);
throw new Exception();
}
By definition the HashMap is not sorted so how about a SortedMap? An implementation of a SortedMap is a TreeMap which sorts the entries according to keys (or a Comparator).
I believe that suits you since your map has integers as keys.
Edit:
You can use a List or whatever collection suits you in your adapter. For example keep a reference to the ids and the albums which is the data that you're interested in displaying through the adapter.
private int[] ids;
private Album[] albums;
As you're passing the data (included in a map) to your adapter then you could extract that data and place it in the array containers so you can take advantage of the index. For example,
public MyAdapter(Map<Integer,Album> data){
ids = new int[map.size()];
albums = new Album[map.size()];
int i = 0;
for (Map.Entry<Integer,Album> e : map.entrySet()){
ids[i] = e.getKey();
albums[i++] = e.getValue();
}
}
Now that you have your arrays you can sort them also if you like and in case you want to grab the 3rd album and its id all you need to do is,
int id = ids[2];
Album album = albums[2];
I have a database created with location updates and in the database there is a bunch of locations x and y. and in the second method readFirestore() reads the location data and compares the favorite locations which came from sqlite database and if the favorite location is near the data from firestore it writes the campaign name which is on the same location to another database. But when I want to compare the favorite location in the firestore methot, there is just the last item of the database. I looked with the Log.
Code 1:
public List<DataModel> listFavoriteLocation(){
db = new DatabaseHelper(this);
SQLiteDatabase mydb = db.getWritableDatabase();
List<DataModel> data=new ArrayList<>();
Cursor csr = mydb.rawQuery("select * from "+TABLE+" ;",null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (csr.moveToNext()) {
dataModel= new DataModel();
String FAVCurrentLocationLAT = csr.getString(csr.getColumnIndexOrThrow("FAVCurrentLocationLAT"));
String FAVCurrentLocationLONG = csr.getString(csr.getColumnIndexOrThrow("FAVCurrentLocationLONG"));
dataModel.setFAVCurrentLocationLAT(FAVCurrentLocationLAT);
dataModel.setFAVCurrentLocationLONG(FAVCurrentLocationLONG);
stringBuffer.append(dataModel);
data.add(dataModel);
}
for (DataModel mo:data ) {
this.List_FAVCurrentLocationLAT = mo.getFAVCurrentLocationLAT();
this.List_FAVCurrentLocationLONG = mo.getFAVCurrentLocationLONG();
Log.i("helloLAT",""+List_FAVCurrentLocationLAT); //OK
Log.i("helloLONG",""+List_FAVCurrentLocationLONG); //OK
// This section writes the favorite locations seperately to the log.
}
return data;
}
Code 2:
public void readFirestore() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("campaigns")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
private String FSname,FScityLAT,FScityLONG,FScampaignStartDate,FScampaignEndDate;
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
for (QueryDocumentSnapshot document : task.getResult()) {
String name = document.getString("name");
String cityLAT = document.getString("cityLAT");
String cityLONG = document.getString("cityLONG");
String campaignStartDate = document.getString("campaignStartDate");
String campaignEndDate = document.getString("campaignEndDate");
this.FSname = name;
this.FScityLAT = cityLAT;
this.FScityLONG = cityLONG;
this.FScampaignStartDate = campaignStartDate;
this.FScampaignEndDate = campaignEndDate;
listFavoriteLocation();
String FS_FAVCurrentLocationLAT = List_FAVCurrentLocationLAT;
String FS_FAVCurrentLocationLONG = List_FAVCurrentLocationLONG;
Log.i("hellolist",""+List_FAVCurrentLocationLAT); // just writes the last loc item from sqlite
double FS_FAVCurrentLocationLAT_double = Double.parseDouble(FS_FAVCurrentLocationLAT); // Fav Loc DB
double FS_FAVCurrentLocationLONG_double = Double.parseDouble(FS_FAVCurrentLocationLONG); double FScityLAT_double = Double.parseDouble(FScityLAT); // Campaign Loc Firestore LAT
double FScityLONG_double = Double.parseDouble(FScityLONG);
double theta = FScityLONG_double - FS_FAVCurrentLocationLONG_double;
double dist = Math.sin(Math.toRadians(FS_FAVCurrentLocationLAT_double)) * Math.sin(Math.toRadians(FScityLAT_double)) + Math.cos(Math.toRadians(FS_FAVCurrentLocationLAT_double)) * Math.cos(Math.toRadians(FScityLAT_double)) * Math.cos(Math.toRadians(theta));
dist = Math.acos(dist);
dist = Math.toDegrees(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
if (dist <= 0.5) // 500 meter
{
SQLiteQueryFavCampaign = "INSERT OR REPLACE INTO myTable3(FAVCampaignName, FAVCampaigncampaignStartDate, FAVCampaigncampaignEndDate)" + " VALUES('"+FSname+"','"+FScampaignStartDate+"','"+FScampaignEndDate+"');";
SQLITEDATABASEFavCampaign.execSQL(SQLiteQueryFavCampaign);
Log.i("helloname",""+FSname);
}
}
} else {
}
}
});
Toast.makeText(CampaignActivity.this,"Creating", Toast.LENGTH_SHORT).show();
}
If I understand correctly: the listFavoriteLocation method properly retrieves the data you're expecting from the database. If you take a look at the rest of your code, you'll see that you are iterating over the list of data and overwriting your instance variables with them, one-by-one, until the list has been fully iterated over, meaning you will only preserve the last element in your instance once you've left the method.
So, to be clear, the following block will properly log every element, but only the values of the last element will be preserved in the two instance variables you're using (FAVCurrentLocationLAT and FavCurrentLocationLong):
for (DataModel mo:data ) {
this.List_FAVCurrentLocationLAT = mo.getFAVCurrentLocationLAT();
this.List_FAVCurrentLocationLONG = mo.getFAVCurrentLocationLONG();
Log.i("helloLAT",""+List_FAVCurrentLocationLAT); //OK
Log.i("helloLONG",""+List_FAVCurrentLocationLONG); //OK
// This section writes the favorite locations seperately to the log.
}
What you need to do is use the returned data list being loaded in the listFavoriteLocation method, and then manipulate it in the following code as you wish.
So, for example:
List<DataModel> data = listFavoriteLocation();
for (int i = 0; i < data.size(); i++) {
DataModel dataModel = data.get(i);
log.i("Data model "+i+": "+dataModel);
// Do work on each data model element here
}
I have a Map with different values:
props = new HashMap<String, Object>();
props.put("cmis:objectTypeId", "D:ruc:PLICO");
props.put("cmis:name", "PLICO_1.pdf");
props.put("cmis:description", "Descr");
props.put("ruc:doc_surname", "Rossi");
props.put("ruc:doc_name", "Mario");
I want to do a query (QueryStatement or other) that dynamically reads this parameters (some of them can be missing) and build QueryStatement.
Does it exist an easy way to generate the query String for QueryStatement? Or do I should iterate my Map to build a String containing all the parameters and values in my query?
My solution, but maybe somebody know how to improve it without dynamically build the query string:
StringBuilder query = new StringBuilder("SELECT * FROM ? where ");
String folder = null;
if (path!=null)
{
folder = findPath(path);
if (folder==null)
{
return null;
}
query.append("IN_FOLDER(?) AND ");
}
ArrayList <String> values = new ArrayList<String>();
Map<String, Object> properties = loadAnnotationAndData(doc);
String objectType = properties.remove(MyEnum.cmis_object_type_id.getValue()).toString();
for (Map.Entry<String, Object> entry : properties.entrySet())
{
System.out.println(entry.getKey() + " - " + entry.getValue());
query.append(entry.getKey() + "=? AND ");
values.add(entry.getValue().toString());
}
query.delete(query.length()-4, query.length());
query.append(" ORDER BY cmis:creationDate");
System.out.println(query.toString());
Session cmisSession = getCmisSession();
QueryStatement qs=
cmisSession.createQueryStatement(query.toString());
int offset = 1;
qs.setType(offset++, objectType);
if (path!=null)
{
qs.setString(offset++, folder);
}
for (int i=0; i<values.size(); i++)
{
System.out.println(values.get(i).toString());
qs.setString(i+offset, values.get(i).toString());
}
I have created an AsynTaskInsideActivity class that extends AsyncTask<Void, Void, List<String>> within the MainActivity as an inner class. I am using this AsynTaskInsideActivity for getting all the records from the location table. This location table has following columns:
location_id
country
state
zip_code
And I want to fetch records from each individual column. So, for storing every record of each individual column I created four List type arrays (i.e. one for each column) and successfully stored the retrieved Cursor data within each of them. Now, the problem is I need to return every column's records. So, to be specific how can I return those four individual List type arrays from a one AsyncTask class. Currently, I am returning only the list type array namely locationId which has all the location ids I fetched from location table's location_id column.
Questions:
How can I return multiple list array items from a single AsyncTask class? After all when we query a database, sometimes we need records from multiple columns from an individual table to process further operations.
Is there any better approach that I can use to overcome this problem? or I have to believe some things are really impossible.
This is what my AsyncTask class looks like:
public class AsyncTaskInsideActivity extends AsyncTask<Void, Void, List<String>> {
private static final String CLASS_TAG = AsyncTaskInsideActivity.class.getSimpleName();
#Override
protected List<String> doInBackground(Void... params) {
Log.v(CLASS_TAG, "AsyncTaskInsideActivity started successfully....");
SoCalledDbHelper soCalledDbHelper = new SoCalledDbHelper
(getBaseContext());
//key-value pairs for inserting data into the table
ContentValues soCalledValues = new ContentValues();
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_CITY_NAME, "Kim Kardishian");
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_STATE, "No Ass Holes");
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_ZIP_CODE, 007);
//insert location data
soCalledDbHelper.addLocationData(soCalledValues);
//For storing the cursor data which will be retrieved by the read query.
Cursor locationDataCursor;
//Query for all the data in the location table
locationDataCursor = soCalledDbHelper.getAllLocationData(null, null, null, null);
List<String> sCLocationId = new ArrayList<String>();
List<String> sCCityName = new ArrayList<String>();
List<String> sCState = new ArrayList<String>();
List<String> sCZipCode = new ArrayList<String>();
if (locationDataCursor.getCount() > 0) {
//Reset the cursor location
locationDataCursor.moveToPosition(-1);
while (locationDataCursor.moveToNext()) {
//Extracting data from the location cursor
sCLocationId.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("_id")));
sCCityName.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("city_name")));
sCState.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("state")));
sCZipCode.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("zip_code")));
}
Log.i(CLASS_TAG, "Success: Cursor has data! #Total Records: " +
locationDataCursor.getCount());
for (String locationIds : sCLocationId) {
Log.i(CLASS_TAG, "Location Id: + " + locationIds);
}
for (String cityNamez : sCCityName) {
Log.i(CLASS_TAG, "City Names: + " + cityNamez);
}
for (String statesNames : sCState) {
Log.i(CLASS_TAG, "State Names: + " + statesNames);
}
for (String zipCodes : sCZipCode) {
Log.i(CLASS_TAG, "Zip Codes: + " + zipCodes);
}
} else {
Log.w(CLASS_TAG, "Error: Cursor is empty! #Total Records: " +
locationDataCursor.getCount());
}
locationDataCursor.close();
soCalledDbHelper.close();
Log.v(CLASS_TAG, "AsyncTaskDbHelper ended successfully....");
return sCLocationId;
}
}
You could just return extend your AsyncTask off of AsyncTask<Void, Void, List<List<String>> and be done with it but this is not the best approach.
A better approach would be to extend off of AsyncTask<Void, Void, List<Location>> where Location is defined as:
public class Location
{
private String location_id;
private String country;
private String state;
private String zip_code;
// Constructors, getters and setters go here. Your IDE should be able to generate them.
// You can also override the toString method to format the output better
}
Your loop would then look something like this:
List<Location> locations_list = new ArrayList<Location>();
if (locationDataCursor.moveToFirst()) {// Moves to first if cursor is not empty
do{
Location location = new Location();
//Extracting data from the location cursor
location.setID(locationDataCursor.getString
(locationDataCursor.getColumnIndex("_id")));
location.setCity(locationDataCursor.getString
(locationDataCursor.getColumnIndex("city_name")));
location.setState(locationDataCursor.getString
(locationDataCursor.getColumnIndex("state")));
location.setZip(locationDataCursor.getString
(locationDataCursor.getColumnIndex("zip_code")));
// Add location to the list
locations_list.add(location)
}while (locationDataCursor.moveToNext())
Log.i(CLASS_TAG, "Success: Cursor has data! #Total Records: " +
locationDataCursor.getCount());
for (Location l : locations_list) {
Log.i(CLASS_TAG, "Location: " + l.toString());
}
} else {
Log.w(CLASS_TAG, "Error: Cursor is empty!"
}
// Close any open DB objects
locationDataCursor.close();
soCalledDbHelper.close();
Log.v(CLASS_TAG, "AsyncTaskDbHelper ended successfully....");
// Return the list of locations
return locations_list;
Well, after researching for the solution to this question over the internet and devoting several hours for getting the single AsyncTask to return multiple values I came up with a solution with a nested List array i.e. List<List<String>>
Original Credits:
#Simon: Who gave me an indication (or hint) that how could I update my AsyncTask to get the job done, that was proved to be really helpful.
#VERT9x: Thanks for putting the effort and getting the job done with a different approach.
Solution:
public class AsyncTaskInsideActivity extends AsyncTask<Void, Void, List<List<String>>> {
private static final String CLASS_TAG = AsyncTaskInsideActivity.class.getSimpleName();
#Override
protected List<String> doInBackground(Void... params) {
Log.v(CLASS_TAG, "AsyncTaskInsideActivity started successfully....");
SoCalledDbHelper soCalledDbHelper = new SoCalledDbHelper
(getBaseContext());
//key-value pairs for inserting data into the table
ContentValues soCalledValues = new ContentValues();
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_CITY_NAME, "Kim Kardishian");
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_STATE, "No Ass Holes");
soCalledValues.put(SoCalledContract.LocationTable.COLUMN_ZIP_CODE, 007);
//insert location data
soCalledDbHelper.addLocationData(soCalledValues);
//For storing the cursor data which will be retrieved by the read query.
Cursor locationDataCursor;
//Query for all the data in the location table
locationDataCursor = soCalledDbHelper.getAllLocationData(null, null, null, null);
List<String> sCLocationId = new ArrayList<String>();
List<String> sCCityName = new ArrayList<String>();
List<String> sCState = new ArrayList<String>();
List<String> sCZipCode = new ArrayList<String>();
if (locationDataCursor.getCount() > 0) {
//Reset the cursor location
locationDataCursor.moveToPosition(-1);
while (locationDataCursor.moveToNext()) {
//Extracting data from the location cursor
sCLocationId.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("_id")));
sCCityName.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("city_name")));
sCState.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("state")));
sCZipCode.add(locationDataCursor.getString
(locationDataCursor.getColumnIndex("zip_code")));
}
Log.i(CLASS_TAG, "Success: Cursor has data! #Total Records: " +
locationDataCursor.getCount());
for (String locationIds : sCLocationId) {
Log.i(CLASS_TAG, "Location Id: + " + locationIds);
}
for (String cityNamez : sCCityName) {
Log.i(CLASS_TAG, "City Names: + " + cityNamez);
}
for (String statesNames : sCState) {
Log.i(CLASS_TAG, "State Names: + " + statesNames);
}
for (String zipCodes : sCZipCode) {
Log.i(CLASS_TAG, "Zip Codes: + " + zipCodes);
}
} else {
Log.w(CLASS_TAG, "Error: Cursor is empty! #Total Records: " +
locationDataCursor.getCount());
}
locationDataCursor.close();
soCalledDbHelper.close();
//Creating a List that can store List(s) within it.
//List of Lists String
List<List<String>> arrayOfLists = new ArrayList<List<String>>();
//Adding those Lists that was used to store each column records
arrayOfLists.add(sCLocationId);
arrayOfLists.add(sCCityName);
arrayOfLists.add(sCState);
arrayOfLists.add(sCZipCode);
//Start iterating over the parent arrayOfLists List
for(int i = 0; i < arrayOfLists.size(); i++) {
//Print each arrayOfLists data item it contains
Log.v(CLASS_TAG, "Parent List: " + arrayOfLists.get(i).toString());
//Start iterating over child of arrayOfLists List
for(int j = 0; j < arrayOfLists.get(i).size(); j++) {
//Print each arrayOfLists CHILD data item it contains
Log.v(CLASS_TAG, "Child List: " + arrayOfLists.get(i).get(j).toString());
}
}
//Size of the arrayOfLists
Log.v(CLASS_TAG, "Parent List Size: " + Integer.toString(arrayOfLists.size()));
//Size of the arrayOfLists child container
Log.v(CLASS_TAG, "Child List Size: " + Integer.toString(arrayOfLists.get(1).size()));
Log.v(CLASS_TAG, "AsyncTaskDbHelper ended successfully....");
return arrayOfLists;
}
Changes I Made:
Changed the 3rd parameter of AsyncTask class and doInBackground() return type to List<List<String>>, so it can return multiple values.
For solution see under these two lines:
locationDataCursor.close();
soCalledHelper.close();