How do the retrieve the date of the mms from content://mms. - android

I did get the information on how to retrieve the text and the image for the mms sent from this link: How to Read MMS Data in Android?.
But I am not sure how to retrieve the date for the mms that was sent.
I know I have to look into content://mms and not in content://mms/part.
This is the Mothod to retrieve the mms text:
private String getMmsText(String id) {
Uri partURI = Uri.parse("content://mms/part/" + id);
InputStream is = null;
StringBuilder sb = new StringBuilder();
try {
is = getContentResolver().openInputStream(partURI);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String temp = reader.readLine();
while (temp != null) {
sb.append(temp);
temp = reader.readLine();
}
}
} catch (IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
and then, in the onCreate method, I use this code to get the info:
Cursor cursor = getContentResolver().query(uri, null, selectionPart,
null, null);
if (cursor.moveToFirst()) {
do {
String partId = cursor.getString(cursor.getColumnIndex("_id"));
String type = cursor.getString(cursor.getColumnIndex("ct"));
if ("text/plain".equals(type)) {
String data = cursor.getString(cursor
.getColumnIndex("_data"));
if (data != null) {
// implementation of this method above
body = getMmsText(partId);
} else {
body = cursor.getString(cursor.getColumnIndex("text"));
}
}
} while (cursor.moveToNext());
}
try {
main.setText(body);
img.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
I just want to know where can I make changes to get the date value.
Some info will be really helpful.

I'm not overly familiar with MMS's, but I'd imagine something like this would at least get you started
Cursor cursor = activity.getContentResolver().query(Uri.parse("content://mms"),null,null,null,date DESC);
count = cursor.getCount();
if (count > 0)
{
cursor.moveToFirst();
long timestamp = cursor.getLong(2);
Date date = new Date(timestamp);
String subject = cursor.getString(3);
}
It's completely untested of course, but should point you in the right direction. Hope this helps!
Edit
After doing a bit of reading, there used to be (possibly still is) a "bug" with the timestamp in MMS messages, when retrieving the data. If you end up with a silly value (like the epoch), you'll have to * 1000 before using it. Just an aside :) I.e.:
long timestamp = (cursor.getLong(2) * 1000);

Related

Loading Artists from Android MediaStore along with Artwork

I am aware that media artwork is stored under albums and to get them you need to have the album id to access it. I have been able to get the images for tracks and albums using the album id.
However for artists table doesn't have the album id field. Other apps such as Play Music and Poweramp are somehow able to get the track artwork and add them to the respective artists.
How do i achieve this?
The way I do it is to get all albums for an artist and then use the rnd function to return an albumid:
String artist_id = c.getString(c.getColumnIndex(MediaStore.Audio.Artists._ID));
Cursor crs = album.getArtistsAlbumcursor(mContext, artist_id);
if(crs!=null && crs.moveToFirst()) {
Random rn = new Random();
int rnd = rn.nextInt( crs.getCount());
crs.moveToPosition(rnd);
album_id = crs.getLong(crs.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
crs.close();
}
where getArtistsAlbumcursor is:
public Cursor getArtistsAlbumcursor(Context context, String artistId) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String artistid = MediaStore.Audio.Media.ARTIST_ID;
final String[] columns = { _id, album_id, artistid };
String where = artistid +" =?";
String[] aId = {artistId};
return cr.query(uri, columns, where, aId, null);
}
Once you have an albumid you can get your albumart using your original method.
Or
if you want to get the albumart from the mp3 track itself, you will need to implement a libary such as jaudiotagger or org.blinkenlights.jid3.v2.
Life gets a little more complicated but below how to get albumart from the mp3 tag using the JID3 library:
try {
bmp = getmp3AlbumArt(sourceFile);
} catch (Exception e) {
e.printStackTrace();
}
where getmp3Albumart is:
public Bitmap getmp3AlbumArt(File SourceFile) throws Exception {
Bitmap bmp = null;
arrayByte = null;
APICID3V2Frame frames[];
MediaFile MediaFile = new MP3File(SourceFile);
try {
Object obj = null;
obj = MediaFile.getID3V2Tag();
if (obj != null) {
tagImage = (org.blinkenlights.jid3.v2.ID3V2_3_0Tag) obj;
if ((tagImage != null) && (arrayByte == null) && (tagImage.getAPICFrames() != null) && (tagImage.getAPICFrames().length > 0)) {
frames = tagImage.getAPICFrames();
for (int i = 0; i < tagImage.getAPICFrames().length; i++) {
if (frames[i] != null) {
arrayByte = frames[i].getPictureData();
break;
}
}
}
}
} catch (ID3Exception | OutOfMemoryError e) {
e.printStackTrace();
}
if (arrayByte != null) {
try {
bmp = BitmapFactory.decodeByteArray(arrayByte, 0, arrayByte.length);
} catch (Exception|OutOfMemoryError e) {
e.printStackTrace();
}
}
return bmp;
}

Android SQL Lite query very slow

I have developed a this function for search all element in a 20 km range respect position of single element into
ArrayList<GeoJsonResponse> result = new ArrayList<GeoJsonResponse>();
Cursor cursor = mDb.query(database_event_schema.TABLE_NAME, null, null, null, null, null, null);
String[] colums = new String[]{database_event_schema._EVENT_ID,database_event_schema._AUTHOR, database_event_schema._LAT,database_event_schema._LON,database_event_schema._PLACE,database_event_schema._MAG,database_event_schema._DEPTH,database_event_schema._TIME};
Double lat,lon,magnitude = null,distance = null;
if (cursor != null) {
while (cursor.moveToNext()) {
try{lat = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._LAT)));}catch(Exception e){continue;}
try{lon = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._LON)));}catch(Exception e){continue;}
String place = cursor.getString(cursor.getColumnIndex(database_event_schema._PLACE));
double dist_km = Utills.distance(curPos.latitude,curPos.longitude,lat,lon,'K');
if(dist_km>=0 && dist_km<=10) {
String id = cursor.getString(cursor.getColumnIndex(database_event_schema._EVENT_ID));
String author = cursor.getString(cursor.getColumnIndex(database_event_schema._AUTHOR));
try{magnitude = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._MAG)));}catch(Exception e){}
try{distance = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._DEPTH)));}catch(Exception e){}
String date = cursor.getString(cursor.getColumnIndex(database_event_schema._TIME));
Date dateNew = null;
if(!date.equals(""))
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
dateNew = format.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("test", e.getLocalizedMessage());
}
}
result.add(new GeoJsonResponse(id,author,place,magnitude,distance,date,dateNew,lat,lon));
}
}
}
return result;
but the query is very slow. How can I increase the speed query?
By this table the query select all element with a location with 20km respect the event selected. The table have 500.000 record whitout index.
The result are show into a list
I have write a wrong code?
Thanks
You should create a SQLite distance function in C (so the distance calculation will be faster) and use it as a filter in your query to limit the results.
See an example (for iOS): http://www.thismuchiknow.co.uk/?p=71

Parsing XML error, arrayindexoutofbounds exception.

I'm trying to parse some XML to a string and I'm getting an outofbounds exception. I'm fairly new to android as well as trying to get text from a website, namely the CTA Bus Tracker API . One block of the XML looks like this:
<route>
<rt>1</rt>
<rtnm>Bronzeville/Union Station</rtnm>
</route>
This is my method:
class loadRoutes extends AsyncTask<String, String, String[]> {
#Override
protected String[] doInBackground(String... strings) {
try {
URL routesURL = new URL(strings[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(routesURL.openStream()));
String [] result = new String[2];
String line;
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
in.readLine();
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
in.close();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
The first readline() gets to the line with an rt and grabs that line, then in the if statement, readline() should get the next line, which should contain rtnm. I keep getting indexoutofbounds on the line firstPos = line.indexOf("rtnm").
The while loop is already reading in the next line, so you don't need to in.readLine(); in the if statement. Try running it like this:
while((line = in.readLine()) != null) {
if(line.contains("<rt>")) {
int firstPos = line.indexOf("<rt>");
String tempNum = line.substring(firstPos);
tempNum = tempNum.replace("<rt>", "");
int lastPos = tempNum.indexOf("</rt>");
result[0] = tempNum.substring(0, lastPos);
} else if (line.contains("<rtnm>") {
firstPos = line.indexOf("<rtnm>");
String tempName = line.substring(firstPos);
tempName = tempName.replace("<rtnm>", "");
lastPos = tempName.indexOf("</rtnm>");
result[1] = tempName.substring(0, lastPos);
}
}
Also, it might be easier to write your own XML parser in a different class. This XML parser android documentation has an example of exactly what you are trying to do.

How to read whole chapter from epub files?

I want to make epub reader app.Now i am getting only chapter name in the file but how to get whole data in the chapter.
I think I have already posted this out before.
Using nl.siegmann.epublib which you can google.
In my code I will show you how I did it as you look at Book class which shows how the the epub works.
Using Spine on book class I get the maximum spine of the book which means the entire book.
I then convert it to string.
Here is my code on how I did it.
public String getEntireBook()
{
String line, linez = null;
Spine spine = amBook().getSpine();
Resource res;
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
int start = 0;
StringBuilder string = new StringBuilder();
for (int i = start; count > i; i = i +1) {
res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
return linez;
}

Fail to split downloaded txt file

I have a String that I try to split. The following code works
lsSagor = "some text\n Some more text\n More text~Text again\n Text\n text~Some text ..."
final String[] laList = lsSagor.split("~");
String[] laSaga = laList[0].split("\n");
Gives:
laSaga[0] => some text
laSaga[1] => some more text
laSaga[2] => More text
But if I download the textfile, it fails to split and gives:
laSaga[0] => "some text\n Some more text\n More text"
So it seems the first split works, but not the second.
Here is the code I use to download the file
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
//handle the exception !
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
From the documentation
I don't think you will find your string contains any newline character to split on, you would need to do
while ((line = rd.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
to get that and I'm sure there is an easier way to just read it newlines and all in the first place.
Hi I think the problem is in String.split() function
Old method but work :)
public static String[] splitString(String str, char separator)
{
String[] retVal = null;
int length = str.length();
int size = 1;
int jIndx = 0;
int expressionLength = 0;
while ((jIndx = str.indexOf(separator, jIndx + 1)) != -1)
{
size++;
}
retVal = new String[size];
jIndx = 0;
char[] charArray = str.toCharArray() ;
for (int index = 0; index < length; index++)
{
if (charArray[index] == separator)
{
retVal[jIndx] = str.substring(index - expressionLength, index);
jIndx++;
expressionLength = 0;
}
else
expressionLength++;
if (index + 1 == length)
{
retVal[jIndx] = str.substring(index + 1 - expressionLength, index + 1);
}
}
return retVal;
}
This is the (not so beautiful) solution
lsSagor = "some text# Some more text# More text~Text again\n Text# text~Some text ..."
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
guiLaList is used for layout with "\n" and the other list laList to get the information I wanted.

Categories

Resources