如何根据两个不同活动中其他旋转器的位置来更改旋转器的位置

2024-01-01

我在两个不同的活动中有两个 Android 微调器下拉列表。但是两个微调器都具有来自同一源的相同数据。我想根据第一个活动的位置更改第二个活动的位置。如何解决此问题?

更新的代码:

第一个活动:

public class ServiceRequest extends BaseActivity implements OnItemClickListener {
    private List<Item> customerList = new ArrayList<Item>();
    private SpinnerAdapter adapter;
    public static final String EXTRA_INTENT_CUSTOMER_LIST  ="extra_intent_customer_list";

    public static final String EXTRA_INTENT_SELECTED_ITEM = "extra_intent_selected_item";
    private List<Item> items;
    Spinner spin;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLayoutInflater().inflate(R.layout.service_request, frameLayout);

       ;


    );
                    System.out.println("Selected item "    Button login = (Button) findViewById(R.id.booking);

        final String message = autoCompView.getText().toString();
        //Create the bundle


        login.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
{

                    if(customerList.isEmpty()) return;
                    Item selectedItem = (Item) spin.getSelectedItem();
                    spin.getSelectedItem().toString(+selectedItem);

              Intent intent = new Intent(ServiceRequest.this, Form.class);
//            intent.putExtra(EXTRA_INTENT_CUSTOMER_LIST, (Serializable) customerList);
                    intent.putExtra("seletedItem", selectedItem);
                    intent.putExtra(EXTRA_INTENT_SELECTED_ITEM, selectedItem);
                    startActivity(intent);
                }
            }

        });

        spin = (Spinner) findViewById(R.id.service_spinner);
        adapter = new SpinnerAdapter((ArrayList<Item>) customerList, this);
        spin.setAdapter(adapter);
    }


    public void onStart(){
        super.onStart();
        BackTask bt=new BackTask();
        bt.execute();
    }
    private class BackTask extends AsyncTask<Void,Void,ArrayList<Item>> {
        ArrayList<String> list;
        protected void onPreExecute(){
            super.onPreExecute();
            list=new ArrayList<>();
        }
        protected ArrayList<Item> doInBackground(Void... params) {
            InputStream is = null;
            String result = "";
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://my_url/Service.asmx/GetServiceList");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                // Get our response as a String.
                is = entity.getContent();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
                is.close();
                //result=sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // parse json data
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject obj = jArray.getJSONObject(i);
                    Item customer = new Item();
                    customer.setId(obj.getString("ServiceId"));
                    customer.setName(obj.getString("ServiceName"));

                    // adding movie to movies array
                    customerList.add(customer);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
//            adapter.notifyDataSetChanged();
            return null;
        }
        @Override
        protected void onPostExecute(ArrayList<Item> customerList) {
            if(customerList != null && !customerList.isEmpty()){
                adapter.updateDate(customerList);
            }
        }

    }}

第二个活动代码

     public class Form extends BaseActivity {

    //    ArrayList<String> listItems = new ArrayList<>();
//    ArrayAdapter<String> adapter;
    private ArrayList<Item> customerList = new ArrayList<Item>();
    private SpinnerAdapter adapter;
    private List<Item> items;

    AdapterView.OnItemSelectedListener listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLayoutInflater().inflate(R.layout.activity_form, frameLayout);

        if(getIntent().hasExtra(ServiceRequest.EXTRA_INTENT_SELECTED_ITEM)){
            selectedItem = (Item)getIntent().getSerializableExtra(ServiceRequest.EXTRA_INTENT_SELECTED_ITEM);
        }


        service_need = (Spinner) findViewById(R.id.service_need);
        adapter = new SpinnerAdapter(customerList, this);
        service_need.setAdapter(adapter);
       /*  Commented by me
       if(selectedItem != null){
            service_need.setSelection(customerList.indexOf(selectedItem));
        }*/




        /*
        Commented for testing :Praveen
        Bundle bundle = getIntent().getExtras();
        String stuff1 = bundle.getString("local");*/
        autoCompView.setText("stuff1");
//        position = customerList.indexOf(bundle.getString("name"));
//        spin.setSelection(position);
//        adapter.notifyDataSetChanged();
//        adapter.notifyDataSetChanged();

//        String name = bundle.getString("name");
//        adapter.add(name);


    }

    public void onStart() {
        super.onStart();
        BackTask bt = new BackTask();
        bt.execute();
    }

    private class BackTask extends AsyncTask<Void, Void, ArrayList<Item>> {
        ArrayList<String> list;

        protected void onPreExecute() {
            super.onPreExecute();
//            list = new ArrayList<>();

        }

        protected ArrayList<Item> doInBackground(Void... params) {
            InputStream is = null;
            String result = "";
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://my_url/Service.asmx/GetServiceList");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                // Get our response as a String.
                is = entity.getContent();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
                is.close();
                //result=sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // parse json data
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject obj = jArray.getJSONObject(i);
                    Item customer = new Item();
                    customer.setId(obj.getString("ServiceId"));
                    customer.setName(obj.getString("ServiceName"));
                    customerList.add(customer);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
//            adapter.notifyDataSetChanged();
            return null;
        }

        @Override
        protected void onPostExecute(ArrayList<Item> customerList) {
            if(customerList != null && !customerList.isEmpty()){
                adapter.updateDate(customerList);
                if(selectedItem != null){
                    spin.setSelection(customerList.indexOf(selectedItem));
                }
            }
        }
    }


}

模型类

public class Item implements Serializable {
    String id;
    String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Item item = (Item) o;

        if (getId() != item.getId()) return false;
        return getName().equals(item.getName());

    }
}

适配器类

public class SpinnerAdapter extends BaseAdapter {

    ArrayList<Item> categories = new ArrayList<>();
    Context mContext;

    public SpinnerAdapter(ArrayList<Item> categories, Context context){
        this.categories = categories;
        mContext = context;
    }

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

    @Override
    public Object getItem(int i) {
        return categories.get(i);
    }

    @Override
    public long getItemId(int i) {
        return categories.get(i).hashCode();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        Item item = categories.get(i);
        ViewHolder holder = null;
        if(view == null){
            view = LayoutInflater.from(mContext).inflate(R.layout.spin_row, null);
            holder = new ViewHolder();
            holder.name = (TextView) view.findViewById(R.id.name);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        holder.name.setText(item.getName());
        return view;
    }

    static class ViewHolder{
        TextView name;
    }

}

JSON 响应

[{"ServiceId":"1","ServiceName":"AC"},
{"ServiceId":"5","ServiceName":"Plumbing"},
{"ServiceId":"3","ServiceName":"Refrigerator"},
{"ServiceId":"7","ServiceName":"Appliances"},
{"ServiceId":"27","ServiceName":"Others"}]

您可以使用 2 个主题来解决此问题。

  1. 共享偏好

  2. Intent

共享偏好

存储 Spinner 数组的位置。

当您再次使用 时,获取该位置并将其设置为 Spinner。

例子:-

用于将位置保存或存储到 SharePrefernce 中。

int position = spin.getSelectedItemPosition() ;
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("position",position ).commit();

用于从 SharePrefernce 向 Spinner 获取或设置值。

int position = PreferenceManager.getDefaultSharedPreferences(this).getInt("position", 0);
spin.setSelection(position);

Intent

将Spinner数组的位置存储在intent中。

当您再次使用 Intent 时,获取位置并将其设置为 Spinner 。

例子:-

用于保存或将位置存储到 Intent 中。

int position = spin.getSelectedItemPosition() ;
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("position", position);
startActivity(myIntent);

用于从 Intent 向 Spinner 获取或设置值。

Intent mIntent = getIntent();
int position = mIntent.getIntExtra("position", 0);
spin.setSelection(position);

这两者都有效。我已经检查过了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据两个不同活动中其他旋转器的位置来更改旋转器的位置 的相关文章

随机推荐

  • 使用 InAppBrowser 处理从远程网页直接发送到应用程序的事件

    我想从我的 cordova 应用程序打开一个外部 Web 应用程序 并直接在本机应用程序上处理 Web 应用程序事件 例如 当加载特定 URL 时 应用程序应通过调用函数来处理它 有谁知道这是否可能 是的 确实可以使用 InAppBrows
  • distplot/kdeplot如何计算kde曲线?

    我正在使用seaborn 来绘制数据 一切都很好 直到我的导师问我下面的代码中的情节是如何制作的 import numpy as np import seaborn as sns import matplotlib pyplot as pl
  • Mediastyle 通知在 Android 11 中不起作用

    我的自定义媒体样式通知在 Android 11 中不再适用于我的音乐应用 在 Android 10 及之前的版本中运行良好 我是否需要添加任何其他代码才能使其在 Android 11 中运行 我应该补充一点 摆脱 setMediaSessi
  • Windows 上的 java 堆栈转储

    我在标准 Windows 命令窗口中有一个正在运行的 java 进程 即我已经运行 cmd 并输入 java jar 如果可能的话 我需要能够获得所有线程的完整堆栈转储 我记得在 Linux 下你可以通过 quit 命令上的选项向 JVM
  • 隐藏警告的杂注:where 条件中使用的字段可能包含空值

    我正在寻找一个编译指示 可以用来隐藏当选择的 WHERE 条件中使用的字段可能包含数据库中的 NULL 值时生成的编译器警告 阅读 SAP note 1088403 后 我知道这里可能存在问题 但我无法应用那里建议的解决方案 因为我在 WH
  • Instagram 有分享按钮吗? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我已经用谷歌搜索了几个小时 但没有在网络上找到任何与 Instagram 共享按钮相关的文章和文档 有还是没有 您无法使用 API 在 I
  • laravel file_get_contents 路线没有得到响应

    我有一条路线 Route group array prefix gt playlist function Route get raw id array as gt rawPlaylist uses gt PlaylistsControlle
  • React Native - ReactNavigation.addNavigationHelpers 不是函数

    我使用的是react navigation 1 2 1 当我将react navigation更新到2 0 0时 一切都工作正常 但出现以下错误 知道为什么会这样吗 React Navigation add 导航助手不是一个函数 impor
  • 其他开发团队如何处理版本号?

    我们的应用程序已经相当成熟 因此我们的版本已经达到了 16 但是 这可能会给人留下该软件已经过时且脱节的印象 有多少商业应用程序的版本为 20 显然 版本号是相当任意的 其他人使用什么 我非常喜欢 Ubuntu 的 Month date 方
  • Scala Slick 表继承

    我以这种方式实现 SQL 表继承 Table Shape Column Type shape id integer square foat name character varying 64 Table Triangle Column Ty
  • 有没有一种方法可以在不发送测试邮件的情况下测试电子邮件地址是否存在? [复制]

    这个问题在这里已经有答案了 可能的重复 如何在不发送电子邮件的情况下检查电子邮件地址是否存在 https stackoverflow com questions 565504 how to check if an email address
  • Windows Azure 多重部署

    这是场景 太多的网站具有相同的源代码和自己的数据库 每个客户都有自己的系统和自己的数据库 但所有客户都使用相同的源代码 我只有一个 TFS 项目 因为所有客户都使用相同的代码 不是物理上的 因为我必须在每个网站上部署到每个客户 问题 我如何
  • 运输例外

    我正在尝试导入 happybase 但在连接时收到以下错误消息 我已经运行了 Hadoop 伪节点集群和 Hbase 安装的组件版本如下 Hadoop 版本 1 0 4 Hbase 版本 0 94 4 快乐基地 0 4 有人可以查看下面的例
  • R 编程:自动合并字符串

    我正在尝试自动化这里工作的一些系统 专门用于根据调查数据生成报告 假设我对 1 个问题有 3 条评论 current comments lt c too slow not fast enough bad speed 基本上我想要做的是将注释
  • 如何从 servlet 调用 EJB 3.1 非零参数构造函数?

    我有一个 login java servlet 正如其名称所示 它为我的 Web 应用程序提供登录功能 我是一名新手 正在使用 EJB 3 1 和 EE 6 在我的 LoginBean java EBJ 中 我有一个无参数构造函数和另一个具
  • 在android中动态创建活动

    android 如何从 android 清单文件注册一个活动 以便它出现在包管理器中 我确实明白这是在安装应用程序时完成的 有没有办法调整 android 源代码来创建 API 来动态创建和注册活动 android如何从android清单文
  • 以计数作为标签的 2D 摘要图

    我有一个数量的测量值 value 在特定点 lon and lat 如下面的示例数据 library ggplot2 set seed 1 dat lt data frame lon runif 1000 1 15 lat runif 10
  • 有没有办法在 Swift 中重写数组到字符串的转换?

    我正在尝试使用 Swift 让它看起来更 动态类型 只是为了好玩 没有预期的生产价值 现在我陷入了将内置类型转换为的覆盖行为String 例如 我想看到这个输出Array let nums 1 2 3 print nums I m an a
  • 码头工人。没有这样的文件或目录

    我有一些文件 我想将它们移动到 Docker 容器中 但最后 docker 找不到文件 本地计算机上包含文件的文件夹位于 home katalonne flask4 文件结构如果重要的话 The Dockerfile First Flask
  • 如何根据两个不同活动中其他旋转器的位置来更改旋转器的位置

    我在两个不同的活动中有两个 Android 微调器下拉列表 但是两个微调器都具有来自同一源的相同数据 我想根据第一个活动的位置更改第二个活动的位置 如何解决此问题 更新的代码 第一个活动 public class ServiceReques