Android : Make this object as Parcelable

天涯浪子 提交于 2020-01-04 06:52:38

问题


I have an object that I need to pass between 2 Activity. The object has HashTable, String[], etc. Can't make out how to make it Parcalebale so that I can populate an array of the object and pass single obj or array to other Activity. My class is :

 public class TrainRoute  { // implements Parcelable
private String RouteName;
private int RouteIndex;

private Context ctx;
private Hashtable<String, String> stationsList;
private String[] stationsNames;
private String[] trainTimings;

private boolean hasSpecialMessages;
private Hashtable<String, String> specialMessages; 

private String firstStation; 
private String CURRENT_ROUTE_PATH;


public TrainRoute(Context ctx, String routeName, int routeIndex, String routeUpOrDownPath, boolean hasSpecialMessages) {
    this.ctx = ctx;
    this.RouteName = routeName;
    this.RouteIndex = routeIndex;
    this.CURRENT_ROUTE_PATH = routeUpOrDownPath;
    this.hasSpecialMessages = hasSpecialMessages;       
}
public String getName() { return RouteName; }
public int getIndex() { return RouteIndex; }

public String[] getStationsNames()
{       
    if(this.stationsList == null)
    {
        String file = this.CURRENT_ROUTE_PATH + "/" + CONSTANTS.SUBPATH_STATIONS + "/" + this.RouteIndex + ".txt";
        String[][] tempList = ResourceReader.GetValues(ctx, file, 2);
        this.stationsList = new Hashtable<String, String>(tempList.length);
        this.stationsNames = new String[tempList.length];
        for(int i=0;i<tempList.length;i++)
        {
            this.stationsList.put(tempList[i][0], tempList[i][1] );
            this.stationsNames[i] = tempList[i][0];
        }
        this.firstStation = this.stationsNames[0];
    }

    return stationsNames;
}

public String[] getTimings(String stationName)
{
    if(this.trainTimings == null)
    {
        String file = this.CURRENT_ROUTE_PATH + "/" + CONSTANTS.SUBPATH_TIMINGS + "/" + this.RouteIndex + ".txt";
        this.trainTimings = ResourceReader.GetLines(ctx, file);

        for(int i=0;i<this.trainTimings.length;i++)
        {
            this.trainTimings[i] = this.trainTimings[i].substring(0, 2) + ":" + this.trainTimings[i].substring(2, 4);
        }
    }

    int minutesFromOrigin =  
        Integer.parseInt(this.stationsList.get(stationName).toString())
        - Integer.parseInt(this.stationsList.get(this.firstStation).toString());

    String[] trainTimingsForStation = new String[this.trainTimings.length];
    for (int i = 0; i < trainTimingsForStation.length; i++) {
        trainTimingsForStation[i] = AddMinutes(this.trainTimings[i], minutesFromOrigin);
    }

    return trainTimingsForStation;
}

public void loadSpecialMessages()
{
    if(this.hasSpecialMessages == true && this.specialMessages == null)
    {
        this.specialMessages = new Hashtable<String, String>();
        String specialMessagesFilePath = this.CURRENT_ROUTE_PATH + "/" + CONSTANTS.SPECIALMESSAGES_FOLDER_NAME + "/" + this.RouteIndex + ".txt";

        String[][] tempSpecialMessages = ResourceReader.GetValues(ctx, specialMessagesFilePath, 2);
        for (int i = 0; i < tempSpecialMessages.length; i++)
        {
            tempSpecialMessages[i][1] = tempSpecialMessages[i][1].replaceAll("\\n", "\n");  //  StringFunctions.replace(tempSpecialMessages[i][1], "\\n", "\n");


            tempSpecialMessages[i][0] = tempSpecialMessages[i][0].substring(0, 2) + ":" + tempSpecialMessages[i][0].substring(2, 4);;

            this.specialMessages.put(tempSpecialMessages[i][0], tempSpecialMessages[i][1]);
        }
    }
}   

public boolean hasSpecialMessage(int trainIndex)
{
    if(this.hasSpecialMessages == true)
    {
        return this.specialMessages.containsKey(this.trainTimings[trainIndex - 1]);
    }
    else
        return false;
}


public String getSpecialMessage(int trainIndex)
{
    return this.specialMessages.get((this.trainTimings[trainIndex - 1]).toString()).toString();
}   

On implementing Parcelable, I can't make out how to add the object fields in implemented functions.

Due to so many HashTable, String[], would implementing Serialiazable more preferred for this case than Parcelable ? If add Serializable then also how to implement ts methods for the same.

EDIT: In the above obj, I added a method :

    public Hashtable<String, String> getAllSpecialMessages() {
    return this.specialMessages;
}

I am trying just to pass this HashTable from my Activity to another Activity :

intent.putExtra("specialMsgs", curTrainRoute.getAllSpecialMessages());

// OTHER ACTIVTY 
    Serializable data = sender.getSerializableExtra("specialMsgs");
    if (data != null) {
        spMsgs = new Hashtable<String, String>((HashMap<String, String>)data);
        Log.i(TAG, " GOT spMsgs : Len = " + spMsgs.size());
        if (spMsgs.size() > 0) {
            java.util.Enumeration<String> keys = spMsgs.keys(); 
            while(keys.hasMoreElements()) {
                Log.i(TAG, "SP= " + spMsgs.get(keys));
            }
        }
    }

Here I get "GOT spMsgs : Len = 4. But in Log SP=, I get infinite null. Why enteries can't be found of passed Hashtable ??? What am I still missing ?

Am looking out for some guidance for this issue since last 2 days, but couldn't figure out what & how to do with this object.

Any help is highly appreciated.


回答1:


I would suggest going an alternate route and encoding the object to JSON, as it is built-in in Android from API level 1, instead of reinventing an object exchange format as you would have to if you go with Parcelable.

The problem with Serializable will be that you cannot easily add it to an Intent.




回答2:


Could finally pass the Hasttable to other Activity and got it as it is. With this, I got to do soem workigns in other Activity, but was not a bad idea or lots of code to work on. So, got it.

Thanks a lot fiddler & Peter.



来源:https://stackoverflow.com/questions/11742374/android-make-this-object-as-parcelable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!