why cannot insert data into sqlite? - java

i got no idea why it return me nullpointerexception. I think is because the table don't have data. So, the data seem like did not add into database
this is my activity class.
private void createdata(){
String title[] = {"rancangan1", "rancangan2", "rancangan3", "rancangan4", "rancangan5"};
String date[] = {"isnin", "selasa", "rabu", "khamis", "jumaat"};
String time[] = {"17:00-18:00", "18:00-19:00", "17:00-18:00", "18:00-19:00", "19:00-20:00"};
String channel[] = {"astro ria", "astro ria", "astro ria", "astro ria", "astro ria"};
try{
for(int i = 0; i < title.length; i++){
ContentValues values = new ContentValues();
values.put(ImamShareData.DataContent.KEY_PROGRAM_TITLE, title[i]);
values.put(ImamShareData.DataContent.KEY_PROGRAM_DATE, date[i]);
values.put(ImamShareData.DataContent.KEY_PROGRAM_TIME, time[i]);
values.put(ImamShareData.DataContent.KEY_PROGRAM_CHANNEL, channel[i]);
cr.insert(ImamShareData.DataContent.PROGRAM_URI, values);
//Log.i(TAG, "Successfully added index " + i + " as ID " + mId[i]);
}
}catch(Exception e){
Log.v("error",""+e);
}
}
private void filldata(){
String[] from = new String[]{ImamShareData.DataContent.KEY_PROGRAM_DATE, ImamShareData.DataContent.KEY_PROGRAM_TIME, ImamShareData.DataContent.KEY_PROGRAM_CHANNEL};
String[] from1 = new String[]{ImamShareData.DataContent.KEY_PROGRAM_TITLE};
int[] to = new int[]{R.id.programdate, R.id.programtime, R.id.programchannel};
int[] to1 = new int[]{R.id.programtitle};
SimpleExpandableListAdapter SEL = new SimpleExpandableListAdapter(this,
createGroupList(), R.layout.programgroup_row, from1, to1,
createChildList(), R.layout.programchild_row, from, to);
setListAdapter( SEL );
}
private List createGroupList() {
String[] column = new String[]{ImamShareData.DataContent.KEY_PROGRAM_TITLE};
ArrayList result = new ArrayList();
String title[] = null;
for( int i = 1 ; i <= 5; ++i ) {
Cursor cursor = managedQuery(ImamShareData.DataContent.PROGRAM_URI, column, null, null, null);
HashMap m = new HashMap();
title[i] = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_TITLE));
m.put(ImamShareData.DataContent.KEY_PROGRAM_TITLE, title[i]);
result.add( m );
}
return result;
}
private List createChildList() {
String date;
String time;
String channel;
String[] column = new String[]{ImamShareData.DataContent.KEY_PROGRAM_DATE, ImamShareData.DataContent.KEY_PROGRAM_TIME, ImamShareData.DataContent.KEY_PROGRAM_CHANNEL};
ArrayList result = new ArrayList();
for( int i = 1 ; i <= 5 ; ++i ) {
ArrayList secList = new ArrayList();
for( int n = 0 ; n < 3 ; n+=3 ) {
Cursor cursor = managedQuery(ImamShareData.DataContent.PROGRAM_URI, column, null, null, null);
HashMap child = new HashMap();
date = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_DATE));
time = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_TIME));
channel = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_CHANNEL));
child.put(ImamShareData.DataContent.KEY_PROGRAM_DATE, date);
child.put(ImamShareData.DataContent.KEY_PROGRAM_TIME, time);
child.put(ImamShareData.DataContent.KEY_PROGRAM_CHANNEL, channel);
secList.add( child );
}
result.add( secList );
}
return result;
}
this is my contentprovider class
#Override
public Uri insert(Uri uri, ContentValues initialvalues) {
TableNumber = sUriMatcher.match(uri);
if( TableNumber != PROGRAM){
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if(initialvalues != null){
values = new ContentValues(initialvalues);
}else{
values = new ContentValues();
}
SQLiteDatabase mDb = mDbHelper.getWritableDatabase();
long rowId = mDb.insert(DatabaseHelper.TABLE_PROGRAM, null, values);
if(rowId > 0){
Uri programUri = ContentUris.withAppendedId(ImamShareData.DataContent.PROGRAM_URI, rowId);
getContext().getContentResolver().notifyChange(programUri, null);
return programUri;
}
throw new IllegalArgumentException("Failed to insert row into " + uri);
}
this is my datasharing class
public static final class DataContent implements BaseColumns{
public static final Uri PROGRAM_URI = Uri.parse("content://" + AUTHORITY + "/" + PROGRAMPATH);
public static final String CONTENT_MORE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.android.imammuda";
public static final String CONTENT_ONE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.android.imammuda";
public static final String KEY_PROGRAM_ID = "_id";
public static final String KEY_PROGRAM_TITLE = "ProgramTitle";
public static final String KEY_PROGRAM_DATE = "ProgramDate";
public static final String KEY_PROGRAM_TIME = "ProgramTime";
public static final String KEY_PROGRAM_CHANNEL = "ProgramChannel";
}
this is my logcat
05-12 16:05:46.024: ERROR/AndroidRuntime(5175): Caused by: java.lang.NullPointerException
05-12 16:05:46.024: ERROR/AndroidRuntime(5175): at com.android.imammuda.Program.createGroupList(Program.java:112)
05-12 16:05:46.024: ERROR/AndroidRuntime(5175): at com.android.imammuda.Program.filldata(Program.java:82)

You have not initialized your title variable in method createGroupList:
String title[] = null;
...
title[i] = cursor.getColumnName....
in the for loop the length is hard coded to maximum 5, so the easiest fix is:
String[] title = new String[5];

Related

Displayed all Fetched data SQLite

Hi I have this code which retrieves data from the SQLite local database I have created.
the code below is a public cursor which retrieves all the data i require from the database
public Cursor RetriveAdvertData (DatabasOpperations DBOpp, String Username, String AdvertType){
SQLiteDatabase SQDB = DBOpp.getReadableDatabase();
String[] Coloumns = {TableData.TableInfo.USERNAME, TableData.TableInfo.ADVERT_NAME, TableData.TableInfo.ADVERT_EMAIL, TableData.TableInfo.ADVERT_ADDRESS, TableData.TableInfo.ADVERT_NUMBER, TableData.TableInfo.ADVERT_TYPE};
String Where = TableData.TableInfo.USERNAME + " LIKE ? AND " + TableData.TableInfo.ADVERT_TYPE + " LIKE ?";
String Argument[] = {Username, AdvertType};
Cursor Cur = SQDB.query(TableData.TableInfo.TABLE_NAME2, Coloumns, Where, Argument, null, null, null);
return Cur;
}
I then call that Cursor in another java page
Context Contx = this;
public DatabasOpperations DB = new DatabasOpperations(Contx);
public Cursor Cur;
Cur = DB.RetriveAdvertData(DB, DBUsername, "Restaurant");
String AdName = "";
String AdEmail = "";
String AdAddress = "";
String AdNumber = "";
String AdType = "";
if (Cur.moveToFirst()){
do {
AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));
final String[] Adverts = new String[]{
AdName, AdEmail, AdAddress, AdNumber, AdType
};
ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Adverts);
LV1.setAdapter(setListAdapter);
}while (Cur.moveToNext());
}
Cur.close();
the code does display only one row from the database, how do i amend the code to display all the rows in the database?
Try to put the setAdapter out of the while loop:
List<String[]> arr = new ArrayList<>();
if (Cur.moveToFirst()) {
do {
AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));
final String[] Adverts = new String[]{
AdName, AdEmail, AdAddress, AdNumber, AdType
};
arr.add(Adverts)
} while (Cur.moveToNext());
}
Cur.close();
ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arr);
LV1.setAdapter(setListAdapter);

When using gson to serialize a POJO in a JSP page, output is empty. What am I missing?

I have a JSP page that runs a database query and serializes the results to JSON. The object that I am serializing is this:
class DataObject {
private int iTotalRecords;
private int iTotalDisplayRecords;
private String sEcho;
private ArrayList<String> columns;
private ArrayList<ArrayList<String>> data;
//getter and setter methods
public void setColumns( ArrayList<String> cols ) {
columns = cols;
}
public void setTotalDisplayRecords( int _numrecs ) {
iTotalDisplayRecords = _numrecs;
}
public void setTotalRecords( int _numrecs ) {
iTotalRecords = _numrecs;
}
public void setData( ArrayList<ArrayList<String>> _data ) {
data = _data;
}
public void setEcho( String _echo ) {
sEcho = _echo;
}
#Override
public String toString() {
return "DataObject [iTotalRecords=" + iTotalRecords +
", iTotalDisplayRecords=" + iTotalDisplayRecords +
", sEcho=" + sEcho +
", columns=" + columns +
", data=" + data + "]";
}
public DataObject() {
this.sEcho = "1";
this.iTotalDisplayRecords = 0;
this.iTotalRecords = 0;
this.columns = new ArrayList<String>();
this.data = new ArrayList<ArrayList<String>>();
}
}
I have simplified the page, the JSP (which still produces blank JSON) is shown below:
String queryOvr = "select 'error' as Input_Parameters";
String sEcho = "0";
LOG.error("db_json_test.jsp - QUERY: " + queryOvr);
int rowCount=0;
int totalCount=0;
Statement stmt = null;
ResultSet returnData = null;
Connection conn = null;
try {
conn = DatabaseUtilities.getConnection(); //proprietary connection pool of host application
stmt = conn.createStatement();
returnData = stmt.executeQuery(queryOvr);
ResultSetMetaData rsmd = returnData.getMetaData();
DataObject dObj = new DataObject();
ArrayList<String> headerRow = new ArrayList<String>();
int colCount = rsmd.getColumnCount();
// write column names
for (int i=0; i<colCount; i++) {
String headerName = rsmd.getColumnName(i+1);
if ("".equals(headerName)) {
headerName = "Column-" + String.valueOf(i+1);
}
LOG.error("db_json_test.jsp - HEADER: " + headerName);
headerRow.add(headerName);
}
dObj.setColumns(headerRow);
// write data
ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
while ( returnData.next() ) {
rowCount++;
ArrayList<String> dataRow = new ArrayList<String>();
for (int i=0; i<colCount; i++){
String dbData = returnData.getString(i+1);
LOG.error("db_json_test.jsp - DATA: row: " + headerRow.get(i) + ", value: " + dbData);
dataRow.add(dbData);
}
dataArray.add(dataRow);
totalCount++;
}
dObj.setData(dataArray);
dObj.setEcho(sEcho);
dObj.setTotalRecords(totalCount);
dObj.setTotalDisplayRecords(rowCount);
LOG.error("db_json_test.jsp - OBJ: " + dObj.toString());
Type typeResults = new TypeToken<DataObject>(){}.getType();
Gson gson = new Gson();
String json = gson.toJson(dObj, typeResults);
LOG.error("db_json_test.jsp - JSON: " + json);
//gson.toJson(dObj, typeResults, response.getWriter());
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
}
catch (Throwable t) {
LOG.error("db_json.jsp - Error: " + t.toString());
//t.printStackTrace();
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write("{\"error\":\"" + t.toString() + "\"}");
response.getWriter().flush();
response.getWriter().close();
}
When I look in the logs I can see that the DataObject instance is getting properly populated:
783167943 30 Sep 2015 17:37:51,924 ERROR [http-8500-1] JSP - db_json_test.jsp - QUERY: select 'error' as Input_Parameters
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - HEADER: Input_Parameters
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - DATA: row: Input_Parameters, value: error
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - OBJ: DataObject [iTotalRecords=1, iTotalDisplayRecords=1, sEcho=0, columns=[Input_Parameters], data=[[error]]]
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - JSON:
However when I go to serialize it using gson.toJson(dObj) I get a blank string. I have tried specifying the type as shown in the example above to no different results. Outside of the argument that I probably shouldn't be doing this in a JSP file, what am I missing here?
Worth noting is that the catch routine does return the error message as valid JSON, so the contentType and charset are getting properly set in the headers.
The following Java code DOES produce the expected JSON...
public class gsonTest {
class DataObject {
private int iTotalRecords;
private int iTotalDisplayRecords;
private String sEcho;
private ArrayList<String> columns;
private ArrayList<ArrayList<String>> data;
// getter and setter methods
public void setColumns(ArrayList<String> cols) {
columns = cols;
}
public void setTotalDisplayRecords(int _numrecs) {
iTotalDisplayRecords = _numrecs;
}
public void setTotalRecords(int _numrecs) {
iTotalRecords = _numrecs;
}
public void setData(ArrayList<ArrayList<String>> _data) {
data = _data;
}
public void setEcho(String _echo) {
sEcho = _echo;
}
#Override
public String toString() {
return "DataObject [iTotalRecords=" + iTotalRecords
+ ", iTotalDisplayRecords=" + iTotalDisplayRecords
+ ", sEcho=" + sEcho
+ ", columns=" + columns
+ ", data=" + data + "]";
}
public DataObject() {
this.sEcho = "";
this.iTotalDisplayRecords = 0;
this.iTotalRecords = 0;
this.columns = new ArrayList<String>();
this.data = new ArrayList<ArrayList<String>>();
}
}
public static void main(String[] args) {
int totalCount = 0;
String sEcho = "1";
Gson gson = new Gson();
gsonTest tst = new gsonTest();
Type typeResults = new TypeToken<DataObject>(){}.getType();
DataObject obj = tst.new DataObject();
ArrayList<String> headerRow = new ArrayList<String>();
// write column names
int colCount = 2;
for (int i = 0; i < colCount; i++) {
headerRow.add("Column-" + String.valueOf(i));
}
obj.setColumns(headerRow);
// write data
ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
int rowCount = 0;
while (rowCount < 20) {
ArrayList<String> dataRow = new ArrayList<String>();
for (int i = 0; i < colCount; i++) {
dataRow.add("Row-" + String.valueOf(rowCount) + ":Col-"
+ String.valueOf(i));
}
rowCount++;
dataArray.add(dataRow);
totalCount++;
}
obj.setData(dataArray);
obj.setEcho(sEcho);
obj.setTotalRecords(totalCount);
obj.setTotalDisplayRecords(rowCount);
String output = gson.toJson(obj,typeResults);
System.out.println(obj.toString());
System.out.println(output);
}
}
Here is the output:
DataObject [iTotalRecords=20, iTotalDisplayRecords=20, sEcho=1,
columns=[Column-0, Column-1], data=[[Row-0:Col-0, Row-0:Col-1],
[Row-1:Col-0, Row-1:Col-1], [Row-2:Col-0, Row-2:Col-1], [Row-3:Col-0,
Row-3:Col-1], [Row-4:Col-0, Row-4:Col-1], [Row-5:Col-0, Row-5:Col-1],
[Row-6:Col-0, Row-6:Col-1], [Row-7:Col-0, Row-7:Col-1], [Row-8:Col-0,
Row-8:Col-1], [Row-9:Col-0, Row-9:Col-1], [Row-10:Col-0,
Row-10:Col-1], [Row-11:Col-0, Row-11:Col-1], [Row-12:Col-0,
Row-12:Col-1], [Row-13:Col-0, Row-13:Col-1], [Row-14:Col-0,
Row-14:Col-1], [Row-15:Col-0, Row-15:Col-1], [Row-16:Col-0,
Row-16:Col-1], [Row-17:Col-0, Row-17:Col-1], [Row-18:Col-0,
Row-18:Col-1], [Row-19:Col-0, Row-19:Col-1]]]
{"iTotalRecords":20,"iTotalDisplayRecords":20,"sEcho":"1","columns":["Column-0","Column-1"],"data":[["Row-0:Col-0","Row-0:Col-1"],["Row-1:Col-0","Row-1:Col-1"],["Row-2:Col-0","Row-2:Col-1"],["Row-3:Col-0","Row-3:Col-1"],["Row-4:Col-0","Row-4:Col-1"],["Row-5:Col-0","Row-5:Col-1"],["Row-6:Col-0","Row-6:Col-1"],["Row-7:Col-0","Row-7:Col-1"],["Row-8:Col-0","Row-8:Col-1"],["Row-9:Col-0","Row-9:Col-1"],["Row-10:Col-0","Row-10:Col-1"],["Row-11:Col-0","Row-11:Col-1"],["Row-12:Col-0","Row-12:Col-1"],["Row-13:Col-0","Row-13:Col-1"],["Row-14:Col-0","Row-14:Col-1"],["Row-15:Col-0","Row-15:Col-1"],["Row-16:Col-0","Row-16:Col-1"],["Row-17:Col-0","Row-17:Col-1"],["Row-18:Col-0","Row-18:Col-1"],["Row-19:Col-0","Row-19:Col-1"]]}
After digging further I came to a workable solution. By combining the test Java class into the JSP as follows I got the correct output. I am unsure why this worked and the original did not
<%# page
language="java"
session="true"
contentType="application/json; charset=UTF-8"
%>
<%# page import="com.google.gson.Gson,
java.lang.reflect.Type,
com.google.gson.reflect.TypeToken,
java.util.ArrayList,
java.sql.*,
org.apache.log4j.Category,
com.foo.bar.*;"
%>
<%
final org.apache.log4j.Category LOG = org.apache.log4j.Category.getInstance ("JSP");
class db_json {
class DataObject {
private int iTotalRecords;
private int iTotalDisplayRecords;
private String sEcho;
private ArrayList<String> columns;
private ArrayList<ArrayList<String>> data;
// getter and setter methods
public void setColumns(ArrayList<String> cols) {
columns = cols;
}
public void setTotalDisplayRecords(int _numrecs) {
iTotalDisplayRecords = _numrecs;
}
public void setTotalRecords(int _numrecs) {
iTotalRecords = _numrecs;
}
public void setData(ArrayList<ArrayList<String>> _data) {
data = _data;
}
public void setEcho(String _echo) {
sEcho = _echo;
}
#Override
public String toString() {
return "DataObject [iTotalRecords=" + iTotalRecords
+ ", iTotalDisplayRecords=" + iTotalDisplayRecords
+ ", sEcho=" + sEcho
+ ", columns=" + columns
+ ", data=" + data + "]";
}
public DataObject() {
this.sEcho = "";
this.iTotalDisplayRecords = 0;
this.iTotalRecords = 0;
this.columns = new ArrayList<String>();
this.data = new ArrayList<ArrayList<String>>();
}
}
public String testJson(HttpServletRequest request){
String queryOvr = "select 'error' as Input_Parameters";
LOG.debug("db_json3.jsp - QUERY: " + queryOvr);
Gson gson = new Gson();
int rowCount=0;
int totalCount=0;
Statement stmt = null;
ResultSet returnData = null;
Connection conn = null;
try {
conn = DatabaseUtilities.getConnection();
stmt = conn.createStatement();
returnData = stmt.executeQuery(queryOvr);
ResultSetMetaData rsmd = returnData.getMetaData();
DataObject dObj = new DataObject();
ArrayList<String> headerRow = new ArrayList<String>();
int colCount = rsmd.getColumnCount();
// write column names
for (int i=0; i<colCount; i++) {
String headerName = rsmd.getColumnName(i+1);
if ("".equals(headerName)) {
headerName = "Column-" + String.valueOf(i+1);
}
LOG.debug("db_json3.jsp - HEADER: " + headerName);
headerRow.add(headerName);
}
dObj.setColumns(headerRow);
// write data
ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
while ( returnData.next() ) {
if ( rowCount>=iDisplayStart && iDisplayLength>=0 && rowCount<iDisplayLength ) {
rowCount++;
ArrayList<String> dataRow = new ArrayList<String>();
for (int i=0; i<colCount; i++){
String dbData = returnData.getString(i+1);
LOG.debug("db_json3.jsp - DATA: row: " + headerRow.get(i) + ", value: " + dbData);
dataRow.add(dbData);
}
dataArray.add(dataRow);
}
totalCount++;
}
dObj.setData(dataArray);
dObj.setEcho(sEcho);
dObj.setTotalRecords(totalCount);
dObj.setTotalDisplayRecords(rowCount);
LOG.debug("db_json3.jsp - OBJ: " + dObj.toString());
Type typeResults = new TypeToken<DataObject>(){}.getType();
String json = gson.toJson(dObj, typeResults);
LOG.debug("db_json3.jsp - JSON: " + json);
return json;
}
catch (Throwable t) {
LOG.debug("db_json3.jsp - Error: " + t.toString());
return gson.toJson(t);
}
}
}
db_json dbjson = new db_json();
String json = dbjson.testJson();
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
%>

Search in ArrayList and count

In this code I want to search in an ArrayList but my code returns an incorrect result and I can not resolve this problem.
ReceivedItemStructure structure:
public class ReceivedItemStructure {
public String mLastID;
public String mUserID;
public String mSmsBody;
public String mMobileNumber;
public String mDate;
public String mSenderName;
public String mSmsNumber;
public String mContactName;
public String getmLastID() {
return mLastID;
}
}
My Code:
int countSMS = 0;
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
for (ReceivedItemStructure rf:items){
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
}
}
}
My problem is this line :
if( ! mId.equals(rf.getmLastID()) ) {
if mId = 2000 and rf.getmLastID() = 1000 then count must be ++
Loop through your list and do a contains or startswith.
ArrayList<String> resList = new ArrayList<String>();
String searchString = "man";
for (String curVal : list){
if (curVal.contains(searchString)){
resList.add(curVal);
}
}
You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.
Ok so to clarify please try to debug your code like this:
int countSMS = 0;
String TAG = "Debugger";
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
Log.i(TAG, "items size is " + items.size());
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
Log.i(TAG, "Trying to compare " + mId);
for (ReceivedItemStructure rf:items){
Log.i(TAG, "iteration step of " + rf.getmLastID);
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
Log.i(TAG, "they are equal, count is " + countSMS);
}
}
}

insert song to playlist returns null

I was trying to build a music player application , and I wanted to add a feature in order to add a song to a playlist.Here is the code:
public static void addToPlaylist(ContentResolver resolver,SongDetails songDetails,int playlistId) {
String[] cols = new String[] {
"count(*)"
};
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
Cursor cur = resolver.query(uri, cols, null, null, null);
cur.moveToFirst();
final int base = cur.getInt(0);
cur.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base + songDetails.getId()));
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songDetails.getId());
values.put(MediaStore.Audio.Playlists.Members.DISPLAY_NAME, songDetails.getSongTitle());
values.put(MediaStore.Audio.Playlists.Members.ARTIST, songDetails.getArtistName());
values.put(MediaStore.Audio.Playlists.Members.DATA, songDetails.getSongData());
Log.i("URI:",resolver.insert(uri, values)+"");
}
and in the logs I always get:
URI: null
which means that the song is not added to the playlist.Does anybody have any idea why the song is not added?
I've been using this method and it worked for me.
public static String addTracksToPlaylist(final long id, List<MediaData> tracks, final Context context) {
int count = getPlaylistSize(id, context);
ContentValues[] values = new ContentValues[tracks.size()];
for (int i = 0; i < tracks.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i + count + 1);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, tracks.get(i).getId());
}
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", id);
ContentResolver resolver = context.getContentResolver();
int num = resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
return String.format(context.getString(R.string.ADDED_TO_PLAYLIST), num, context.getString(R.string.CURRENT));
}
Retrieving tracks from playlist:
public static Cursor getTrackListFromPlaylist(Context context, long plid) {
String[] MEDIA_COLUMNS = new String[] {
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MINUTES + "||':'||" + SECONDS + " as " + FORMATTED_DURATION,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media._ID
};
return query(context, MediaStore.Audio.Playlists.Members.getContentUri("external", plid),
MEDIA_COLUMNS, null, null, MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);
}

Looking for a appropraite logic

Actually I am using call logs as an input to database and then I am fetching it in a way that I can't get any duplicate values while displaying it and if i have any duplicate value in data base then it should be taken as integer value count. For example: john(6).
Here john must have entry 6 times in database. Don't get me wrong. I don't need a code.I need help. Here is code:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls._ID));
Cursor callLogCursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, new String[]{
android.provider.CallLog.Calls.CACHED_NAME,
android.provider.CallLog.Calls.CACHED_NUMBER_LABEL,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.DATE,
android.provider.CallLog.Calls.DURATION,
android.provider.CallLog.Calls.TYPE
},android.provider.CallLog.Calls._ID + "=?", new String[] { rawContactId }, null);;
if (callLogCursor != null) {
while (callLogCursor.moveToNext()) {
//String id = callLogCursor.getString(0);
String name = callLogCursor.getString(0);
String cacheNumber = callLogCursor.getString(1);
String number = callLogCursor.getString(2);
long dateTimeMillis = callLogCursor.getLong(3);
long durationMillis = callLogCursor.getLong(4);
int callType = callLogCursor.getInt(5);
String duration = getDuration(durationMillis * 1000);
String dateString = getDateTime(dateTimeMillis);
if (cacheNumber == null)
cacheNumber = number;
if (name == null)
name = "Unknown";
Uri image = null;
try {
String conId = fetchContactIdFromPhoneNumber(cacheNumber);
long contId = Long.parseLong(conId);
image = getPhotoUri(contId);
}catch(Exception e) {
Log.e("Exception", e.getMessage());
}
//CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber,
// duration, dateString);
ContentValues values = new ContentValues();
values.put(NAME, name);
values.put(NUMBER, cacheNumber);
values.put(DATE, dateString);
values.put(DURATION,duration );
database.insert(CALL_LOG_TABLE, null, values);
Cursor cursor = database.query(CALL_LOG_TABLE, new String [] {LOG_ID, NAME, NUMBER, DATE, DURATION}, null, null, null, null, null);
int row =0;
if(!cursor.isAfterLast()) {
cursor.moveToFirst();
do{
int pId=cursor.getInt(0);
String pName = cursor.getString(1);
String pNumber = cursor.getString(2);
String pDate = cursor.getString(3);
String pDuration = cursor.getString(4);
int value = 0;
CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber, duration, dateString);
if (callType == CallLog.Calls.OUTGOING_TYPE) {
for(int i=0;i<outgoingList.size();i++){
------------------------------Actually i want Logic here what should i do here--------------
}
}
outgoingList.add(callLogModel);
} else if (callType == CallLog.Calls.INCOMING_TYPE) {
incomingList.add(callLogModel);
} else if (callType == CallLog.Calls.MISSED_TYPE) {
missedcallList.add(callLogModel);
}
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
}
callLogCursor.close();
}
}
You could model the outgoing calls in a hashmap, something like:
Map<String, Integer> outgoingCallsMap = new HashMap<String, Integer>();
for (int i = 0; i < outgoingList.size(); i++) {
String nameOfCallee = outgoingList.get(i);
if (!outgoingCallsMap.containsKey(nameOfCallee)) {
outgoingCallsMap.put(nameOfCallee, 1);
} else {
//Increment calls to this person
outgoingCallsMap.put(nameOfCallee, outgoingCallsMap.get(nameOfCallee) + 1);
}
}
Remove the duplicates in your outGoingList, by iterating it and putting the result to a map, with contact name as key and list of CallLogModel object as value.
You can refer this method.
private void convertToOutGoingMap(List<CallLogModel > outGoingList) {
HashMap<String,List<CallLogModel>> outGoingMap = new HashMap<String, List<CallLogModel>>();//map which has CallLogModel.name as key and List<CallLogModel> as value.
for(CallLogModel model : outGoingList){//Iterate thru the list.
if(outGoingMap.containsKey(model.name))
{
outGoingMap.get(model.name).add(model);//if map contains key, add model to the list.
} else {
List<CallLogModel> modelList = new ArrayList<CallLogModel>();//if it does not contains, initialize a list and add model to it.
modelList.add(model);
outGoingMap.put(model.name, modelList);
}
}
}
}
The key set of this map gives you the unique call log names and corresponding value list gives all occurrences and its size gives you number of occurrences.
Hope this help you.

Categories