如何使用httpUrlConnection将ANDROID中的列表<string>发送到PHP,然后将此字符串拆分为服务器端的字符串数组?

时间:2016-06-09 13:35:19

标签: php android json android-asynctask httpurlconnection

“Teacher_Main”,此活动包含所选学生的list<String>个。我将此列表转换为JSONArray,然后将此json数组转换为字符串,然后将此字符串传递给public class BackgroundWorker_Teacher_Main extends AsyncTask<String,Void,String>。这里是Teacher_Main活动,如下所示。

public class Teacher_Main extends AppCompatActivity {
        ConnectionChecker connectionChecker;
        Spinner T_CLASS, T_COURSE;
        ListView T_LIST_VIEW;
        String t_id, t_class, t_course, s_reg_number;
        List<String> selectedStudentsList;
        String selectedStudent;

AlertDialog.Builder alertDialog;
public int count = 0, len = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_teacher__main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    t_id = getIntent().getStringExtra("teacherID");
    T_CLASS = (Spinner) findViewById(R.id.selectClass);
    T_COURSE = (Spinner) findViewById(R.id.selectCourse);
    T_LIST_VIEW = (ListView) findViewById(R.id.listView);
    selectedStudentsList = new ArrayList<String>();


    T_LIST_VIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectedStudent = ((TextView) view).getText().toString();
            if (selectedStudentsList.contains(selectedStudent)) {
                selectedStudentsList.remove(selectedStudent);
            } else {
                selectedStudentsList.add(selectedStudent);
            }
        }
    });
       }

public void markClicked(View view) {
    if (connectionChecker.isConnection()) {
        markAttendance();
    }
}

private void markAttendance() {       
    String message="Adding please wait..";
    String[] array=getArrayFromList(selectedStudentsList);
    len=array.length;
    JSONArray jsonArray=new JSONArray(selectedStudentsList);

    String dataToSend=jsonArray.toString();
    BackgroundWorker_Teacher_Main backgroundWorker_teacher_main=new BackgroundWorker_Teacher_Main(this,T_CLASS,T_COURSE,T_LIST_VIEW,array,message);
    backgroundWorker_teacher_main.execute("markAttendance", t_id, t_class, t_course,dataToSend);

}

将字符串传递给public class BackgroundWorker_Teacher_Main extends AsyncTask<String,Void,String>后,我获取Teacher_Main通过params传递的所有值,然后使用httpUrlConnection将此字符串发送到PHP-Server。以下是public class BackgroundWorker_Teacher_Main extends AsyncTask<String,Void,String>

的代码
public class BackgroundWorker_Teacher_Main extends AsyncTask<String,Void,String> {
    Context ctx;
    Spinner T_CLASS,T_COURSE;
    ListView T_LIST_VIEW;
    String[] list;
    String message;
    String method;
    ProgressDialog progressDialog;
    AlertDialog.Builder alertDialog;



    public BackgroundWorker_Teacher_Main(Context ctx, Spinner t_CLASS, Spinner t_COURSE, ListView t_LIST_VIEW,String[] array, String message)
    {
        this.ctx = ctx;
        T_CLASS = t_CLASS;
        T_COURSE = t_COURSE;
        T_LIST_VIEW = t_LIST_VIEW;
        this.list=array;
        this.message = message;
    }

    @Override
    protected void onPreExecute()
    {
        progressDialog=new ProgressDialog(ctx);
        progressDialog.setTitle("Progress");
        progressDialog.setMessage(message);
        progressDialog.setIcon(R.drawable.app_icon);
        progressDialog.setCancelable(true);
        progressDialog.show();

        alertDialog=new AlertDialog.Builder(ctx)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        alertDialog.create();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params)
    {
        method=params[0];
        String markAttendanceUrl="http://10.0.2.2/AndroidAttendanceSystem/Teacher_Main/mark_attendance.php";

        if(method.equals("markAttendance"))
        {
            String t_id,t_class,t_course,t_student_reg;
            t_id=params[1];
            t_class=params[2];
            t_course=params[3];
            t_student_reg=params[4];
            try {
                URL url=new URL(markAttendanceUrl);
                String data = URLEncoder.encode("method", "UTF-8") + "=" + URLEncoder.encode(method, "UTF-8") + "&" +
                        URLEncoder.encode("teacherID", "UTF-8") + "=" + URLEncoder.encode(t_id, "UTF-8")+"&"+
                        URLEncoder.encode("teacherClass","UTF-8")+"="+ URLEncoder.encode(t_class,"UTF-8")+"&"+
                        URLEncoder.encode("teacherCourse","UTF-8")+"="+URLEncoder.encode(t_course,"UTF-8")+"&"+
                        URLEncoder.encode("studentRegNumber","UTF-8")+"="+URLEncoder.encode(t_student_reg,"UTF-8");
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);


                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));


                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));

                String returnedMessage = "";
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    returnedMessage += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return returnedMessage;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        progressDialog.dismiss();

        if(method.equals("markAttendance"))
        {
            alertDialog.setMessage(result);
            alertDialog.show();
        }
        super.onPostExecute(result);
    }
}

在服务器端,我的字符串看起来像['RYK2012','BWP2012','PAK2016']。如何从服务器端的此字符串中获取数组。字符串数组应包含

arr[0]=>RYK2012
arr[1=>BWP2012
arr[2]=>PAK2016
.
.

实际上我想将这些值存储到数据库中,为此需要数组字符串值。 我的PHP-Code如下所示

<?php
require "init_connection.php";
method=$_POST["method"];
$t_id=$_POST["teacherID"];
$t_class=$_POST["teacherClass"];
$t_course=$_POST["teacherCourse"];
$s_reg_number=$_POST["studentRegNumber"];

print($s_reg_number);
?>

0 个答案:

没有答案