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

时间:2017-11-10 11:35:59

标签: java android eclipse

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

ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter(this, 
                android.R.layout.simple_spinner_item,
                itemList);

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

itemList.add(p.getCourseId()+" "+p.getRoom()+" "+p.getSection());

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

这是我在onCreate上的代码:

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

更新:这是我的整个代码,我实现了分割功能:

Courseprof.java

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

这是错误:

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)

4 个答案:

答案 0 :(得分:0)

您可以使用拆分功能

实施例

course=mySpinner.getSelectedItem().toString();
String[] splited = course.split(" ");

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

您可以将旋转器全局对象设为

private Spinner mySpinner;

在setContentView之后在onCreate()方法中初始化微调器

mySpinner= (Spinner) findViewById(R.id.spincourse);

答案 1 :(得分:0)

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

String[] data = mySpinner.getSelectedItem().toString().split(" ");
course = data[0];
section = data[2];

答案 2 :(得分:0)

您可以根据空格分割String

String selectedCource = mySpinner.getSelectedItem().toString();
String[] words = selectedCource.split("\\s");//splits the string based on whitespace 

String course = words[0];
String selection = words[2];

答案 3 :(得分:0)

尝试这个,

String[] data = mySpinner.getSelectedItem().toString().split(" ");
course = data[0];
section = data[data.length-1];