首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在微调器中获取所选项目的第一个和最后一个连接字符串?

如何在微调器中获取所选项目的第一个和最后一个连接字符串?
EN

Stack Overflow用户
提问于 2017-11-10 19:35:59
回答 4查看 51关注 0票数 0

我在我的微调器中添加了一个适配器,代码如下:

代码语言:javascript
运行
复制
ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter(this, 
                android.R.layout.simple_spinner_item,
                itemList);

我通过以下方式在我的项目列表中添加了项目:

代码语言:javascript
运行
复制
itemList.add(p.getCourseId()+" "+p.getRoom()+" "+p.getSection());

我的微调器中的数据显示如下:"IT117P R210 A58“、"IT200P R310 A57”、"IT500 3400 A28“,因此数据分别是: course、room和section。我需要做的是在用户单击微调器项目时仅获取课程字符串(p.getCourseId())和部分字符串(p.getSection())(不包括房间)。选择该项后,它将在另一个类上传递数据

下面是我在onCreate上的代码:

代码语言:javascript
运行
复制
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
      public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {

                    course=mySpinner.getSelectedItem().toString(); 
               //this i think will get all the string item 
              //in spinner not the course and section only:(
             //HOW to get the course and section? 

                    new Thread(new Runnable() {
                        public void run() {

                            data = bw.getAttendanceFromDB(term, course,sections);
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    ArrayList<Properties> attendanceusers = attendanceUse(data);
                                    addAttendance(attendanceusers);                     
                                }
                            });   
                        }
                    }).start();
                }

更新:下面是我的全部代码,我实现了split函数:

Courseprof.java

代码语言:javascript
运行
复制
public class Courseprof extends Activity{
String data = "";
TableLayout tl;
TableRow tr;
Button btcourse;
int term=1;
String course="",sections="";
Spinner mySpinner = (Spinner) findViewById(R.id.spincourse);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.courses);
        tl = (TableLayout) findViewById(R.id.maintable);

        final BackgroundWorker bw = new BackgroundWorker(Courseprof.this,"Courseprof");
        Bundle get=getIntent().getExtras();
        final int profid=get.getInt("id"); //kunin ni course from fragment
        new Thread(new Runnable() {
            public void run() {
                data = bw.getCourseFromDB(profid);
                System.out.println(data);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        ArrayList<Properties> courseusers = parseJSON(data);
                        addData(courseusers);                     
                    }

                });   
            }
        }).start();

        mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            String splithis;
            String[] splited=mySpinner.getSelectedItem().toString().split(" ");
            course = splited[0];
            sections = splited[2];
            new Thread(new Runnable() {
                public void run() {

                    data = bw.getAttendanceFromDB(term, course,sections);
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            ArrayList<Properties> attendanceusers = attendanceUse(data);
                            addAttendance(attendanceusers);                     
                        }
                    });   
                }
            }).start();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
            return;
        }
    });
    }
    public ArrayList<Properties> parseJSON(String result) {
        ArrayList<Properties> courseusers = new ArrayList<Properties>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Properties user = new Properties();
                user.setRoom(json_data.getString("rooms_id")); //ipinasa dito
                user.setCourse(json_data.getString("course_id"));
                user.setSection(json_data.getString("sections_id"));
                courseusers.add(user);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());  
        }
        return courseusers;
    }
    public ArrayList<Properties> attendanceUse(String result) {
        ArrayList<Properties> attendanceusers = new ArrayList<Properties>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Properties user = new Properties();
                user.setStudentfname(json_data.getString("student_fname")); //ipinasa dito
                user.setStudentmname(json_data.getString("student_mname"));
                user.setStudentlname(json_data.getString("student_lname"));
                user.setStatdescript(json_data.getString("status_description"));
                attendanceusers.add(user);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());  
        }
        return attendanceusers;
    }
    @SuppressWarnings({ "rawtypes" })
    public void addData(ArrayList<Properties> courseusers) {

        List<String> itemList=new ArrayList<String>();
        for (Iterator i = courseusers.iterator(); i.hasNext();) {
            Properties p = (Properties) i.next();
              itemList.add(p.getCourseId()+" "+p.getRoom()+" "+p.getSection());
        }
        ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter(this, 
                android.R.layout.simple_spinner_item,
                itemList);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mySpinner.setAdapter(adapter);
    }
    TextView label;
    void addHeaderAttendance(){
        /** Create a TableRow dynamically **/
        tr = new TableRow(this);

        /** Creating a TextView to add to the row **/
        label = new TextView(this);
        label.setText("Students");
        label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        label.setPadding(5, 5, 5, 5);
        label.setBackgroundColor(Color.RED);
        LinearLayout Ll = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 5, 5, 5);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(label,params);
        tr.addView((View)Ll); // Adding textView to tablerow.

        /** Creating Qty Button **/
        TextView place = new TextView(this);
        place.setText("Status");
        place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        place.setPadding(5, 5, 5, 5);
        place.setBackgroundColor(Color.RED);
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 5, 5, 5);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(place,params);
        tr.addView((View)Ll); // Adding textview to tablerow.

         // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }
    @SuppressWarnings({ "rawtypes" })
    public void addAttendance(ArrayList<Properties> attendanceusers) {
        addHeaderAttendance();

        for (Iterator i = attendanceusers.iterator(); i.hasNext();) {

            Properties p = (Properties) i.next();

            /** Create a TableRow dynamically **/
            tr = new TableRow(this);

            /** Creating a TextView to add to the row **/
            label = new TextView(this);
            label.setText(p.getStudentfname()+" "+p.getStudentlname()+" "+p.getStudentmname());

            label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            label.setPadding(5, 5, 5, 5);
            label.setBackgroundColor(Color.GRAY);
            LinearLayout Ll = new LinearLayout(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 2, 2, 2);
            //Ll.setPadding(10, 5, 5, 5);
            Ll.addView(label,params);
            tr.addView((View)Ll); // Adding textView to tablerow.

            TextView stats = new TextView(this);
            stats.setText(p.getStatdescript());
            stats.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            stats.setPadding(5, 5, 5, 5);
            stats.setBackgroundColor(Color.GRAY);
            Ll = new LinearLayout(this);
            params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 2, 2, 2);
            //Ll.setPadding(10, 5, 5, 5);
            Ll.addView(stats,params);
            tr.addView((View)Ll); // Adding textview to tablerow.

             // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
        }
    } 
}

错误如下:

代码语言:javascript
运行
复制
11-10 20:36:24.964: E/AndroidRuntime(10862): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.navigationdrawerdemo/in.wptrafficanalyzer.navigationdrawerdemo.Courseprof}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132)

11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)

11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.ActivityThread.access$1100(ActivityThread.java:229)

11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)

11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.os.Handler.dispatchMessage(Handler.java:102)

11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.os.Looper.loop(Looper.java:148)

11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.ActivityThread.main(ActivityThread.java:7406)
11-10 20:36:24.964: E/AndroidRuntime(10862):    at java.lang.reflect.Method.invoke(Native Method)
11-10 20:36:24.964: E/AndroidRuntime(10862):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
11-10 20:36:24.964: E/AndroidRuntime(10862):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
11-10 20:36:24.964: E/AndroidRuntime(10862): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.Activity.findViewById(Activity.java:2316)
11-10 20:36:24.964: E/AndroidRuntime(10862):    at in.wptrafficanalyzer.navigationdrawerdemo.Courseprof.<init>(Courseprof.java:35)
11-10 20:36:24.964: E/AndroidRuntime(10862):    at java.lang.Class.newInstance(Native Method)
11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.Instrumentation.newActivity(Instrumentation.java:1096)
11-10 20:36:24.964: E/AndroidRuntime(10862):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-11-10 19:41:33

您可以用空格拆分选定的字符串,以获得值。

代码语言:javascript
运行
复制
String[] data = mySpinner.getSelectedItem().toString().split(" ");
course = data[0];
section = data[2];
票数 0
EN

Stack Overflow用户

发布于 2017-11-10 19:40:38

你可以使用split函数

示例

代码语言:javascript
运行
复制
course=mySpinner.getSelectedItem().toString();
String[] splited = course.split(" ");

String first = splited[0];
String second = splited[1];
String last = splited[2];

你可以让微调器全局对象像这样

代码语言:javascript
运行
复制
private Spinner mySpinner;

在setContentView like之后初始化onCreate()方法中的微调函数

代码语言:javascript
运行
复制
mySpinner= (Spinner) findViewById(R.id.spincourse);
票数 0
EN

Stack Overflow用户

发布于 2017-11-10 20:00:43

您可以根据空格拆分String

代码语言:javascript
运行
复制
String selectedCource = mySpinner.getSelectedItem().toString();
String[] words = selectedCource.split("\\s");//splits the string based on whitespace 

String course = words[0];
String selection = words[2];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47221926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档