I trying to store a list of songs that I query from Android Media Store but I am not sure how to save multiple columns (i.e. song name, track path, duration, etc..)
I currently use a HashMap and ArrayList to display the song Name and Duration in a list view but I'd like to store more information from my query. Any tips on how to get a multidimensional vector/container of some sort? I tried using JSON obj/arrays but I everytime I store values in them I can only get that last one out...
while (c.moveToNext()) {
HashMap<String, String> temp = new HashMap<String, String>();
temp.put("Title", c.getString(c
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
temp.put("Duration", Tools.stringOfTime(Long.parseLong(c.getString(c
.getColumnIndex(MediaStore.Audio.Media.DURATION)))));
list.add(temp);
JSON attempt... basically I added each query row into 1 json object and kept putting those objects into a json array but for some reason I can only get the last value from my list where as the hashmap approach works fine but can only store 2 fields..
// object = new JSONObject();
// try {
// object.put(
// "Title",
// c.getString(c
// .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
// object.put("Data", c.getString(c
// .getColumnIndex(MediaStore.Audio.Media.DATA)));
// object.put("Artist", c.getString(c
// .getColumnIndex(MediaStore.Audio.Media.ARTIST)));
// object.put("Album", c.getString(c
// .getColumnIndex(MediaStore.Audio.Media.ALBUM)));
// object.put("Duration", c.getString(c
// .getColumnIndex(MediaStore.Audio.Media.DURATION)));
// jarray.put(object);
// } catch (JSONException e) {
// e.printStackTrace();
// }
//
// jlist.add(object);
// }
// try {
// tv.setText(object.getString("Title"));
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// Log.d("SongsActivity", "Couldn't print json object");
// }
Store the cursor object in an Application class field variable.
Like: http://developer.android.com/reference/android/app/Application.html
Did some quick research, and almost every answer I see to questions like this returns to: run the query again in the next activity.
The other answer was to create an application class to act as a data hub.
Related
Hi I'm using the Google Sheets API v4 for Java.
I want to make a Server List where I register up new Server IP's for my own small project. At the moment I can append a new Entry at a empty row using
AppendCellsRequest appendCellReq = new AppendCellsRequest();
appendCellReq.setSheetId(0);
appendCellReq.setRows(rowData);
appendCellReq.setFields("userEnteredValue");
The Problem is now, that I want delete this row later, so I need to figure out how to find it later. My Idea was to add a UniqueID or to search for the exact added Values or to remember the row number. However a way would it be to find and replace all cells. But I would rather have a way to get the row number of my added data.
I'm very happy to hear some advices.
Since long search I finaly found an answer. There are tutorials which indeed made it possible to append a row, but wasnt able to return in which Row they inserted. With this code its now possible. I found it after hours of searching somewhere. It is not the best code, but it works and can be modified.
String range = "A1"; // TODO: Update placeholder value.
// How the input data should be interpreted.
String valueInputOption = "RAW"; // TODO: Update placeholder value.
// How the input data should be inserted.
String insertDataOption = "INSERT_ROWS"; // TODO: Update placeholder value.
// TODO: Assign values to desired fields of `requestBody`:
ValueRange requestBody = new ValueRange();
List<Object> data1 = new ArrayList<Object>();
data1.addAll(Arrays.asList(dataArr));
List<List<Object>> data2 = new ArrayList<List<Object>>();
data2.add(data1);
requestBody.setValues(data2);
Sheets sheetsService;
try {
sheetsService = getSheetsService();
Sheets.Spreadsheets.Values.Append request = sheetsService.spreadsheets().values().append(spreadSheetId,
range, requestBody);
request.setValueInputOption(valueInputOption);
request.setInsertDataOption(insertDataOption);
AppendValuesResponse response = request.execute();
// TODO: Change code below to process the `response` object:
Logger.println(response.getTableRange());
String startCell = response.getTableRange().split(":")[1];
String colString = startCell.replaceAll("\\d", "");
String row = startCell.replaceAll(colString, "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am displaying list of data based on the query result in MAF along with A-Team persistence accelerator, below is the sample code which i'm using when some action button has been clicked,
ClassMappingDescriptor descriptor = ClassMappingDescriptor.getInstance(PojoClass.class);
DBPersistenceManager pm= getLocalPersistenceManager();
try {
StringBuffer sql = pm.getSqlSelectFromPart(descriptor);
sql.append(" WHERE ACTIVE_FLAG='YES'");
sql = pm.constructOrderByClause(sql, descriptor);
ResultSet set = pm.executeSqlSelect(sql.toString(), new ArrayList());
List ResultList = pm.createEntitiesFromResultSet(set, (List) descriptor.getAttributeMappingsDirect());
System.out.println("ResultList size : " +ResultList.size())
setEntityList(ResultList);
} catch (Exception exp) {
System.out.println("Exception : " + exp);
}
If ResultList size returns any value then it is working as expected, But when ever ResultList size returns 0 then listView showing all data of the particular associated pojo class table. In this case, actually non of the record should be displayed.
Any help would be appreciated, please comment below if you need any more details regarding this.
I understand that people have faced this issue before and I have gone through the previous posts.
I have an arrayList and I'm trying to add objects to it. During every add call, the same object reference is being copied. Though I have used the 'new' operator and am creating new objects. This is something basic and has worked previously when I create the object again during each iteration.
Any help is much appreciated.
Here is my code.
public List<Actor> readAllActors()
{
String selectMovie = "SELECT * from ACTOR;";
List<Actor> listOfActors = new ArrayList<Actor>();
try {
statement = conn.prepareStatement(selectMovie);
results = statement.executeQuery(selectMovie);
Actor a = new Actor();
while (results.next())
{
a = getActorFromResult(results);
listOfActors.add(new Actor(a.getId(), a.getFirstName(), a.getLastName(), a.getDateOfBirth()));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfActors;
}
private Actor getActorFromResult(ResultSet results) throws SQLException {
// TODO Auto-generated method stub
int id = results.getInt("id");
String fname = results.getString("firstName");
String lname = results.getString("lastName");
String dob = results.getString("dateOfBirth");
Actor actor = new Actor(id, fname, lname, dob );
return actor;
}
I have tried printing the object in each iteration. It is fetching the right row from the table.. the new Actor() seems to have no effect in creating a new object reference!!
Your code is fine and can't pass the same reference all the time. You can check it via a == check of your listed objects.
You could refactor you code to
results = statement.executeQuery(selectMovie);
while (results.next())
{
listOfActors.add(getActorFromResult(results));
}
as you're creating a new Actor and thus a new object with an own reference after fetching the result set. This will also make the code clearer here.
Also return new Actor(id, fname, lname, dob ); will do the job in your result method. You're not using the self-descriptive local variable anyways.
I suspect your problem lies in your database. Try querying it with a database tool.
try to change that line
listOfActors.add(new Actor(a.getId(), a.getFirstName(), a.getLastName(), a.getDateOfBirth()));
to that
listOfActors.add(getActorFromResult(results));
and delete line
a = getActorFromResult(results);
Your references are for sure not the same, please check it in debugger.
I am trying to catch values from the database in to a array list. and i want to get only the latitude and the longitude to create the markers.
here is my gettemple() function in db handler class
public ArrayList<kovil> Get_Temple(String temple_type, String Limit) {
try {
temple_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TEMPLE +"WHERE KEY_TMPTYPE=" + temple_type +"LIMIT" + Limit;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.print("CALLED");
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
kovil Kovil = new kovil();
Kovil.setID(Integer.parseInt(cursor.getString(0)));
Kovil.settemplename(cursor.getString(1));
Kovil.settempletype(cursor.getString(2));
Kovil.setlatitude(cursor.getString(3));
Kovil.setlongitude(cursor.getString(4));
Kovil.setimage_name(cursor.getString(5));
Kovil.setyear_build(cursor.getString(6));
Kovil.setaddress(cursor.getString(7));
Kovil.setcity(cursor.getString(8));
Kovil.setemail(cursor.getString(9));
Kovil.setwebsite(cursor.getString(10));
Kovil.settelephone1(cursor.getString(11));
Kovil.settelephone2(cursor.getString(12));
Kovil.setDescription(cursor.getString(13));
// Adding contact to list
temple_list.add(Kovil);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return temple_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_temples", "" + e);
}
return temple_list;
}
this will return the temple_list array in the same class.
private final ArrayList<kovil> temple_list = new ArrayList<kovil>();
and trying to call the Get_Temple() function in view map class
dbhand.Get_Temple((getIntent().getExtras().getString("temple_type")), getIntent().getExtras().getString("notemples"));
for (int i=0; i< Integer.parseInt(getIntent().getExtras().getString("notemples"));i++) {
//displaytemples(9.662502, 80.010239, "mugan kovil");
}
and i am trying to display the markers using this class
public boolean displaytemples(double lati, double longi, String templename){
MarkerOptions marker = new MarkerOptions().position(new LatLng(lati, longi)).title(templename);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon));
//marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(marker);
return true;
}
I want to catch only the latitude and the longitude from the array list and using that for loop i want to pass the latitude and the longitude to the displaytemples ().
can any one help me to write the for loop which will catch only the latitude and the longitude and pass it to the displaytemples() function. thank you...
To be honest, your code makes me scared... But that's different problem. The only thing I would point out - is please do not fetch DB from the main thread. You are blocking UI this way :( . Look at AsyncTask or some other ways to offload DB operations off the main thread..
As for your problem - you can try something like this:
ArrayList<kovil> data = dbhand.Get_Temple(getIntent().getExtras().getString("temple_type"),
getIntent().getExtras().getString("notemples"));
for (kovil temple: data) {
displaytemples(Double.parseDouble(temple.getlatitude(),
temple.getlongitude(),
temple.gettemplename());
}
I'm working in a project with DB. There are a method that collect info from the DB and set the info in ArrayList:
public ArrayList<Director> listAll(){
ArrayList<Director>list = new ArrayList<Director>();
Director direc = new Director();
int cont=0;
String sql = "select * from director;";
try{
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next()){
direc.setCode(res.getInt("CODE"));
direc.setName(res.getString("NAME"));
direc.setNationality(res.getString("NATIONALITY"));
direc.setOscar(res.getInt("OSCAR"));
list.add(direc);
// THIS IS USE TO CONFIRM IF IT WORKS ///////////////////////////////////////
// JOptionPane.showMessageDialog(null,"Code:"+list.get(cont).getCode()+"Nombre"+list.get(cont).getName());
// cont++;
}
}catch (SQLException e) {
e.printStackTrace();
}
return list;
}
I use JOptionPane.showMessageDialog to see if I get info from DB and is added correctly to de ArrayList, and it's works.
Now the ArrayList back the invoker class, this is the method:
private void stackArray(){
ArrayList<Director>arrayDir = new ArrayList<Director> ();
ArrayList<Director>arrayDir = conexion.listAll();
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(0).getCode()+"Name"+arrayDir.get(0).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(1).getCode()+"Name"+arrayDir.get(1).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(2).getCode()+"Name"+arrayDir.get(2).getName());
}
Again I use the JOptionPane.showMesageDialog to show the first three positions, but it's not work, the problem, as far as I've seen, is all the positions have the same object saved (exactly the last).
Summarizing the ArrayList have the same object (last in DB), there are no problems at run or compile.
I don't know if I write something bad, or just a noob fail.
the problem, as far as I've seen, is all the positions have the same
object saved (exactly the last).
You are changing value of same instance Director. Thats why, you seen the last value of Director object. You should create new instance of Director with iteration of while loop.
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next){
Director direc = new Director();// Declare Director instance here.
.....
list.add(direc);
}