java - 如何将旋转器中选取的文本放入字符串中并在其他类中使用

标签 java android mysql android-spinner getstring

我想要做的是在微调器中选择文本并将其保存到 mysql 数据库中。我需要一些帮助,因为我不知道如何传递字符串并在从微调器获取字符串后在另一个类中使用它。以下是add_blood_glucose_record.java中的代码:

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class AddBloodGlucoseRecord extends AppCompatActivity implements View.OnClickListener {
    Button btnSelectDate,btnSelectTime;
    private EditText editDate;
    //private EditText editTime;

    private DatePickerDialog DatePickerDialog;
    //private TimePickerDialog TimePickerDialog;

    private SimpleDateFormat dateFormatter;
    Spinner spinner;
    private EditText editPatientID;
    private EditText edit_sugar_con;
    String pid,sgrcon,measured,date,selection;

private String mItemSelectedMessageTemplate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_blood_glucose_record);


        mItemSelectedMessageTemplate =
                getString(R.string.spinner_message_template);
        Spinner spinner = (Spinner) findViewById(R.id.measured_time);

        spinner.setOnItemSelectedListener(new SpinnerInfo());



        dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.TRADITIONAL_CHINESE);
        findViewsById();

        setDateTimeField();

        editPatientID = (EditText) findViewById(R.id.editPatientID);
        edit_sugar_con = (EditText) findViewById(R.id.edit_sugar_con);
    }


    private void findViewsById() {
        btnSelectDate=(Button)findViewById(R.id.edit_date);
        btnSelectDate.requestFocus();
        //editDate.setInputType(InputType.TYPE_NULL);
        //editDate.requestFocus();

       // editTime = (EditText) findViewById(R.id.edit_time);
       // editTime.setInputType(InputType.TYPE_NULL);
    }


    private void setDateTimeField() {
        btnSelectDate.setOnClickListener(this);
        //editTime.setOnClickListener(this);

        Calendar newCalendar = Calendar.getInstance();
        DatePickerDialog = new DatePickerDialog(this, new android.app.DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                btnSelectDate.setText(dateFormatter.format(newDate.getTime()));
            }

        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    }

        /**TimePickerDialog = new TimePickerDialog(this, new android.app.TimePickerDialog.OnTimeSetListener(){
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                Calendar newTime = Calendar.getInstance();
                newTime.set(hourOfDay, minute);
                editTime.setText(newTime.getTime());
            }

        },newCalendar.get(Calendar.HOUR_OF_DAY), newCalendar.get(Calendar.MINUTE));
    }
         **/

    private void showToast(String text) {

        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }


public class SpinnerInfo implements AdapterView.OnItemSelectedListener {
    private boolean isFirst = true;
    @Override
    public void onItemSelected(AdapterView<?> spinner, View selectedView,
                               int selectedIndex, long id) {
        if (isFirst) {
            isFirst = false;
        } else {

            String selection =
                    //spinner.getItemAtPosition(selectedIndex).toString();
                    spinner.getSelectedItem().toString();
            String message =
                    String.format(mItemSelectedMessageTemplate, selection);
            showToast(message);
        }
    }


    @Override
    public void onNothingSelected(AdapterView<?> spinner) {
// Won’t be invoked unless you programmatically remove entries
    }
}

然后,我使用以下代码将字符串传递给BackgroundTask.java,以便在插入按钮onClick 时将数据添加到mysql 数据库中。到目前为止,这部分工作起来就像一个魅力,我可以将正常的 editText 值传递给字符串。我不知道的是如何将微调器中选择的文本传递给BackgroundTask.java

public void insert(View view){
    pid = editPatientID.getText().toString();
    if(pid.equals(""))
    {
        Toast.makeText(this, "Please enter patient id!", Toast.LENGTH_LONG).show();
        return;
    }

    sgrcon = edit_sugar_con.getText().toString();
    if(sgrcon.equals(""))
    {
        Toast.makeText(this, "Please enter sugar concentration!", Toast.LENGTH_LONG).show();
        return;
    }
    date = btnSelectDate.getText().toString();


    measured = spinner.getSelectedItem().toString();

    String method = "save";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method,pid,sgrcon,date,measured);

}

我是编码和 Android 开发的新手。非常感谢您的帮助!!

BackgroundTask.java:


    public class BackgroundTask extends AsyncTask<String,Void,String> {
        AlertDialog alertDialog;
        Context ctx;
        BackgroundTask(Context ctx)
        {
            this.ctx =ctx;
        }




        @Override
        protected void onPreExecute() {
            alertDialog = new AlertDialog.Builder(ctx).create();
            alertDialog.setTitle("");
        }





        @Override
        protected String doInBackground(String... params) {


            String save_url = "http://192.168.php";
            //String login_url = "http://10.0.2.2/webapp/login.php";
            String method = params[0];
            if (method.equals("save")) {
                String pid = params[1];
                String sgrcon = params[2];
                String date = params[3];

                try {
                    URL url = new URL(save_url);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    //httpURLConnection.setDoInput(true);
                    OutputStream OS = httpURLConnection.getOutputStream();
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                    String data = URLEncoder.encode("pid", "UTF-8") + "=" + URLEncoder.encode(pid, "UTF-8") + "&" +
                            URLEncoder.encode("sgrcon", "UTF-8") + "=" + URLEncoder.encode(sgrcon, "UTF-8") + "&" +
                            URLEncoder.encode("date", "UTF-8") + "=" + URLEncoder.encode(date, "UTF-8")+
RLEncoder.encode("measured", "UTF-8") + "=" + URLEncoder.encode(measured, "UTF-8") +
                            URLEncoder.encode("time", "UTF-8") + "=" + URLEncoder.encode(date, "UTF-8");
                    bufferedWriter.write(data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    OS.close();
                    InputStream IS = httpURLConnection.getInputStream();
                    IS.close();
                    //httpURLConnection.connect();
                    httpURLConnection.disconnect();
                    return "Data is added to patient's profile!!";
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            return null;
        }
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
        @Override
        protected void onPostExecute(String result) {
            if(result.equals("Data is added to patient's profile!!"))
            {
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();


            }
            else
            {
                alertDialog.setMessage(result);
                alertDialog.show();
            }
        }
    }

运行时出错:

01-15 10:34:46.657  14570-14570/com.example.rex.patient4 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.rex.patient4, PID: 14570
    java.lang.IllegalStateException: Could not execute method for android:onClick
            at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:278)
            at android.view.View.performClick(View.java:4764)
            at android.view.View$PerformClick.run(View.java:19844)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
            at android.view.View.performClick(View.java:4764)
            at android.view.View$PerformClick.run(View.java:19844)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.widget.Spinner.getSelectedItem()' on a null object reference
            at com.example.rex.patient4.AddBloodGlucoseRecord.insert(AddBloodGlucoseRecord.java:163)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
            at android.view.View.performClick(View.java:4764)
            at android.view.View$PerformClick.run(View.java:19844)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

最佳答案

将字符串selection声明为公共(public),然后将其传递到后台,就像传递editext字符串一样。

关于java - 如何将旋转器中选取的文本放入字符串中并在其他类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34756949/

相关文章:

java - jBPM 5.4 与 Tomcat 7 和 MySQL

android - 在 AsyncTask onPostExecute 中使用 canvas.drawBitmap

java - SQLite select 不适用于Where 子句

php - 数据库切片密码的最后两个字符(?!)

java - 如何设置 JCheckBox 有复选标记,或者不在程序中

java -/bin/sh :/usr/jdk64/jdk1. 7.0_45/bin/java: 无法执行二进制文件

PHP 和 MYSQL 空白结果。脚本突然停止。无错误日志

PHP 无限重复第一个 MySQL 结果

java - 使用 JVM 内存默认值运行 Java Web 应用程序

java - 从BroadcastReciever内部的startActivityForResult获取结果,调用ACTION_INSTALL_PACKAGE Intent