如何获取日期值并使用json android将其发送到服务器?

时间:2016-12-29 04:42:42

标签: android json datepicker

我正在制作注册表格,我必须把用户日期并保存在数据库中。我是android的新手,所以我不知道如何将日期选择器放在edittext上并将日期选择器的值发送到server..kindly解决我的问题..

这是我的Registartion.java

public class RegistrationForm extends AppCompatActivity {

    EditText fn,ln,mb,em,pw,cpw,dob,gen;
    Switch sw;
    RadioGroup male,feml;
    Switch swth;
    private ProgressDialog pDialog;



    private static String url_create_book = "http://cloud.....com/broccoli/creatinfo.php";

    // JSON Node names
    // JSON Node names
    private static final String TAG_SUCCESS = "success";


String rval;

    JSONParser jsonParser = new JSONParser();
    private int serverResponseCode = 0;
    Context c;
    int i=0;


    Button sub;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_form);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        fn=(EditText)findViewById(R.id.fnm) ;
        ln=(EditText)findViewById(R.id.lnm) ;
        mb=(EditText)findViewById(R.id.mobile) ;
        em=(EditText)findViewById(R.id.email) ;
        pw=(EditText)findViewById(R.id.pass) ;
        cpw=(EditText)findViewById(R.id.cpass) ;


        RadioButton male=(RadioButton)findViewById(R.id.rgm) ;

        RadioButton feml=(RadioButton)findViewById(R.id.rgf) ;

        Switch swth=(Switch)findViewById(R.id.mySwitch) ;



        RadioGroup rgrp=(RadioGroup)findViewById(R.id.rg);

        RadioButton radioButton;





        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        sub=(Button)findViewById(R.id.sub2);




        sub.setOnClickListener(new View.OnClickListener() {



            @Override
            public void onClick(View v) {
                RadioGroup rgrp=(RadioGroup)findViewById(R.id.rg);

                RadioButton radioButton;

                int selectedId = rgrp.getCheckedRadioButtonId();

                // find the radiobutton by returned id
                radioButton = (RadioButton) findViewById(selectedId);
                rval=radioButton.getText().toString();
                Toast.makeText(RegistrationForm.this,
                        rval, Toast.LENGTH_SHORT).show();


                new CreateNewProduct().execute();



                // startActivity(new Intent(RegistrationForm.this, Home.class));


            }
        });


    }







    class CreateNewProduct extends AsyncTask<String, String, String> {
        private  String fname;
        private  String lname;
        private  String email;
        private  String passwrd;
        private  String cpasswrd;



        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(RegistrationForm.this);
            pDialog.setMessage("Creating books..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            fname = fn.getText().toString();
            lname = ln.getText().toString();
            email = em.getText().toString();
            passwrd=pw.getText().toString();
            cpasswrd=cpw.getText().toString();
        }




        protected String doInBackground(String... args) {


            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("First_Name", fname));
            params.add(new BasicNameValuePair("Last_Name",lname));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("Gender", rval));
            params.add(new BasicNameValuePair("password", passwrd));
            params.add(new BasicNameValuePair("confirmPasw",cpasswrd));


            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_book,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), Login.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }

这是我的xml:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.zeba.broccoli.Login">




<!-- Registration Form -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="20dip"
            android:orientation="vertical"
            android:layout_marginTop="20dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true">
            <!-- Full Name Label -->

            <EditText android:id="@+id/fnm"

                android:hint="First Name"
                android:layout_width="fill_parent"
                android:background="@drawable/rounded_edittext"
                android:layout_height="40dp"
                android:paddingLeft="5dp"
                android:layout_marginTop="30dp"

                android:layout_marginBottom="20dip"/>

            <EditText android:id="@+id/lnm"

                android:hint="Last Name"
                android:layout_width="fill_parent"
                android:background="@drawable/rounded_edittext"
                android:layout_height="40dp"
                android:paddingLeft="5dp"

                android:layout_marginBottom="20dip"/>


            <EditText android:id="@+id/mobile"
                android:layout_width="fill_parent"

                android:layout_height="40dp"
                android:paddingLeft="5dp"
                android:background="@drawable/rounded_edittext"
                android:hint="Mobile Number"
                android:layout_marginBottom="20dip"/>
            <!-- Password Label -->


            <EditText android:id="@+id/email"
                android:layout_width="fill_parent"
                android:hint="Email"
                android:layout_height="40dp"
                android:paddingLeft="5dp"
                android:background="@drawable/rounded_edittext"

                android:layout_marginBottom="20dip"/>

            <EditText android:id="@+id/pass"
                android:layout_width="fill_parent"
                android:hint="password"
                android:inputType="textPassword"
                android:layout_height="40dp"
                android:paddingLeft="5dp"
                android:background="@drawable/rounded_edittext"

                android:layout_marginBottom="20dip"/>
            <!-- Register Button -->



            <EditText android:id="@+id/cpass"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:paddingLeft="5dp"
                android:inputType="textPassword"
                android:background="@drawable/rounded_edittext"
                android:hint="Confirm password"
                android:layout_marginBottom="20dip"/>


            <EditText android:id="@+id/dob"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:paddingLeft="5dp"
                android:background="@drawable/rounded_edittext"
                android:hint="Date of Birth(Optional)"
                android:layout_marginBottom="20dip"/>
            <!-- Register Button -->


            <!-- Link to Login Screen -->


            <TextView
                android:id="@+id/gen"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dip"
                android:text="Gender"
                android:textSize="18dp"/>


            <RelativeLayout

                android:layout_width="match_parent"
                android:layout_height="match_parent"

                tools:context=".MainActivity"
                >
                <RadioGroup
                    android:id="@+id/rg"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    >
                    <RadioButton
                        android:id="@+id/rgm"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:checked="true"

                        android:layout_weight="1"
                        android:textSize="14dp"
                        android:text="Male"
                        />
                    <RadioButton
                        android:id="@+id/rgf"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:checked="false"

                        android:layout_weight="1"
                        android:textSize="14dp"
                        android:text="Female"
                        />
                </RadioGroup>
            </RelativeLayout>



            <View
                android:layout_width="fill_parent"
                android:layout_height="2dp"
                android:background="#c0c0c0"/>



            <TextView android:id="@+id/rupdates"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dip"
                android:layout_marginBottom="20dip"
                android:text="Receive updates on offers, promotions and discounts"
                android:gravity="center"
                android:textSize="20dip"
                />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity"
                android:padding="5dp">

                <TextView android:id="@+id/sms"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dip"
                    android:text="Subscribe to sms"

                    android:textSize="20dip"
                    />

                <Switch
                    android:id="@+id/mySwitch"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_alignParentRight="true" />


                <Button
                    android:id="@+id/sub2"
                    style="?android:textAppearanceSmall"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="40dp"
                    android:text="Submit"
                    android:background="@drawable/mybutton"

                    android:textColor="#fff"
                    android:textStyle="bold"
                    android:elevation="0dp" />


            </RelativeLayout>






        </LinearLayout>
        <!-- Registration Form Ends -->
</ScrollView>
请尝试通过我的编码给出答案

2 个答案:

答案 0 :(得分:1)

我不太了解NameValuePair将数据发送到服务器,因为它现在已经取消了... 您可以使用库将数据发送到服务器,该服务器由谷歌名称 VOLLEY LIBRARY

提供

使用排球你需要将它添加到你的应用程序leve gradle dependencies

compile 'com.android.volley:volley:1.0.0'

并将数据发送到服务器,就像这种格式......

ProgressDialog progress=new ProgressDialog(mContext, R.style.MyProgressDialog);
    progress.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
    progress.show();
    StringRequest stringRequest = new StringRequest(Request.Method.POST, PROJECT_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    progress.dismiss();
                    if (response.trim().equals("success")) {
                        Toast.makeText(mContext, "Project Sucessfully Send", Toast.LENGTH_LONG).show();

                    } else {
                        Toast.makeText(mContext, response, Toast.LENGTH_LONG).show();

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progress.dismiss();
                    Toast.makeText(mContext, error.toString(), Toast.LENGTH_LONG).show();

                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<>();
            map.put("teacher-email", teacheremail);
            map.put("teacher-name", teachername);
            map.put("student-id", id);
            map.put("student-name",to);
            map.put("title",title);
            map.put("message", message);
            map.put("project-url", project);
            map.put("status",status);
            map.put("startdate",startdate);
            map.put("enddate",enddate);
            return map;
        }

DATE PICKER

您可以像这样添加日期选择器

Editext et=(Editext)findViewByID(your id);
et.setOnClickListener(new View.OnClickListener(){
     @Override
        public void onClick(View v) {
               int mYear, mMonth, mDay;
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                et.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
            }
        }, mYear, mMonth, mDay);
        //forsetting minimum date for selection
        datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis()); //optional for setting min date
        datePickerDialog.show();
        }
}

<强>更新

在您的值/样式

上添加此项
<style name="datepicker" parent="@android:style/Theme.Holo.Light.Dialog">
    <!---TODO-->
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:focusedMonthDateColor">@android:color/holo_red_dark</item>
</style>

并通过更改此

将此主题添加到您的日期选择器
DatePickerDialog datePickerDialog = new DatePickerDialog(mContext,R.style.datepicker, new DatePickerDialog.OnDateSetListener() 

答案 1 :(得分:0)

日期选择器的代码

的xml:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="date"
        android:ems="12"
        android:id="@+id/date"
        android:focusable="false"
        android:textSize="14dp" />

的java:

    Calendar myCalendar = Calendar.getInstance();

    EditText date = (EditText) findViewById(R.id.date);

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String myFormat = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

            date.setText(sdf.format(myCalendar.getTime()));
        }

    };

    date.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new DatePickerDialog(Activity.this, date, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

现在要将数据发送到服务器,你的网址就像http://www.domain.com/path/.../creatinfo.php所以要将数据发送到服务器上的那个php文件,使用下面的代码 params.add(new BasicNameValuePair("confirmPasw",cpasswrd)); myCode Goes here return null;

mycode的:

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.domain.com/path/.../creatinfo.php");
            httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

        InputStream iss = entity.getContent();
        } catch(Exception e) {
            Log.e("pass 2", "Connection Error");
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader
                    (new InputStreamReader(iss,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");
            iss.close();
            result = sb.toString();
        } catch(Exception e) {
            e.printStackTrace();
        }

        try {
            JSONObject json_data = new JSONObject(result);
            code=(json_data.getInt("code"));

            if(code==1){
                done = 1; //values saved to database and returned success
            }
            else
                done = 0; //values not saved to database and returned fail
        } catch(Exception e) {
            e.printStackTrace();
        }