开发者

how can using shared preferences string values in surface view class in Android

开发者 https://www.devze.com 2023-03-05 02:54 出处:网络
i am implementing one game application in this application i am using shared preferences in preferences Activity

i am implementing one game application in this application i am using shared preferences in preferences Activity

spinnerTheme.setOnItemSelectedListener(new OnItemSelectedListener(){ 
  SharedPreferences prefs1 = getSharedPreferences("TipCalcPreferenceDatabase", 0);
    Editor e = prefs1.edit(); 

    public void onItemSelected(AdapterView parent,View v,int position,long id)
  {
            prefs = getSharedPreferences("TipCalcPreferenceDatabase", 0);
            Editor e = prefs.edit(); 
            String str;
            if(position==0)
            {
                str=  String.valueOf((R.drawable.image1));
                e.putString("TipCalcPropertyName", str); 

           }
            if(position==1)
          {
                 str=  String.valueOf((R.drawable.image2));
                 e.putString("TipCalcPropertyName", str); 

            }
            else if(position==2)
          { 
                str=  String.valueOf((R.drawable.ballon_background));
            e.putString("TipCalcPropertyName", str); 

        }
         e.commit();

            /* Preferences current Theme update  START*/
                String mySetting = prefs.getString("TipCalcPropertyName", "");
                LinearLayout ln=(LinearLayout) findViewById(R.id.LinearLayout);
                ln.setBackgroundResource((int) Double.parseDouble(mySetting) );


  }
    public void onNothingSelected(AdapterView<?> arg0) 
    {
        开发者_运维问答    // TODO Auto-generated method stub
    }
});

above sharedprefrences how can implementing in surface view class

this is the surface class initialize() abstract method extends to layout class

public void initialize() 
    {
        int n;
       Bitmap background;
        // Screen size
      Log.v("height",scwidth+"is width and height is "+scheight);


        background=getImage(R.drawable.image1);

        background = background.createScaledBitmap(background,scwidth,scheight, true);
}

below xml file is surface view

<com.softwares.bird.BirdGame xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_absolute"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FF000000" android:orientation="horizontal">


</com.softwares.bird.BirdGame>

this shared prefrences values how can pass surface view class forward valuable suggestion i am struck in this issue in more days thanks in advance


I actually had this issue and since my application wants to store a more complex object I did this I took the object serialized it then stored it to a file. I can then check from any activity this file and get the full object. No need to use the string key garbage of prefs and Bundles.

/**
 * @param act - current activity calling the function
 * @return false if global Object not set and the dat file is not there or empty 
 */
public static void setInFile(Activity act, Object_VO obj) {

    ((Object) act.getApplication()).setObjectState(obj);

    String ser = SerializeObject.objectToString(obj);
    if (ser!= null && !ser.equalsIgnoreCase("")) {
        SerializeObject.WriteSettings(act, ser, "android.dat");
    } else {
        SerializeObject.WriteSettings(act, "", "android.dat");
    }

}

You will need this to serialize and deserialize:

/**
 * Take an object and serialize and then save it to preferences
 *
 */
 public class SerializeObject {

/**
 * Create a String from the Object using Base64 encoding
 * @param object - any Object that is Serializable
 * @return - Base64 encoded string.
 */
public static String objectToString(Serializable object) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        new ObjectOutputStream(out).writeObject(object);
        byte[] data = out.toByteArray();
        out.close();

        out = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(out,0);
        b64.write(data);
        b64.close();
        out.close();

        return new String(out.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * Creates a generic object that needs to be cast to its proper object
 * from a Base64 ecoded string.
 * 
 * @param encodedObject
 * @return
 */
public static Object stringToObject(String encodedObject) {
    try {
        return new ObjectInputStream(new Base64InputStream(
                new ByteArrayInputStream(encodedObject.getBytes()), 0)).readObject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * Save serialized settings to a file
 * @param context
 * @param data
 */
public static void WriteSettings(Context context, String data, String filename){ 
    FileOutputStream fOut = null; 
    OutputStreamWriter osw = null;

    try{
        fOut = context.openFileOutput(filename, Context.MODE_PRIVATE);       
        osw = new OutputStreamWriter(fOut); 
        osw.write(data); 
        osw.flush(); 
        //Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
    } catch (Exception e) {       
        e.printStackTrace(); 
       // Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
    } 
    finally { 
        try { 
            if(osw!=null)
                osw.close();
            if (fOut != null)
                fOut.close(); 
        } catch (IOException e) { 
               e.printStackTrace(); 
        } 
    } 
}

/**
 * Read data from file and put it into a string
 * @param context
 * @param filename - fully qualified string name
 * @return
 */
public static String ReadSettings(Context context, String filename){ 
    StringBuffer dataBuffer = new StringBuffer();
    try{
        // open the file for reading
        InputStream instream = context.openFileInput(filename);
        // if file the available for reading
        if (instream != null) {
            // prepare the file for reading
            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);

            String newLine;
            // read every line of the file into the line-variable, on line at the time
            while (( newLine = buffreader.readLine()) != null) {
                // do something with the settings from the file
                dataBuffer.append(newLine);
            }
            // close the file again
            instream.close();
        }

    } catch (java.io.FileNotFoundException f) {
        // do something if the myfilename.txt does not exits
        Log.e("FileNot Found in ReadSettings", "filename = " + filename);
    } catch (IOException e) {
        Log.e("IO Error in ReadSettings", "filename = " + filename);
    }

    return dataBuffer.toString();
}

}

and finally you need to create global object state you can reference.

package com.utils;
/**
 * Global class to hold the application state of the object
 *
 */
public class ObjectState extends Application {

private Object_VO obj;

public Object_VO getObjectState() {
    return this.obj;
}

public void setObjectState(Object_VO o) {
    this.obj = o;
}
}

Oh yeah and you need to update your AndroidManifest.xml file to include the reference to the ObjectState since it references Application like this...

    <application android:name="com.utils.ObjectState" android:icon="@drawable/icon" android:label="@string/app_name">
      <activity android:name=".MainActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号