writting class object in a file in extarnal storage - android

at first, i am using Nexus 7 as my testing device.
i want to save a class object with its all variables current value in a file and want to save the file in such place so that, after reboot of the phone (assuming that the phone is shutted down by the user) , i can get the object from the file and can use the data (which are saved in the variables in the saved object class) for my further use. where should i save my file (with the object) such that, it will work for most of the devices.
here is my code(writting a class object in a file in extarnal storage):
File file = new File(Environment.getExternalStorageDirectory(), "savedData");
if(!file.exists()){
file.createNewFile();
Toast.makeText(getActivity(), "not exist", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(), "exist", Toast.LENGTH_LONG).show();
}
if(file.canWrite())
Toast.makeText(getActivity(), "writable", Toast.LENGTH_LONG).show();
else
Toast.makeText(getActivity(), "not writable", Toast.LENGTH_LONG).show();
FileOutputStream fos = new FileOutputStream(file);
String car = "ferrari";
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(app);
os.writeObject(car);
os.close();
here is my code(reading the class object from the file from extarnal storage):
File file = new File(Environment.getExternalStorageDirectory(), "savedData");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream is = new ObjectInputStream(fis);
savedData = (SavedFriend) is.readObject();
String car = (String) is.readObject();
Toast.makeText(getApplicationContext(), car, Toast.LENGTH_LONG).show();
is.close();
i have written object in one class and read it from another class. as you can see, i have written a string (car) as object for test purpose and the class object. i have read them in another class. now the value of class object and string (car) are showing perfectly. that means they are written well in the file in external storage. but when i shut down my Nexux 7 (for testing the app) and run the app again, the value of string (car) is showing perfectly, but the values of the variables from the class object are showing null. what is the problem?
in my manifest i have added:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
by the way, the class's object i want to write as object implements Serializable .... even, i have implements Serializable for all classes for test . but it is not working.
i cannot use Database or other storage technique, because i have came a long way with this app so if i use other technique, i have to change most of my code. please help.
is it possible to write the object in phone's internal memeory? i have also write the file using getActivity().getApplicationContext().openFileOut() before. but i fetch the same problem with that approach.
Edited:
SavedFriend Class:
public class SavedFriend extends Application implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static List<GraphUser> selectedUsers;
private static String friendsId;
private static Session session;
private static Bundle bundle;
private static Context context;
private static long time;
private static int year, month, date, hour, min;
//private Activity activity;
//dynamic
private static String[] pmsg = new String[5];
private static String[] smsg = new String[5];
private static String[] fmsg = new String[5];
private static long[] ptime = new long[5];
private static long[] stime = new long[5];
private static long[] ftime = new long[5];
private static int[] pyear = new int[5];
private static int[] syear = new int[5];
private static int[] fyear = new int[5];
private static int[] pmonth = new int[5];
private static int[] smonth = new int[5];
private static int[] fmonth = new int[5];
private static int[] pdate = new int[5];
private static int[] sdate = new int[5];
private static int[] fdate = new int[5];
private static int[] phour = new int[5];
private static int[] shour = new int[5];
private static int[] fhour = new int[5];
private static int[] pmin = new int[5];
private static int[] smin = new int[5];
private static int[] fmin = new int[5];
private static String[] pfriendName = new String[5];
private static String[] sfriendName = new String[5];
private static String[] ffriendName = new String[5];
private static String[] pfriendId = new String[5];
private static String[] sfriendId = new String[5];
private static String[] ffriendId = new String[5];
private static String[] pDateTime = new String[5];
private static String[] sDateTime = new String[5];
private static String[] fDateTime = new String[5];
private static int pmaster_key = -1;
private static int smaster_key = -1;
private static int fmaster_key = -1;
public void setYear(int year){
SavedFriend.year = year;
}
public void setMonth(int month){
SavedFriend.month = month;
}
public void setDate(int date){
SavedFriend.date = date;
}
public void setHour(int hour){
SavedFriend.hour = hour;
}
public void setMin(int min){
SavedFriend.min = min;
}
public static int getYear (){
return year;
}
public static int getMonth (){
return month;
}
public static int getDate (){
return date;
}
public static int getHour (){
return hour;
}
public static int getMin (){
return min;
}
public static List<GraphUser> getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(List<GraphUser> selectedUsers) {
SavedFriend.selectedUsers = selectedUsers;
}
public static String getfriendsId() {
return friendsId;
}
public void setfriendsId(String id) {
SavedFriend.friendsId = id;
}
public static Session getSession(){
return session;
}
public void setSession(Session session){
this.session = session;
}
public void setContext(Context context){
this.context = context;
}
public static Context getContext(){
return context;
}
/*public void setActivity(Activity activity){
this.activity = activity;
}
public Activity getActivity(){
return activity;
}*/
public void setBundle(Bundle bundle){
SavedFriend.bundle = bundle;
}
public Bundle getBundle(){
return bundle;
}
public void setPmsg(String Pmsg, long Ptime, String Pfriendname, String Pfriendid,
int year, int month, int date, int hour, int min){
Log.e("key before inc",Integer.toString(pmaster_key));
pmaster_key++;
Log.e("key after inc",Integer.toString(pmaster_key));
if(pmaster_key == 0){
pmsg[pmaster_key] = Pmsg;
ptime[pmaster_key] = Ptime;
pfriendName[pmaster_key] = Pfriendname;
pfriendId[pmaster_key] = Pfriendid;
pyear[pmaster_key] = year;
pmonth[pmaster_key] = month;
pdate[pmaster_key] = date;
phour[pmaster_key] = hour;
pmin[pmaster_key] = min;
Log.e("first entry", pmsg[pmaster_key]);
//write();
}else{
boolean check = false;
for(int i=0; i<pmaster_key; i++){
if(ptime[i] < Ptime){
long temp1 = 0;
String temp2 = null;
String temp3 = null;
String temp4 = null;
int temp5 = 0;
int temp6 = 0;
int temp7 = 0;
int temp8 = 0;
int temp9 = 0;
for(int j=i; j<=pmaster_key; j++){
if(j<pmaster_key){
temp1 = ptime[j];
temp2 = pmsg[j];
temp3 = pfriendName[j];
temp4 = pfriendId[j];
temp5 = pyear[j];
temp6 = pmonth[j];
temp7 = pdate[j];
temp8 = phour[j];
temp9 = pmin[j];
}
pmsg[j] = Pmsg;
ptime[j] = Ptime;
pfriendName[j] = Pfriendname;
pfriendId[j] = Pfriendid;
pyear[j] = year;
pmonth[j] = month;
pdate[j] = date;
phour[j] = hour;
pmin[j] = min;
if(j<pmaster_key){
Pmsg = temp2;
Ptime = temp1;
Pfriendname = temp3;
Pfriendid = temp4;
year = temp5;
month = temp6;
date = temp7;
hour = temp8;
min = temp9;
}
Log.e("sorted entry", pmsg[j]);
Log.e("key & j",Integer.toString(pmaster_key)+", "+Integer.toString(j));
check = true;
}
}
if(check){
Log.e("sorted entry after loop", pmsg[pmaster_key]);
break;
}
}
if(!check){
pmsg[pmaster_key] = Pmsg;
ptime[pmaster_key] = Ptime;
pfriendName[pmaster_key] = Pfriendname;
pfriendId[pmaster_key] = Pfriendid;
pyear[pmaster_key] = year;
pmonth[pmaster_key] = month;
pdate[pmaster_key] = date;
phour[pmaster_key] = hour;
pmin[pmaster_key] = min;
Log.e("sorted entry last pos", pmsg[pmaster_key]);
}
//write();
}
}
public void setSmsg(){
smaster_key++;
if(smaster_key>5)
smaster_key = 0;
smsg[smaster_key] = pmsg[pmaster_key];
stime[smaster_key] = ptime[pmaster_key];
sfriendName[smaster_key] = pfriendName[pmaster_key];
sfriendId[smaster_key] = pfriendId[pmaster_key];
syear[smaster_key] = pyear[pmaster_key];
smonth[smaster_key] = pmonth[pmaster_key];
sdate[smaster_key] = pdate[pmaster_key];
shour[smaster_key] = phour[pmaster_key];
smin[smaster_key] = pmin[pmaster_key];
Log.e("one entry deleted", pmsg[pmaster_key]);
pmaster_key--;
}
public void setFmsg(){
fmaster_key++;
if(fmaster_key>5)
fmaster_key = 0;
fmsg[fmaster_key] = pmsg[pmaster_key];
ftime[fmaster_key] = ptime[pmaster_key];
ffriendName[fmaster_key] = pfriendName[pmaster_key];
ffriendId[fmaster_key] = pfriendId[pmaster_key];
fyear[fmaster_key] = pyear[pmaster_key];
fmonth[fmaster_key] = pmonth[pmaster_key];
fdate[fmaster_key] = pdate[pmaster_key];
fhour[fmaster_key] = phour[pmaster_key];
fmin[fmaster_key] = pmin[pmaster_key];
pmaster_key--;
}
public static int[] getPyear(){
return pyear;
}
public static int[] getPmonth(){
return pmonth;
}
public static int[] getPdate(){
return pdate;
}
public static int[] getPhour(){
return phour;
}
public static int[] getPmin(){
return pmin;
}
public static int[] getSyear(){
return syear;
}
public static int[] getSmonth(){
return smonth;
}
public static int[] getSdate(){
return sdate;
}
public static int[] getShour(){
return shour;
}
public static int[] getSmin(){
return smin;
}
public static int[] getFyear(){
return fyear;
}
public static int[] getFmonth(){
return fmonth;
}
public static int[] getFdate(){
return fdate;
}
public static int[] getFhour(){
return fhour;
}
public static int[] getFmin(){
return fmin;
}
public static int getPmaster_key(){
return pmaster_key;
}
public static int getSmaster_key(){
return smaster_key;
}
public static int getFmaster_key(){
return fmaster_key;
}
public static String[] getPmsg(){
return pmsg;
}
public static String[] getSmsg(){
return smsg;
}
public static String[] getFmsg(){
return fmsg;
}
public static long[] getPtime(){
return ptime;
}
public static long[] getStime(){
return stime;
}
public static long[] getFtime(){
return ftime;
}
public static String[] getPfriendname(){
return pfriendName;
}
public static String[] getSfriendname(){
return sfriendName;
}
public static String[] getFfriendname(){
return ffriendName;
}
public static String[] getPfriendid(){
return pfriendId;
}
public static String[] getSfriendid(){
return sfriendId;
}
public static String[] getFfriendid(){
return ffriendId;
}
public static String[] getPdateTime(){
return pDateTime;
}
public static String[] getSdateTime(){
return sDateTime;
}
public static String[] getFdateTime(){
return fDateTime;
}
public void setTime(long time){
SavedFriend.time = time;
}
public static long getTime(){
return time;
}
public void Delete(int position){
if(position == pmaster_key){
pmaster_key--;
}else{
for(int i=position; i<pmaster_key; i++){
pmsg[i] = pmsg[i+1];
ptime[i] = ptime[i+1];
pfriendName[i] = pfriendName[i+1];
pfriendId[i] = pfriendId[i+1];
pyear[i] = pyear[i+1];
pmonth[i] = pmonth[i+1];
pdate[i] = pdate[i+1];
phour[i] = phour[i+1];
pmin[i] = pmin[i+1];
}
pmaster_key--;
}
}
public void Edit(int position, String Nmsg, long Ntime, String NfriendName, String NfriendId,
int Nyear, int Nmonth, int Ndate, int Nhour, int Nmin){
pmsg[position] = Nmsg;
ptime[position] = Ntime;
pfriendName[position] = NfriendName;
pfriendId[position] = NfriendId;
pyear[position] = Nyear;
pmonth[position] = Nmonth;
pdate[position] = Ndate;
phour[position] = Nhour;
pmin[position] = Nmin;
}
public void writeNow (){
try {
File file = new File(Environment.getExternalStorageDirectory(), "savedData");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(new SavedFriend());
os.close();
} catch (Exception e) {
Toast.makeText(context, "Unknown error", Toast.LENGTH_LONG).show();
}
}
}

The fields in the SavedFriend class should not be static. static fields are not written during serialization.

Related

How do I display a list of all MIME types supported by a given Android device?

I'm trying to displaying a device supported format programmatically. i have found this on the internet. the question is, how to display those ? please help me, im newbie in Android development.
Here is the code for checking file format of the device.
package com.android.mmscommon;
import java.util.ArrayList;
public class ContentType {
public static final String MMS_MESSAGE = "application/vnd.wap.mms-message";
// The phony content type for generic PDUs (e.g. ReadOrig.ind,
// Notification.ind, Delivery.ind).
public static final String MMS_GENERIC = "application/vnd.wap.mms-generic";
public static final String MULTIPART_MIXED = "application/vnd.wap.multipart.mixed";
public static final String MULTIPART_RELATED = "application/vnd.wap.multipart.related";
public static final String MULTIPART_ALTERNATIVE = "application/vnd.wap.multipart.alternative";
public static final String TEXT_PLAIN = "text/plain";
public static final String TEXT_HTML = "text/html";
public static final String TEXT_VCALENDAR = "text/x-vCalendar";
public static final String TEXT_VCARD = "text/x-vCard";
public static final String IMAGE_UNSPECIFIED = "image/*";
public static final String IMAGE_JPEG = "image/jpeg";
public static final String IMAGE_JPG = "image/jpg";
public static final String IMAGE_GIF = "image/gif";
public static final String IMAGE_WBMP = "image/vnd.wap.wbmp";
public static final String IMAGE_PNG = "image/png";
public static final String AUDIO_UNSPECIFIED = "audio/*";
public static final String AUDIO_AAC = "audio/aac";
public static final String AUDIO_AMR = "audio/amr";
public static final String AUDIO_IMELODY = "audio/imelody";
public static final String AUDIO_MID = "audio/mid";
public static final String AUDIO_MIDI = "audio/midi";
public static final String AUDIO_MP3 = "audio/mp3";
public static final String AUDIO_MPEG3 = "audio/mpeg3";
public static final String AUDIO_MPEG = "audio/mpeg";
public static final String AUDIO_MPG = "audio/mpg";
public static final String AUDIO_MP4 = "audio/mp4";
public static final String AUDIO_X_MID = "audio/x-mid";
public static final String AUDIO_X_MIDI = "audio/x-midi";
public static final String AUDIO_X_MP3 = "audio/x-mp3";
public static final String AUDIO_X_MPEG3 = "audio/x-mpeg3";
public static final String AUDIO_X_MPEG = "audio/x-mpeg";
public static final String AUDIO_X_MPG = "audio/x-mpg";
public static final String AUDIO_3GPP = "audio/3gpp";
public static final String AUDIO_OGG = "application/ogg";
public static final String VIDEO_UNSPECIFIED = "video/*";
public static final String VIDEO_3GPP = "video/3gpp";
public static final String VIDEO_3G2 = "video/3gpp2";
public static final String VIDEO_H263 = "video/h263";
public static final String VIDEO_MP4 = "video/mp4";
public static final String APP_SMIL = "application/smil";
public static final String APP_WAP_XHTML = "application/vnd.wap.xhtml+xml";
public static final String APP_XHTML = "application/xhtml+xml";
public static final String APP_DRM_CONTENT = "application/vnd.oma.drm.content";
public static final String APP_DRM_MESSAGE = "application/vnd.oma.drm.message";
private static final ArrayList<String> sSupportedContentTypes = new ArrayList<String>();
private static final ArrayList<String> sSupportedImageTypes = new ArrayList<String>();
private static final ArrayList<String> sSupportedAudioTypes = new ArrayList<String>();
private static final ArrayList<String> sSupportedVideoTypes = new ArrayList<String>();
static {
sSupportedContentTypes.add(TEXT_PLAIN);
sSupportedContentTypes.add(TEXT_HTML);
sSupportedContentTypes.add(TEXT_VCALENDAR);
sSupportedContentTypes.add(TEXT_VCARD);
sSupportedContentTypes.add(IMAGE_JPEG);
sSupportedContentTypes.add(IMAGE_GIF);
sSupportedContentTypes.add(IMAGE_WBMP);
sSupportedContentTypes.add(IMAGE_PNG);
sSupportedContentTypes.add(IMAGE_JPG);
//supportedContentTypes.add(IMAGE_SVG); not yet supported.
sSupportedContentTypes.add(AUDIO_AAC);
sSupportedContentTypes.add(AUDIO_AMR);
sSupportedContentTypes.add(AUDIO_IMELODY);
sSupportedContentTypes.add(AUDIO_MID);
sSupportedContentTypes.add(AUDIO_MIDI);
sSupportedContentTypes.add(AUDIO_MP3);
sSupportedContentTypes.add(AUDIO_MPEG3);
sSupportedContentTypes.add(AUDIO_MPEG);
sSupportedContentTypes.add(AUDIO_MPG);
sSupportedContentTypes.add(AUDIO_X_MID);
sSupportedContentTypes.add(AUDIO_X_MIDI);
sSupportedContentTypes.add(AUDIO_X_MP3);
sSupportedContentTypes.add(AUDIO_X_MPEG3);
sSupportedContentTypes.add(AUDIO_X_MPEG);
sSupportedContentTypes.add(AUDIO_X_MPG);
sSupportedContentTypes.add(AUDIO_3GPP);
sSupportedContentTypes.add(AUDIO_OGG);
sSupportedContentTypes.add(VIDEO_3GPP);
sSupportedContentTypes.add(VIDEO_3G2);
sSupportedContentTypes.add(VIDEO_H263);
sSupportedContentTypes.add(VIDEO_MP4);
sSupportedContentTypes.add(APP_SMIL);
sSupportedContentTypes.add(APP_WAP_XHTML);
sSupportedContentTypes.add(APP_XHTML);
sSupportedContentTypes.add(APP_DRM_CONTENT);
sSupportedContentTypes.add(APP_DRM_MESSAGE);
// add supported image types
sSupportedImageTypes.add(IMAGE_JPEG);
sSupportedImageTypes.add(IMAGE_GIF);
sSupportedImageTypes.add(IMAGE_WBMP);
sSupportedImageTypes.add(IMAGE_PNG);
sSupportedImageTypes.add(IMAGE_JPG);
// add supported audio types
sSupportedAudioTypes.add(AUDIO_AAC);
sSupportedAudioTypes.add(AUDIO_AMR);
sSupportedAudioTypes.add(AUDIO_IMELODY);
sSupportedAudioTypes.add(AUDIO_MID);
sSupportedAudioTypes.add(AUDIO_MIDI);
sSupportedAudioTypes.add(AUDIO_MP3);
sSupportedAudioTypes.add(AUDIO_MPEG3);
sSupportedAudioTypes.add(AUDIO_MPEG);
sSupportedAudioTypes.add(AUDIO_MPG);
sSupportedAudioTypes.add(AUDIO_MP4);
sSupportedAudioTypes.add(AUDIO_X_MID);
sSupportedAudioTypes.add(AUDIO_X_MIDI);
sSupportedAudioTypes.add(AUDIO_X_MP3);
sSupportedAudioTypes.add(AUDIO_X_MPEG3);
sSupportedAudioTypes.add(AUDIO_X_MPEG);
sSupportedAudioTypes.add(AUDIO_X_MPG);
sSupportedAudioTypes.add(AUDIO_3GPP);
sSupportedAudioTypes.add(AUDIO_OGG);
// add supported video types
sSupportedVideoTypes.add(VIDEO_3GPP);
sSupportedVideoTypes.add(VIDEO_3G2);
sSupportedVideoTypes.add(VIDEO_H263);
sSupportedVideoTypes.add(VIDEO_MP4);
}
// This class should never be instantiated.
private ContentType() {
}
public static boolean isSupportedType(String contentType) {
return (null != contentType) && sSupportedContentTypes.contains(contentType);
}
public static boolean isSupportedImageType(String contentType) {
return isImageType(contentType) && isSupportedType(contentType);
}
public static boolean isSupportedAudioType(String contentType) {
return isAudioType(contentType) && isSupportedType(contentType);
}
public static boolean isSupportedVideoType(String contentType) {
return isVideoType(contentType) && isSupportedType(contentType);
}
public static boolean isTextType(String contentType) {
return (null != contentType) && contentType.startsWith("text/");
}
public static boolean isImageType(String contentType) {
return (null != contentType) && contentType.startsWith("image/");
}
public static boolean isAudioType(String contentType) {
return (null != contentType) && contentType.startsWith("audio/");
}
public static boolean isVideoType(String contentType) {
return (null != contentType) && contentType.startsWith("video/");
}
public static boolean isDrmType(String contentType) {
return (null != contentType)
&& (contentType.equals(APP_DRM_CONTENT)
|| contentType.equals(APP_DRM_MESSAGE));
}
public static boolean isUnspecified(String contentType) {
return (null != contentType) && contentType.endsWith("*");
}
#SuppressWarnings("unchecked")
public static ArrayList<String> getImageTypes() {
return (ArrayList<String>) sSupportedImageTypes.clone();
}
#SuppressWarnings("unchecked")
public static ArrayList<String> getAudioTypes() {
return (ArrayList<String>) sSupportedAudioTypes.clone();
}
#SuppressWarnings("unchecked")
public static ArrayList<String> getVideoTypes() {
return (ArrayList<String>) sSupportedVideoTypes.clone();
}
#SuppressWarnings("unchecked")
public static ArrayList<String> getSupportedTypes() {
return (ArrayList<String>) sSupportedContentTypes.clone();
}
}
Here is the full list : https://www.iana.org/assignments/media-types/media-types.xhtml
It is referenced in the android documentation here: https://developer.android.com/guide/topics/providers/content-provider-creating.html#MIMETypes
Note that these MIME types are supported only if the user has the appropriate app for it. I don't think that you can display the supported MIME types programmatically. However you can check if the one that you want to use is supported using code like this :
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(someUri, "YOUR_MIME_TYPE_HERE");
if(intent.resolveActivity(activity.getPackageManager()) != null)
{
lActivity.startActivity(intent);
}
else
{
Log.w(TAG, "There is no application for this MIME type");
}

Time displayed on Android app is 1-hour ahead

I have an Android app that uses a backend web service to send and receive messages between devices.
Problem: The message time displayed in the app's Inbox and Sent box is 1-hour ahead (e.g. if the real time is 8:00am, the app shows 9:00am) Please help. Here is my code:
private static class DateTime {
static final char HOUR_OF_DAY_0 = 'H'; // (00 - 23)
static final char HOUR_0 = 'I'; // (01 - 12)
static final char HOUR_OF_DAY = 'k'; // (0 - 23) -- like H
static final char HOUR = 'l'; // (1 - 12) -- like I
static final char MINUTE = 'M'; // (00 - 59)
static final char NANOSECOND = 'N'; // (000000000 - 999999999)
static final char MILLISECOND = 'L'; // jdk, not in gnu (000 - 999)
static final char MILLISECOND_SINCE_EPOCH = 'Q'; // (0 - 99...?)
static final char AM_PM = 'p'; // (am or pm)
static final char SECONDS_SINCE_EPOCH = 's'; // (0 - 99...?)
static final char SECOND = 'S'; // (00 - 60 - leap second)
static final char TIME = 'T'; // (24 hour hh:mm:ss)
static final char ZONE_NUMERIC = 'z'; // (-1200 - +1200) - ls minus?
static final char ZONE = 'Z'; // (symbol)
// Composites
static final char TIME_12_HOUR = 'r'; // (hh:mm:ss [AP]M)
static final char TIME_24_HOUR = 'R'; // (hh:mm same as %H:%M)
// * static final char LOCALE_TIME = 'X'; // (%H:%M:%S) - parse format?
static final char DATE_TIME = 'c';
// (Sat Nov 04 12:02:33 EST 1999)
static final char DATE = 'D'; // (mm/dd/yy)
static final char ISO_STANDARD_DATE = 'F'; // (%Y-%m-%d)
// * static final char LOCALE_DATE = 'x'; // (mm/dd/yy)
More info:
public class Inbox {
private String messageID;
private String from;
private List<String> to;
private String subject;
private String voice_file;
private String datetime;
private String is_read;
public String getMessageID(){
return messageID;
}
public void setMessageID(String messageID){
this.messageID= messageID;
}
public String getFrom(){
return from;
}
public void setFrom(String from){
this.from= from;
}
public String getSubject(){
return subject;
}
public void setSubject(String subject){
this.subject= subject;
}
public String getVoiceFile(){
return voice_file;
}
public void setVoiceFile(String voice_file){
this.voice_file= voice_file;
}
public String getDateTime(){
return datetime;
}
public void setDateTime(String datetime){
this.datetime= datetime;
}
public List<String> getTo(){
return this.to;
}
public void setTo(List<String> to){
this.to= to;
}
public String getIsRead(){
return is_read;
}
public void setIsRead(String is_read){
this.is_read= is_read;
}
}
public class Sentbox {
private String messageID;
private String from;
private List<String> toName;
private List<String> to;
private String subject;
private String voice_file;
private String datetime;
public String getMessageID(){
return messageID;
}
public void setMessageID(String messageID){
this.messageID= messageID;
}
public String getFrom(){
return from;
}
public void setFrom(String from){
this.from= from;
}
public String getSubject(){
return subject;
}
public void setSubject(String subject){
this.subject= subject;
}
public String getVoiceFile(){
return voice_file;
}
public void setVoiceFile(String voice_file){
this.voice_file= voice_file;
}
public String getDateTime(){
return datetime;
}
public void setDateTime(String datetime){
this.datetime= datetime;
}
public List<String> getTo(){
return this.to;
}
public void setTo(List<String> to){
this.to= to;
}
public List<String> getToName(){
return this.toName;
}
public void setToName(List<String> toName){
this.toName= toName;
}
}

setTextColor in onpostexecute() from another xml (R.layout.list_item) Asynctask

I want to change the color of the text depending on the value from php jsonobject. The program can already get the value and able to display it on each textview. But my problem is, how can I change the color of each text view at the same time, depending on the Flimitstat, Vlimitstat and Climitstat. Hope you can help me!
This is my ThirdFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ThirdFragment extends ListFragment {
String site1 = "";
String freq1 = "";
String curr1 = "";
String volts1 = "";
String fstat1 = "";
String vstat1 = "";
String cstat1 = "";
String site2 = "";
String freq2 = "";
String curr2 = "";
String volts2 = "";
String fstat2 = "";
String vstat2 = "";
String cstat2 = "";
String site3 = "";
String freq3 = "";
String curr3 = "";
String volts3 = "";
String fstat3 = "";
String vstat3 = "";
String cstat3 = "";
String site4 = "";
String freq4 = "";
String curr4 = "";
String volts4 = "";
String fstat4 = "";
String vstat4 = "";
String cstat4 = "";
String site5 = "";
String freq5 = "";
String curr5 = "";
String volts5 = "";
String fstat5 = "";
String vstat5 = "";
String cstat5 = "";
String site6 = "";
String freq6 = "";
String curr6 = "";
String volts6 = "";
String fstat6 = "";
String vstat6 = "";
String cstat6 = "";
String site7 = "";
String freq7 = "";
String curr7 = "";
String volts7 = "";
String fstat7 = "";
String vstat7 = "";
String cstat7 = "";
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
TextView freqa;
TextView voltsa;
TextView curra;
TextView freqb;
TextView voltsb;
TextView currb;
TextView freqc;
TextView voltsc;
TextView currc;
TextView freqd;
TextView voltsd;
TextView currd;
TextView freqe;
TextView voltse;
TextView curre;
TextView freqf;
TextView voltsf;
TextView currf;
TextView freqg;
TextView voltsg;
TextView currg;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_frag, container, false);
freqa = (TextView)v.findViewById(R.id.frequency1);
voltsa = (TextView)v.findViewById(R.id.acvoltage1);
curra = (TextView)v.findViewById(R.id.accurrent1);
freqb = (TextView)v.findViewById(R.id.frequency2);
voltsb = (TextView)v.findViewById(R.id.acvoltage2);
currb = (TextView)v.findViewById(R.id.accurrent2);
freqc = (TextView)v.findViewById(R.id.frequency3);
voltsc = (TextView)v.findViewById(R.id.acvoltage3);
currc = (TextView)v.findViewById(R.id.accurrent3);
freqd = (TextView)v.findViewById(R.id.frequency4);
voltsd = (TextView)v.findViewById(R.id.acvoltage4);
currd = (TextView)v.findViewById(R.id.accurrent4);
freqe = (TextView)v.findViewById(R.id.frequency5);
voltse = (TextView)v.findViewById(R.id.acvoltage5);
curre = (TextView)v.findViewById(R.id.accurrent5);
freqf = (TextView)v.findViewById(R.id.frequency6);
voltsf = (TextView)v.findViewById(R.id.acvoltage6);
currf = (TextView)v.findViewById(R.id.accurrent6);
freqg = (TextView)v.findViewById(R.id.frequency7);
voltsg = (TextView)v.findViewById(R.id.acvoltage7);
currg = (TextView)v.findViewById(R.id.accurrent7);
new GetContacts().execute();
return v;
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/energyreadings.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_FREQUENCY1 = "Frequency1";
private static final String TAG_ACCURRENT1 = "AC_Voltage1";
private static final String TAG_ACVOLTAGE1 = "AC_Current1";
private static final String TAG_FSTAT1 = "Flimitstat1";
private static final String TAG_VSTAT1 = "Vlimitstat1";
private static final String TAG_CSTAT1 = "Climitstat1";
private static final String TAG_SITENAME2 = "siteName2";
private static final String TAG_FREQUENCY2 = "Frequency2";
private static final String TAG_ACCURRENT2 = "AC_Voltage2";
private static final String TAG_ACVOLTAGE2 = "AC_Current2";
private static final String TAG_FSTAT2 = "Flimitstat2";
private static final String TAG_VSTAT2 = "Vlimitstat2";
private static final String TAG_CSTAT2 = "Climitstat2";
private static final String TAG_SITENAME3 = "siteName3";
private static final String TAG_FREQUENCY3 = "Frequency3";
private static final String TAG_ACCURRENT3 = "AC_Voltage3";
private static final String TAG_ACVOLTAGE3 = "AC_Current3";
private static final String TAG_FSTAT3 = "Flimitstat3";
private static final String TAG_VSTAT3 = "Vlimitstat3";
private static final String TAG_CSTAT3 = "Climitstat3";
private static final String TAG_SITENAME4 = "siteName4";
private static final String TAG_FREQUENCY4 = "Frequency4";
private static final String TAG_ACCURRENT4 = "AC_Voltage4";
private static final String TAG_ACVOLTAGE4 = "AC_Current4";
private static final String TAG_FSTAT4 = "Flimitstat4";
private static final String TAG_VSTAT4 = "Vlimitstat4";
private static final String TAG_CSTAT4 = "Climitstat4";
private static final String TAG_SITENAME5 = "siteName5";
private static final String TAG_FREQUENCY5 = "Frequency5";
private static final String TAG_ACCURRENT5 = "AC_Voltage5";
private static final String TAG_ACVOLTAGE5 = "AC_Current5";
private static final String TAG_FSTAT5 = "Flimitstat5";
private static final String TAG_VSTAT5 = "Vlimitstat5";
private static final String TAG_CSTAT5 = "Climitstat5";
private static final String TAG_SITENAME6 = "siteName6";
private static final String TAG_FREQUENCY6 = "Frequency6";
private static final String TAG_ACCURRENT6 = "AC_Voltage6";
private static final String TAG_ACVOLTAGE6 = "AC_Current6";
private static final String TAG_FSTAT6 = "Flimitstat6";
private static final String TAG_VSTAT6 = "Vlimitstat6";
private static final String TAG_CSTAT6 = "Climitstat6";
private static final String TAG_SITENAME7 = "siteName7";
private static final String TAG_FREQUENCY7 = "Frequency7";
private static final String TAG_ACCURRENT7 = "AC_Voltage7";
private static final String TAG_ACVOLTAGE7 = "AC_Current7";
private static final String TAG_FSTAT7 = "Flimitstat7";
private static final String TAG_VSTAT7 = "Vlimitstat7";
private static final String TAG_CSTAT7 = "Climitstat7";
// contacts JSONArray
JSONObject c = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
freq1 = c.getString(TAG_FREQUENCY1);
curr1 = c.getString(TAG_ACCURRENT1);
volts1 = c.getString(TAG_ACVOLTAGE1);
fstat1 = c.getString(TAG_FSTAT1);
vstat1 = c.getString(TAG_VSTAT1);
cstat1 = c.getString(TAG_CSTAT1);
site2 = c.getString(TAG_SITENAME2);
freq2 = c.getString(TAG_FREQUENCY2);
curr2 = c.getString(TAG_ACCURRENT2);
volts2 = c.getString(TAG_ACVOLTAGE2);
fstat2 = c.getString(TAG_FSTAT2);
vstat2 = c.getString(TAG_VSTAT2);
cstat2 = c.getString(TAG_CSTAT2);
site3 = c.getString(TAG_SITENAME3);
freq3 = c.getString(TAG_FREQUENCY3);
curr3 = c.getString(TAG_ACCURRENT3);
volts3 = c.getString(TAG_ACVOLTAGE3);
fstat3 = c.getString(TAG_FSTAT3);
vstat3 = c.getString(TAG_VSTAT3);
cstat3 = c.getString(TAG_CSTAT3);
site4 = c.getString(TAG_SITENAME4);
freq4 = c.getString(TAG_FREQUENCY4);
curr4 = c.getString(TAG_ACCURRENT4);
volts4 = c.getString(TAG_ACVOLTAGE4);
fstat4 = c.getString(TAG_FSTAT4);
vstat4 = c.getString(TAG_VSTAT4);
cstat4 = c.getString(TAG_CSTAT4);
site5 = c.getString(TAG_SITENAME5);
freq5 = c.getString(TAG_FREQUENCY5);
curr5 = c.getString(TAG_ACCURRENT5);
volts5 = c.getString(TAG_ACVOLTAGE5);
fstat5 = c.getString(TAG_FSTAT5);
vstat5 = c.getString(TAG_VSTAT5);
cstat5 = c.getString(TAG_CSTAT5);
site6 = c.getString(TAG_SITENAME6);
freq6 = c.getString(TAG_FREQUENCY6);
curr6 = c.getString(TAG_ACCURRENT6);
volts6 = c.getString(TAG_ACVOLTAGE6);
fstat6 = c.getString(TAG_FSTAT6);
vstat6 = c.getString(TAG_VSTAT6);
cstat6 = c.getString(TAG_CSTAT6);
site7 = c.getString(TAG_SITENAME7);
freq7 = c.getString(TAG_FREQUENCY7);
curr7 = c.getString(TAG_ACCURRENT7);
volts7 = c.getString(TAG_ACVOLTAGE7);
fstat7 = c.getString(TAG_FSTAT7);
vstat7 = c.getString(TAG_VSTAT7);
cstat7 = c.getString(TAG_CSTAT7);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_FREQUENCY1, freq1);
contact.put(TAG_ACCURRENT1, curr1);
contact.put(TAG_ACVOLTAGE1, volts1);
contact.put(TAG_FSTAT1, fstat1);
contact.put(TAG_VSTAT1, vstat1);
contact.put(TAG_CSTAT1, cstat1);
contact.put(TAG_SITENAME2, site2);
contact.put(TAG_FREQUENCY2, freq2);
contact.put(TAG_ACCURRENT2, curr2);
contact.put(TAG_ACVOLTAGE2, volts2);
contact.put(TAG_FSTAT2, fstat2);
contact.put(TAG_VSTAT2, vstat2);
contact.put(TAG_CSTAT2, cstat2);
contact.put(TAG_SITENAME3, site3);
contact.put(TAG_FREQUENCY3, freq3);
contact.put(TAG_ACCURRENT3, curr3);
contact.put(TAG_ACVOLTAGE3, volts3);
contact.put(TAG_FSTAT3, fstat3);
contact.put(TAG_VSTAT3, vstat3);
contact.put(TAG_CSTAT3, cstat3);
contact.put(TAG_SITENAME4, site4);
contact.put(TAG_FREQUENCY4, freq4);
contact.put(TAG_ACCURRENT4, curr4);
contact.put(TAG_ACVOLTAGE4, volts4);
contact.put(TAG_FSTAT4, fstat4);
contact.put(TAG_VSTAT4, vstat4);
contact.put(TAG_CSTAT4, cstat4);
contact.put(TAG_SITENAME5, site5);
contact.put(TAG_FREQUENCY5, freq5);
contact.put(TAG_ACCURRENT5, curr5);
contact.put(TAG_ACVOLTAGE5, volts5);
contact.put(TAG_FSTAT5, fstat5);
contact.put(TAG_VSTAT5, vstat5);
contact.put(TAG_CSTAT5, cstat5);
contact.put(TAG_SITENAME6, site6);
contact.put(TAG_FREQUENCY6, freq6);
contact.put(TAG_ACCURRENT6, curr6);
contact.put(TAG_ACVOLTAGE6, volts6);
contact.put(TAG_FSTAT6, fstat6);
contact.put(TAG_VSTAT6, vstat6);
contact.put(TAG_CSTAT6, cstat6);
contact.put(TAG_SITENAME7, site7);
contact.put(TAG_FREQUENCY7, freq7);
contact.put(TAG_ACCURRENT7, curr7);
contact.put(TAG_ACVOLTAGE7, volts7);
contact.put(TAG_FSTAT7, fstat7);
contact.put(TAG_VSTAT7, vstat7);
contact.put(TAG_CSTAT7, cstat7);
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
//RADAR 1
//Frequency 1 status
if (TAG_FSTAT1.equals("1")){
freqa.setTextColor(Color.GREEN);
}
else if(TAG_FSTAT1.equals("2")){
freqa.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 1 status
if (TAG_VSTAT1.equals("1")){
voltsa.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT1.equals("2")){
voltsa.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 1 status
if (TAG_CSTAT1.equals("1")){
curra.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT1.equals("2")){
curra.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 2
//Frequency 2 status
if (TAG_FSTAT2.equals("1")){
freqb.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT2.equals("2")){
freqb.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 2 status
if (TAG_VSTAT2.equals("1")){
voltsb.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT2.equals("2")){
voltsb.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 2 status
if (TAG_CSTAT2.equals("1")){
currb.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT2.equals("2")){
currb.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 3
//Frequency 3 status
if (TAG_FSTAT3.equals("1")){
freqc.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT3.equals("2")){
freqc.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 3 status
if (TAG_VSTAT3.equals("1")){
voltsc.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT3.equals("2")){
voltsc.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 3 status
if (TAG_CSTAT3.equals("1")){
currc.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT3.equals("2")){
currc.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 4
//Frequency 4 status
if (TAG_FSTAT4.equals("1")){
freqd.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT4.equals("2")){
freqd.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 4 status
if (TAG_VSTAT4.equals("1")){
voltsd.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT4.equals("2")){
voltsd.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 4 status
if (TAG_CSTAT4.equals("1")){
currd.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT4.equals("2")){
currd.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 5
//Frequency 5 status
if (TAG_FSTAT5.equals("1")){
freqe.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT5.equals("2")){
freqe.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 5 status
if (TAG_VSTAT5.equals("1")){
voltse.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT5.equals("2")){
voltse.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 5 status
if (TAG_CSTAT5.equals("1")){
curre.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT5.equals("2")){
curre.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 6
//Frequency 6 status
if (TAG_FSTAT6.equals("1")){
freqf.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT6.equals("2")){
freqf.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 6 status
if (TAG_VSTAT6.equals("1")){
voltsf.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT6.equals("2")){
voltsf.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 6 status
if (TAG_CSTAT6.equals("1")){
currf.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT6.equals("2")){
currf.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 7
//Frequency 7 status
if (TAG_FSTAT7.equals("1")){
freqg.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT7.equals("2")){
freqg.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 7 status
if (TAG_VSTAT7.equals("1")){
voltsg.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT7.equals("2")){
voltsg.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 7 status
if (TAG_CSTAT7.equals("1")){
currg.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT7.equals("2")){
currg.setTextColor(getResources().getColor(R.color.red));
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_SITENAME1, TAG_FREQUENCY1, TAG_ACCURRENT1,
TAG_ACVOLTAGE1,TAG_SITENAME2, TAG_FREQUENCY2, TAG_ACCURRENT2,
TAG_ACVOLTAGE2,TAG_SITENAME3, TAG_FREQUENCY3, TAG_ACCURRENT3,
TAG_ACVOLTAGE3, TAG_SITENAME4, TAG_FREQUENCY4, TAG_ACCURRENT4,
TAG_ACVOLTAGE4, TAG_SITENAME5, TAG_FREQUENCY5, TAG_ACCURRENT5,
TAG_ACVOLTAGE5, TAG_SITENAME6, TAG_FREQUENCY6, TAG_ACCURRENT6,
TAG_ACVOLTAGE6, TAG_SITENAME7, TAG_FREQUENCY7, TAG_ACCURRENT7,
TAG_ACVOLTAGE7},
new int[] { R.id.sitename1, R.id.frequency1,
R.id.accurrent1, R.id.acvoltage1, R.id.sitename2, R.id.frequency2,
R.id.accurrent2, R.id.acvoltage2, R.id.sitename3, R.id.frequency3,
R.id.accurrent3, R.id.acvoltage3, R.id.sitename4, R.id.frequency4,
R.id.accurrent4, R.id.acvoltage4, R.id.sitename5, R.id.frequency5,
R.id.accurrent5, R.id.acvoltage5, R.id.sitename6, R.id.frequency6,
R.id.accurrent6, R.id.acvoltage6, R.id.sitename7, R.id.frequency7,
R.id.accurrent7, R.id.acvoltage7});
// updating listviews
setListAdapter(adapter);
}
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
You can check my listadapter and i have implemented the same concept to set the text color in two ways
private class CustomerAdapter extends ArrayAdapter<RouteTrackerUser>
{
Context context;
int textViewResourceId;
private ArrayList<RouteTrackerUser> originalitems;
public CustomerAdapter(Context context, int textViewResourceId, ArrayList<RouteTrackerUser> items) {
super(context, textViewResourceId, items);
this.textViewResourceId = textViewResourceId;
this.context = context;
this.originalitems = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
v = inflater.inflate(textViewResourceId, parent, false);
}
final RouteTrackerUser r = originalitems.get(position);
if (r != null) {
TextView textName= (TextView) v.findViewById(R.id.sname);
TextView postal=(TextView) v.findViewById(R.id.postal);
if(r.getVisited().equals("true"))
{
if(textName != null)
{
textName.setTextColor(getResources().getColor(R.color.lightpurple));
textName.setText(r.getStorename());
}
if(postal != null)
{
postal.setTextColor(getResources().getColor(R.color.lightpurple));
postal.setText("Address: "+r.getPostalcode());
}
}
if(r.getVisited().equals("false"))
{
if(textName != null)
{
textName.setTextColor(getResources().getColor(R.color.darkpurple));
textName.setText(r.getStorename());
}
if(postal != null)
{
postal.setTextColor(getResources().getColor(R.color.darkpurple));
postal.setText("Address: "+r.getPostalcode());
}
}
if(RouteTrackerApp.sharedPreference.getInt(RouteTrackerApp.SHARED_ACCESS_UTYPE, 0) == Constants.VAR_TYPE_SALES_PERSON){
v.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
viewdata(r.getUsername(),r.getStoreid(),r.getAccountid(),r.getUid(),r.getVisitplanid(),r.getVisited(),r.getStorename());
}});
}
}
return v;
}
}
and on PostExecute i called this adapter like
protected void onPostExecute(ArrayList<RouteTrackerUser> result)
{
if(result!=null)
{
// System.out.println("User with result===>"+result);
/*for(RouteTrackerUser r :result ){
System.out.println("StoreName===>"+r.getStorename());}*/
Intent intent=getIntent();
TextView username=(TextView)findViewById(R.id.usrname);
final String sname=intent.getExtras().getString("user_name");
username.setText("Welcome, "+sname);
TextView todayvisits=(TextView)findViewById(R.id.todaylist);
todayvisits.setText("TODAY'S STORE VISITS");
userAdapter = new CustomerAdapter(ViewYourPlanList.this, R.layout.view_your_plan_list,result);
userList = (ListView) findViewById(R.id.listview);
userList.setItemsCanFocus(false);
userList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
userList.setAdapter(userAdapter);
dialog.dismiss();
}
else
if you are want to implement in listfragment ! Design a customadapter and set the text color like i shown below and call this customadapter on postexecute.
public class CustomAdapter extends ArrayAdapter<Model> {
private final LayoutInflater mInflater;
public CustomAdapter(Context context) {
super(context, android.R.layout.simple_list_item_2);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Model> data) {
clear();
if (data != null) {
for (Model appEntry : data) {
System.out.println("cust adptr set data: "+appEntry.getStorename());
add(appEntry);
}
}
}
/**
* Populate new items in the list.
*/
#SuppressLint("SimpleDateFormat")
#Override public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.view_your_plan_weekly, parent, false);
} else {
view = convertView;
}
Model item = getItem(position);
int dayVal = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)-1;
ImageView arrow=(ImageView)view.findViewById(R.id.arrow_image);
arrow.setVisibility(View.INVISIBLE);
if(item.getTabId().equals(String.valueOf(dayVal))){
arrow.setVisibility(View.VISIBLE);
}
if(item.getVisited().equals("true"))
{
((TextView)view.findViewById(R.id.sname)).setText(item.getStorename());
((TextView)view.findViewById(R.id.postal)).setText(item.getPostal());
((TextView)view.findViewById(R.id.sname)).setTextColor(Color.parseColor("#D397D4"));
((TextView)view.findViewById(R.id.postal)).setTextColor(Color.parseColor("#D397D4"));
}
if(item.getVisited().equals("false"))
{
((TextView)view.findViewById(R.id.sname)).setText(item.getStorename());
((TextView)view.findViewById(R.id.postal)).setText(item.getPostal());
((TextView)view.findViewById(R.id.sname)).setTextColor(Color.parseColor("#9B419B"));
((TextView)view.findViewById(R.id.postal)).setTextColor(Color.parseColor("#9B419B"));
}
return view;
}
}
Remove this part
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_SITENAME1, TAG_FREQUENCY1, TAG_ACCURRENT1,
TAG_ACVOLTAGE1,TAG_SITENAME2, TAG_FREQUENCY2, TAG_ACCURRENT2,
TAG_ACVOLTAGE2,TAG_SITENAME3, TAG_FREQUENCY3, TAG_ACCURRENT3,
TAG_ACVOLTAGE3, TAG_SITENAME4, TAG_FREQUENCY4, TAG_ACCURRENT4,
TAG_ACVOLTAGE4, TAG_SITENAME5, TAG_FREQUENCY5, TAG_ACCURRENT5,
TAG_ACVOLTAGE5, TAG_SITENAME6, TAG_FREQUENCY6, TAG_ACCURRENT6,
TAG_ACVOLTAGE6, TAG_SITENAME7, TAG_FREQUENCY7, TAG_ACCURRENT7,
TAG_ACVOLTAGE7},
new int[] { R.id.sitename1, R.id.frequency1,
R.id.accurrent1, R.id.acvoltage1, R.id.sitename2, R.id.frequency2,
R.id.accurrent2, R.id.acvoltage2, R.id.sitename3, R.id.frequency3,
R.id.accurrent3, R.id.acvoltage3, R.id.sitename4, R.id.frequency4,
R.id.accurrent4, R.id.acvoltage4, R.id.sitename5, R.id.frequency5,
R.id.accurrent5, R.id.acvoltage5, R.id.sitename6, R.id.frequency6,
R.id.accurrent6, R.id.acvoltage6, R.id.sitename7, R.id.frequency7,
R.id.accurrent7, R.id.acvoltage7});
// updating listviews
setListAdapter(adapter);
and instead of SimpleAdapter you use customadapter. In CustomAdapter you can set the textcolor as i shown in my previous post.Just go through the class "public class CustomAdapter extends ArrayAdapter "

Android read contacts(and details) seems very slow

I use the following code to read each contacts along with their details.
private static final String[] PROJECTION =
{
Data._ID,
Data.MIMETYPE,
Data.DATA1,
Data.DATA2,
Data.DATA3,
Data.DATA4,
Data.DATA5,
Data.DATA6,
Data.DATA7,
Data.DATA8,
Data.DATA9,
Data.DATA10,
Data.DATA11,
Data.DATA12,
Data.DATA13,
Data.DATA14,
Data.DATA15
};
private static final String SELECTION = Data.LOOKUP_KEY + " = ?";
private String[] mSelectionArgs = { "" };
private static final String SORT_ORDER = Data.MIMETYPE;
private static final int MIME_TYPE_INDEX = 1;
private static final int DISPLAY_NAME_INDEX = 3;//data2
private static final int GIVEN_NAME_INDEX = 3;//data2
private static final int FAMILY_NAME_INDEX = 4;//data3
private static final int MIDDLE_NAME_INDEX = 6;//data5
private static final int ORGANIZATION_INDEX = 2;//data2
private static final int PHONE_TYPE_INDEX = 3;//data2
private static final int PHONE_LABEL_INDEX = 4;//data3
private static final int PHONE_NUMBER_INDEX = 2;//data1
private static final int EMAIL_TYPE_INDEX = 3;//data2
private static final int EMAIL_LABEL_INDEX = 4;//data1
private static final int EMAIL_INDEX = 2;//data1
private byte[] createJsonData(ArrayList<String> selected) throws JSONException, IOException{
Log.d("SynchContactActivity", "Time 1: " + java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
int current = 0;
final String messagePrep = getResources().getString(R.string.progress_message_prep);
final String messageCompress = getResources().getString(R.string.progress_message_compress);
final String messageUpload = getResources().getString(R.string.progress_message_upload);
if(selected == null ){
selected = getContacts();
}
final int count = selected.size();
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMax(count);
mProgressDialog.setMessage(messagePrep);
}
}
});
updateProgress(current);
JSONObject root = new JSONObject();
JSONArray contactsArray = new JSONArray();
JSONObject contactJSON, phoneJSON, emailJSON;
JSONArray phonesArray,emailsArray;
String name, lastName, middleName,organization;
for (String key : selected) {
contactJSON = new JSONObject();
phonesArray = new JSONArray();
emailsArray = new JSONArray();
mSelectionArgs[0] = key;
//Cursor details = managedQuery(Data.CONTENT_URI, PROJECTION, SELECTION, mSelectionArgs, SORT_ORDER);
Cursor details = getApplicationContext().getContentResolver().query(Data.CONTENT_URI, PROJECTION, SELECTION, mSelectionArgs, SORT_ORDER);
//initialize null variables
name = null;
lastName = null;
middleName = null;
organization = null;
while(details.moveToNext()){
String mimeType = details.getString(MIME_TYPE_INDEX);
if(mimeType.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)){
name = details.getString(GIVEN_NAME_INDEX);
lastName = details.getString(FAMILY_NAME_INDEX);
middleName = details.getString(MIDDLE_NAME_INDEX);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
organization = details.getString(ORGANIZATION_INDEX);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
phoneJSON = new JSONObject();
String phoneNumber = details.getString(PHONE_NUMBER_INDEX);
int type = details.getInt(PHONE_TYPE_INDEX);
String typeLabel = phoneTypeMap.get(String.valueOf(type));
if (typeLabel == null) {
typeLabel = details.getString(PHONE_LABEL_INDEX);
}
phoneJSON.put("ptype", typeLabel);
phoneJSON.put("number", phoneNumber);
phonesArray.put(phoneJSON);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)){
emailJSON = new JSONObject();
String email = details.getString(EMAIL_INDEX);
int type = details.getInt(EMAIL_TYPE_INDEX);
String typeLabel = emailTypeMap.get(String.valueOf(type));
if (typeLabel == null) {
typeLabel = details.getString(EMAIL_LABEL_INDEX);
}
emailJSON.put("etype", typeLabel);
emailJSON.put("address",email);
emailsArray.put(emailJSON);
}
}
contactJSON.put("firstname", name==null?"null":name);
contactJSON.put("middlename", middleName==null?"null":middleName);
contactJSON.put("lastname", lastName==null?"null":lastName);
contactJSON.put("organization", organization==null?"null":organization);
contactJSON.put("phones", phonesArray);
contactJSON.put("emails", emailsArray);
contactsArray.put(contactJSON);
details.close();
++current;
updateProgress(current);
}
root.put("contacts", contactsArray);
Log.d("SynchContactActivity", "Time 1: " + java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMessage(messageCompress);
}
}
});
// to compress
String json_doc = root.toString();
byte[] compressed = compress(json_doc);
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMessage(messageUpload);
}
}
});
return compressed;
}
This code is too slow - that reads 3-4 contacts per second on average. Is this normal or can be optimized?
I think projection might be a good candidate to be optimized but I'm not sure.
Thanks in advance.
It's hard for me to tell exactly what you're trying to do, but it looks like you're trying to read data from the Contacts Provider and send it to a server using JSON. I suggest you look at the ContactsContract.RawContacts.Entity table, which contains all the data you're probably looking for without the mess of trying to figure out the MIME type of the DATA row you've just retrieved. You're certainly slowing down your app by getting the entire contents of the DATA row.
In addition, you should use a SyncAdapter to do this work. See Transferring Data Using Sync Adapters
Reading contacts can be made in 2-5 seconds. See the example app here
Source code attached

Bluetooth not sending file to other device

It is already asked but i didn't find any solution. For bluetooth application i am using the bluetoothShare.class .
My source code for sending the file to the target device
MainActvity.class:
Set<BluetoothDevice> devices = btAdapter
.getBondedDevices();
final String btDeviceName = selected_deviceName;
BluetoothDevice device = null;
for (BluetoothDevice itDevice : devices) {
if (btDeviceName.equals(itDevice.getName())) {
device = itDevice;
}
}
if (device != null) {
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, uri.toString());
values.put(BluetoothShare.MIMETYPE, "image/jpeg");
values.put(BluetoothShare.DESTINATION,
device.getAddress());
values.put(BluetoothShare.DIRECTION,
BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
final Uri contentUri = getApplicationContext()
.getContentResolver().insert(
BluetoothShare.CONTENT_URI, values);
Log.v(TAG, "Insert contentUri: " + contentUri
+ " to device: " + device.getName());
Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_LONG).show();
} else {
textStatus
.setText("Bluetooth remote device not found");
}
} else {
textStatus.setText("Bluetooth not activated");
}
}
else {
Toast.makeText(getApplicationContext(), "No devices found",
Toast.LENGTH_LONG).show();
}
and the blueToothShare.class:
package process.bluetooth.sendfile.opp;
import android.net.Uri;
import android.provider.BaseColumns;
public final class BluetoothShare implements BaseColumns {
private BluetoothShare() {
}
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_BLUETOOTH_SHARE";
public static final Uri CONTENT_URI = Uri
.parse("content://com.android.bluetooth.opp/btopp");
public static final String TRANSFER_COMPLETED_ACTION = "android.btopp.intent.action.TRANSFER_COMPLETE";
public static final String INCOMING_FILE_CONFIRMATION_REQUEST_ACTION = "android.btopp.intent.action.INCOMING_FILE_NOTIFICATION";
public static final String USER_CONFIRMATION_TIMEOUT_ACTION = "android.btopp.intent.action.USER_CONFIRMATION_TIMEOUT";
public static final String URI = "uri";
public static final String FILENAME_HINT = "hint";
public static final String _DATA = "_data";
public static final String MIMETYPE = "mimetype";
public static final String DIRECTION = "direction";
public static final String DESTINATION = "destination";
public static final String VISIBILITY = "visibility";
public static final String USER_CONFIRMATION = "confirm";
public static final String STATUS = "status";
public static final String TOTAL_BYTES = "total_bytes";
public static final String CURRENT_BYTES = "current_bytes";
public static final String TIMESTAMP = "timestamp";
public static final int DIRECTION_OUTBOUND = 0;
public static final int DIRECTION_INBOUND = 1;
public static final int USER_CONFIRMATION_PENDING = 0;
public static final int USER_CONFIRMATION_CONFIRMED = 1;
public static final int USER_CONFIRMATION_AUTO_CONFIRMED = 2;
public static final int USER_CONFIRMATION_DENIED = 3;
public static final int USER_CONFIRMATION_TIMEOUT = 4;
public static final int VISIBILITY_VISIBLE = 0;
public static final int VISIBILITY_HIDDEN = 1;
public static boolean isStatusInformational(int status) {
return (status >= 100 && status < 200);
}
public static boolean isStatusSuspended(int status) {
return (status == STATUS_PENDING);
}
public static boolean isStatusSuccess(int status) {
return (status >= 200 && status < 300);
}
public static boolean isStatusError(int status) {
return (status >= 400 && status < 600);
}
public static boolean isStatusClientError(int status) {
return (status >= 400 && status < 500);
}
public static boolean isStatusServerError(int status) {
return (status >= 500 && status < 600);
}
public static boolean isStatusCompleted(int status) {
return (status >= 200 && status < 300)
|| (status >= 400 && status < 600);
}
public static final int STATUS_PENDING = 190;
public static final int STATUS_RUNNING = 192;
public static final int STATUS_SUCCESS = 200;
public static final int STATUS_BAD_REQUEST = 400;
public static final int STATUS_FORBIDDEN = 403;
public static final int STATUS_NOT_ACCEPTABLE = 406;
public static final int STATUS_LENGTH_REQUIRED = 411;
public static final int STATUS_PRECONDITION_FAILED = 412;
public static final int STATUS_CANCELED = 490;
public static final int STATUS_UNKNOWN_ERROR = 491;
public static final int STATUS_FILE_ERROR = 492;
public static final int STATUS_ERROR_NO_SDCARD = 493;
public static final int STATUS_ERROR_SDCARD_FULL = 494;
public static final int STATUS_UNHANDLED_OBEX_CODE = 495;
public static final int STATUS_OBEX_DATA_ERROR = 496;
public static final int STATUS_CONNECTION_ERROR = 497;
}
BluetoothShare class not supported android 4.1 and above. you can use the following intent coding to send file in android version 4.1 and above
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setComponent(new ComponentName(
"com.android.bluetooth",
"com.android.bluetooth.opp.BluetoothOppLauncherActivity"));
intent.setType("image/jpeg");
file = new File(filepath);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(intent);
and also some devices in Android v 2.2/2.3 not send the file via bluetoothShare class.
Maybe you can try another solution with BufferedWriter and BufferedReader.
Here is a snipped code:
BluetoothDevice mmDevice;
Set<BluetoothDevice> mBluetoothAdapter;
BluetoothAdapter bAdapter = BluetoothAdapter
.getDefaultAdapter();
mBluetoothAdapter = bAdapter.getBondedDevices();
for (BluetoothDevice bc : mBluetoothAdapter) {
if (bc.getName().indexOf("name_of_bluetoothdevide") != -1) {
UUID uuid = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard
// SerialPortService
// ID
mmDevice = bc;
BluetoothSocket mmSocket = mmDevice
.createInsecureRfcommSocketToServiceRecord(uuid);
bAdapter.cancelDiscovery();
mmSocket.connect();
BufferedWriter Writer = new BufferedWriter(
new OutputStreamWriter(
mmSocket.getOutputStream()));
Writer.write("Bluetooth connected!");
Writer.flush();
app.setmSocket(mmSocket);
break;
}
}
And for reading:
BufferedReader Reader = new BufferedReader(
new InputStreamReader(mmSocket.getInputStream()));
receivedMsg = Reader.readLine();
Hope it can help you.
This code works with firmware from MediaTek. Tested on Android 4.0.4. Sends the file, without asking anything from the user
public boolean SendFileViaBluetoothOPP(String file_path, String destinationMAC){
BluetoothAdapter btadapter = BluetoothAdapter.getDefaultAdapter();
if(btadapter == null)
return false;
BluetoothDevice btdev = btadapter.getRemoteDevice(destinationMAC);
if(btdev == null)
return false;
Uri uri = Uri.fromFile(new File(file_path));
Intent shareIntent = new Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_STREAM, uri)
.setType("application/zip");
List<ResolveInfo> resolvedActivities = getPackageManager().queryIntentActivities(shareIntent, 0);
boolean found = false;
for(ResolveInfo actInfo: resolvedActivities){
if(actInfo.activityInfo.packageName.equals("com.mediatek.bluetooth"))
{
shareIntent.setComponent( new ComponentName(actInfo.activityInfo.packageName, actInfo.activityInfo.name ) );
shareIntent.putExtra("com.mediatek.bluetooth.sharegateway.extra.DEVICE_ADDRESS", btdev);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
found = true;
break;
}
}
if(found){
startActivity(shareIntent);
return true;
}
return false;
}
On older phone from MediaTek with Android 2.2.1 this code launches BluetoothDevicePicker to complete the operation.
Maybe this could help you in some way…
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}

Categories

Resources