本文介绍了使用共享preferences将数据发送到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了什么

正如你可以清楚地看到我从 BLD_IndividualListOfItems_Starters 使用意图将数据发送到 ResultActivity ...看起来像它集合


我想实现 ::
我想用达到相同的输出共享preferences ....在 BLD_IndividualListOfItems_Starters 意味着我要添加数据&安培;在 ResultActivity 我想用共享preferences检索它


在code什么样的变化,我应该需要做


BLD_IndividualListOfItems_Starters.java

 公共类BLD_IndividualListOfItems_Starters延伸活动{
    //声明变量
        的JSONObject的JSONObject;
        JSONArray jsonarray;
        ListView控件列表视图;
        ListViewAdapterForAtomicListItemtype适配器;
        ProgressDialog mProgressDialog;
        ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
        静态字符串NAME =等级;
        按钮BTN;        串TYPE_FILTER;        StringBuilder的结果;        @覆盖
        公共无效的onCreate(捆绑savedInstanceState){
            super.onCreate(savedInstanceState);
            //从listview_main.xml视图
            的setContentView(R.layout.listview_main);            TYPE_FILTER = getIntent()getExtras()的getString(key_title)。。
            Log.v(----价值开始---,TYPE_FILTER);
            //定位listview_main.xml列表视图
            列表视图=(ListView控件)findViewById(R.id.listview);            BTN =(按钮)findViewById(R.id.button1);
            btn.setOnClickListener(新OnClickListener(){                @覆盖
                公共无效的onClick(视图v){
                    // TODO自动生成方法存根                    结果=新的StringBuilder();
                    的for(int i = 0; I< arraylist.size();我++){
                        如果(adapter.mysparse.get(我)==真){                            result.append(arraylist.get(I)获得(BLD_IndividualListOfItems_Starters.NAME));
                            result.append(\\ n);
                        }                    }
                    意图N =新意图(BLD_IndividualListOfItems_Starters.this,ResultActivity.class);
                    n.putExtra(缓冲,result.toString());
                    startActivity(N);
                }
            });            //执行DownloadJSON的AsyncTask
            新DownloadJSON()执行();
        }        // DownloadJSON的AsyncTask
        私有类DownloadJSON扩展的AsyncTask<太虚,太虚,太虚> {            @覆盖
            在preExecute保护无效(){
                super.on preExecute();
                //创建一个progressdialog
                mProgressDialog =新ProgressDialog(BLD_IndividualListOfItems_Starters.this);
                //设置progressdialog称号
                //mProgressDialog.setTitle(\"Fetching信息);
                //设置progressdialog消息
                mProgressDialog.setMessage(正在加载...);
                mProgressDialog.setIndeterminate(假);
                //显示progressdialog
                mProgressDialog.show();
            }            @覆盖
            保护无效doInBackground(虚空...... PARAMS){
                //创建一个数组
                ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();                字符串NEWURL =? +键=+ TYPE_FILTER;
                //从给定的URL地址JSON对象
                的JSONObject = JSONfunctions.getJSONfromURL(http://54.218.73.244:7005/RestaurantAtomicListItemType/+ NEWURL);                尝试{
                    //找到在JSON数组名
                    jsonarray = jsonobject.getJSONArray(餐馆);                    的for(int i = 0; I< jsonarray.length();我++){
                        HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                        的JSONObject = jsonarray.getJSONObject(ⅰ);
                        // Retrive JSON对象
                        map.put(BLD_IndividualListOfItems_Starters.NAME,jsonobject.getString(MasterListMenuName));                        //设置JSON对象到数组
                        arraylist.add(地图);
                    }
                }赶上(JSONException E){
                    Log.e(错误,e.getMessage());
                    e.printStackTrace();
                }
                返回null;
            }            @覆盖
            保护无效onPostExecute(无效参数){
                //将结果传递到ListViewAdapter.java
                适配器=新ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this,ArrayList的);
                //适配器设置到ListView
                listview.setAdapter(适配器);
                //关闭progressdialog
                mProgressDialog.dismiss();
            }
        }
    }

ListViewAdapterForAtomicListItemtype.java

 公共类ListViewAdapterForAtomicListItemtype扩展BaseAdapter实现OnCheckedChangeListener {    //声明变量
    上下文语境;
    LayoutInflater吹气;
    ArrayList的<&HashMap的LT;字符串,字符串>>数据;
    HashMap的<字符串,字符串> resultp =新的HashMap<字符串,字符串>();
    SparseBooleanArray mysparse;    公共ListViewAdapterForAtomicListItemtype(上下文的背景下,
            ArrayList的<&HashMap的LT;字符串,字符串>>数组列表){
        this.context =背景;
        数据=数组列表;
        mysparse =新SparseBooleanArray(data.size());
    }    @覆盖
    公众诠释的getCount(){
        返回data.size();
    }    @覆盖
    公共对象的getItem(INT位置){
        返回null;
    }    @覆盖
    众长getItemId(INT位置){
        返回0;
    }    公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
        //声明变量
        TextView的名称;
        复选框CHK;        吹气=(LayoutInflater)上下文
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);        查看ItemView控件= inflater.inflate(R.layout.listview_item_for_atomic_list_item_type,父母,假);
        //获取位置
        resultp = data.get(位置);        //定位listview_item.xml的TextViews
        名字=(TextView中)itemView.findViewById(R.id.textView_id_atomic_list_item_type);
        CHK =(复选框)itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);
        //捕捉位置,并设置结果向TextViews
        name.setText(resultp.get(BLD_IndividualListOfItems_Starters.NAME));        chk.setTag(位置);
        chk.setChecked(mysparse.get(位置,FALSE));
        chk.setOnCheckedChangeListener(本);        返回ItemView控件;
    }    公共布尔器isChecked(INT位置){
        返回mysparse.get(位置,FALSE);
    }    公共无效setChecked(INT位置,布尔器isChecked){
        mysparse.put(位置,器isChecked);    }    公共无效切换(INT位置){
        setChecked(位置,器isChecked(位置)!);    }    @覆盖
    公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
        // TODO自动生成方法存根
        mysparse.put((整数)buttonView.getTag(),器isChecked);
    }
}

ResultActivity.java

 公共类ResultActivity延伸活动{    LV的ListView;
    ArrayList的<串GT; myList中;
    串MYNAME;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.second);        意向N = getIntent();
        MYNAME = n.getStringExtra(缓冲区);        myList中=新的ArrayList<串GT;();        LV =(ListView控件)findViewById(R.id.listViewData);        myList.add(MYNAME);        ArrayAdapter<串GT;适配器=新ArrayAdapter<串GT;(ResultActivity.this,R.layout.custom_single_list,R.id.textView1,myList中);        lv.setAdapter(适配器);    }}



解决方案

如果你想使用的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.

这篇关于使用共享preferences将数据发送到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 02:31