使用共享首选项将数据发送到另一个活动

时间:2014-01-03 03:53:12

标签: java android android-intent sharedpreferences

我做了什么 ::

您可以清楚地看到我使用意图将数据从BLD_IndividualListOfItems_Starters发送到ResultActivity ...看起来像是一个集合


我想要实现的目标 :: 我希望使用shared preferences来实现相同的输出....这意味着在BLD_IndividualListOfItems_Starters我想要添加数据&在ResultActivity中,我想使用共享首选项

来检索它

我需要对代码进行哪些更改


BLD_IndividualListOfItems_Starters.java

public class BLD_IndividualListOfItems_Starters extends Activity{
    // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapterForAtomicListItemtype adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String NAME = "rank";
        Button btn;

        String TYPE_FILTER;

        StringBuilder result;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.listview_main);

            TYPE_FILTER = getIntent().getExtras().getString("key_title");
            Log.v("---- Value-Start---", TYPE_FILTER);
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);

            btn = (Button) findViewById(R.id.button1);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    result = new StringBuilder();
                    for (int i = 0; i < arraylist.size(); i++) {
                        if (adapter.mysparse.get(i) == true) {

                            result.append(arraylist.get(i).get(BLD_IndividualListOfItems_Starters.NAME));
                            result.append("\n");
                        }

                    }
                    Intent n = new Intent(BLD_IndividualListOfItems_Starters.this, ResultActivity.class);
                    n.putExtra("buffer", result.toString());
                    startActivity(n);
                }
            });

            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }

        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
                // Set progressdialog title
                //mProgressDialog.setTitle("Fetching the information");
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();

                String newurl = "?" + "Key=" + TYPE_FILTER;


                // Retrieve JSON Objects from the given URL address
                jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);

                try {
                    // Locate the array name in JSON
                    jsonarray = jsonobject.getJSONArray("restaurants");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put(BLD_IndividualListOfItems_Starters.NAME, jsonobject.getString("MasterListMenuName"));

                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
    }

ListViewAdapterForAtomicListItemtype.java

public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements OnCheckedChangeListener {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();
    SparseBooleanArray mysparse;

    public ListViewAdapterForAtomicListItemtype(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        mysparse = new SparseBooleanArray(data.size());
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView name;
        CheckBox chk;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
        chk = (CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);


        // Capture position and set results to the TextViews
        name.setText(resultp.get(BLD_IndividualListOfItems_Starters.NAME));

        chk.setTag(position);
        chk.setChecked(mysparse.get(position, false));
        chk.setOnCheckedChangeListener(this);

        return itemView;
    }

    public boolean isChecked(int position) {
        return mysparse.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mysparse.put(position, isChecked);

    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        mysparse.put((Integer) buttonView.getTag(), isChecked);
    }
}

ResultActivity.java

public class ResultActivity extends Activity {

    ListView lv;
    ArrayList<String> myList;
    String myName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        Intent n = getIntent();
        myName = n.getStringExtra("buffer");

        myList = new ArrayList<String>();

        lv = (ListView) findViewById(R.id.listViewData);

        myList.add(myName);

        ArrayAdapter<String> adapter=new ArrayAdapter<String>(ResultActivity.this,R.layout.custom_single_list,R.id.textView1, myList);

        lv.setAdapter(adapter);

    }

}

6 个答案:

答案 0 :(得分:2)

如果您想在多个活动中使用ArrayList<HashMap<String, String>>,那么最好将其另存为应用级别,您可以使用Application class

下面是您研究的示例代码..

<强> MyApplication.java

public class MyApplication extends Application {

    ArrayList<HashMap<String, String>> arraylist;

    @Override
    public void onCreate() {

        super.onCreate();
    }

    public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
    {
        arraylist = setData;
    }

    public ArrayList<HashMap<String, String>> getArrayListMapData()
    {
        return arraylist;
    }
}

<强> MyActivity.java

public class MyActivity extends Activity {

    ArrayList<HashMap<String, String>> arraylist;
    MyApplication mApplication;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mApplication = (MyApplication)getApplication();

        //how to assign list data
        mApplication.setArrayListMapData(arraylist);


        //how to get same list data
        arraylist = mApplication.getArrayListMapData();

        super.onCreate(savedInstanceState);
    }
}

您可以使用相同的代码在多个活动中获取相同的列表..

注意:不要忘记在menifest.xml

中注册课程
   <application
    android:name="com.android.app.MyApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
      > ..................

此处 com.android.app 是包名称, MyApplication 是类名。

答案 1 :(得分:1)

设置数据:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("key", "value").commit();

阅读数据:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String value = prefs.getString("key", null);

答案 2 :(得分:0)

onClick btn的{​​{1}}中:

而不是

OnClickListener

尝试

n.putExtra("buffer", result.toString());

然后在ResultActivity中:

而不是

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("buffer", result.toString()).commit();

尝试

 Intent n = getIntent();
 myName = n.getStringExtra("buffer");

答案 3 :(得分:0)

public class SessionManager {
    // Shared Preferences
    SharedPreferences pref;

    // Editor for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREF_NAME = "demo";


    // Constructor
    public SessionManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }



    /**
     * Set and get User Data
     */
    public void setUserData(String userData) {
        // Storing name in pref
        editor.putString("userData", userData);
        editor.commit();
    }

    public String getUserData() {
        return pref.getString("userData", null);
    }
    }

在第一项活动中设置您的数据

SessionManager s = new SessionManager(this);

s.setUserData( “MYDATA”);

在另一项活动中获取您的数据

SessionManager s = new SessionManager(this);

String data_String = s.getUserData();

答案 4 :(得分:0)

为了您的关注尝试这样的事情

用于将文本输入到sharedPrefernces

中的EditText
SharedPreferences spppp = getSharedPreferences("tab", 0);
SharedPreferences.Editor editors = spppp.edit();
editors.putString("for", "you_value");
editors.commit();

获取另一项活动的价值

SharedPreferences spppp = getSharedPreferences("tab", 0);
String get_value = spppp.getString("for" , "");

干杯

答案 5 :(得分:0)

这是全局共享首选项,可在整个应用程序中使用。您可以访问任何组件或任何类

PreferenceManager manager = (PreferenceManager) PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            SharedPreferences.Editor editor = null;

插入值

editor = manager.getSharedPreferences().edit();
            editor.putString("key", "value");

获取价值

SharedPreferences preferences = manager.getSharedPreferences();
            preferences.getString("key", "value");