且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用共享preferences将数据发送到另一个活动

更新时间:2023-01-08 08:12:19

如果你想使用的ArrayList< HashMap的<字符串,字符串>> 在多个活动则更好保存为应用水平这一点,你可以使用应用类

下面是样本code你的学习。

MyApplication.java

 公共类MyApplication的扩展应用{    ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;    @覆盖
    公共无效的onCreate(){        super.onCreate();
    }    公共无效setArrayListMapData(ArrayList的<&HashMap的LT;字符串,字符串>>使用setData)
    {
        ArrayList的使用setData =;
    }    公众的ArrayList<&HashMap的LT;字符串,字符串>> getArrayListMapData()
    {
        返回数组列表;
    }
}

MyActivity.java

 公共类MyActivity延伸活动{    ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
    所有MyApplication mApplication;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        mApplication =(所有MyApplication)getApplication();        //如何分配列表数据
        mApplication.setArrayListMapData(数组列表);
        //如何获得相同的列表数据
        ArrayList的= mApplication.getArrayListMapData();        super.onCreate(savedInstanceState);
    }
}

您可以在同一code多活动得到相同的列表。

注意:不要忘了在 menifest.xml

注册类
 <应用
    机器人:名字=com.android.app.MyApplication
    机器人:图标=@绘制/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
      > ..................

下面的 com.android.app 是包名和所有MyApplication 是类名。

What Have i done ::

As you can clearly see i am sending data from BLD_IndividualListOfItems_Starters to ResultActivity using intents... looks like its a collection


What i want to achieve :: I want to achieve same output using shared preferences....that means in BLD_IndividualListOfItems_Starters i want to add the data & in ResultActivity i want to retrieve it using shared preferences


What changes in code should i need to make


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);

    }

}


If you want to use ArrayList<HashMap<String, String>> in multiple activity then better to save as application level for this you can use Application class.

below is sample code for your study..

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);
    }
}

You can get same list in multiple activity with same code..

Note: don't forgot to register class in menifest.xml

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

Here com.android.app is package name and MyApplication is class name.