php - 如何通过android以表格格式显示访问另一个类中的微调器选定值

标签 php android mysql sql

您好,在我的应用程序中,我有两个旋转器

spinner1 类名:

Lkg
ukg
playgroup
<小时/>

spinner2:部分名称

Batch A
Batch B

现在,如果单击提交按钮,我想显示包含姓名和学号的学生表。

现在我的问题是旋转器位于第一类中,我想访问第二类中的旋转器,然后我将通过 jsonArray 传递值并以表格格式显示数据。

第一个微调表我有唯一的键作为class_id,第二个表我有唯一的键section_id和class_id作为基于这个class_id和section_id的外键我想获取学生表如果class_id和section_id存在意味着我想获取它记录一下。

参加类(class)

public class Attend extends Activity implements
        OnClickListener {

    private EditText fromDateEtxt;
    private DatePickerDialog fromDatePickerDialog;
    private SimpleDateFormat dateFormatter;
    InputStream is = null;
    String result = null;
    String line = null;
    int class_id;
    //String className = "";
    String sectionName = "";
    String[] class_name, section_name;
    Spinner classSpinner, sectionSpinner;
    private Map<String, Set<String>> classSectionMap = new HashMap<String, Set<String>>();

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        // Spinner element
        classSpinner = (Spinner) findViewById(R.id.spinner);
        sectionSpinner = (Spinner) findViewById(R.id.spinner1);
        Button submit = (Button) findViewById(R.id.button1);
        submit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(AndroidSpinnerExampleActivity.this,
                          "Result : " +
                          "\nclassName : "+ String.valueOf(classSpinner.getSelectedItem()) +
                          "\nSectionName : "+ String.valueOf(sectionSpinner.getSelectedItem()), 

                          Toast.LENGTH_SHORT).show();
                Intent i = new Intent(getApplicationContext(), Attend1.class);
                startActivity(i);



            }
        });

        dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);

        findViewsById();

        setDateTimeField();
        // Spinner click listener
        // spinner.setOnItemSelectedListener(this);

        // Spinner Drop down elements
        final List<String> list1 = new ArrayList<String>();
        final List<String> list2 = new ArrayList<String>();

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://10.0.2.2/android_connect/getuser.php");
            HttpResponse response = httpclient.execute(httppost);
            Log.e("Fail 1", "3");

            HttpEntity entity = response.getEntity();
            Log.e("Fail 1", "4");

            is = entity.getContent();
            Log.e("Pass 1", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
                    Toast.LENGTH_LONG).show();
            finish();
        }

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

        try {
            JSONArray JA = new JSONArray(result);
            JSONObject json = null;

            class_name = new String[JA.length()];
            section_name = new String[JA.length()];

            String className = "";
            String sectionName = "";
            Set<String> sections;
            for (int i = 0; i < JA.length(); i++) {

                json = JA.getJSONObject(i);
                // class_name[i] = json.getString("class_name");
                // section_name[i]=json.getString("section_name");
                className = json.getString("class_name");

                sectionName = json.getString("section_name");
                //Toast.makeText(getApplicationContext(), "classname"+sectionName, Toast.LENGTH_LONG).show();
                if (classSectionMap.containsKey(className)) {
                    sections = classSectionMap.get(className);
                } else {
                    sections = new HashSet<String>();
                    //Toast.makeText(getApplicationContext(), "classname"+className, Toast.LENGTH_LONG).show();
                }
                sections.add(sectionName);
                classSectionMap.put(className, sections);
            }
            Set<String> classKeys = classSectionMap.keySet();
            class_name = classKeys.toArray(new String[classKeys.size()]);
            Set<String> sectionkeys = classSectionMap.get(class_name[0]);
            if (sectionkeys != null) {
                section_name = sectionkeys.toArray(new String[sectionkeys
                        .size()]);
            }

            /*
             * for(int i=0;i<class_name.length;i++) { list1.add(class_name[i]);
             * list2.add(section_name[i]);
             * 
             * }
             */

            spinner_fn();

        } catch (Exception e) {

            Log.e("Fail 3", e.toString());
            e.printStackTrace();
            // login.this.finish();

        }
    }

    private void spinner_fn() {
        // TODO Auto-generated method stub

        ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_spinner_item,
                class_name);
        dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        classSpinner.setAdapter(dataAdapter1);



        classSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long id) {

                Log.e("Position new", class_name[position]);
                Set<String> sectionkeys = classSectionMap
                        .get(class_name[position]);
                if (sectionkeys != null) {
                    section_name = sectionkeys.toArray(new String[sectionkeys
                            .size()]);
                    //Toast.makeText(getApplicationContext(), "sectionName"+section_name, Toast.LENGTH_LONG).show();
                }
                ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(
                        getApplicationContext(), android.R.layout.simple_spinner_item,
                        section_name);
                dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                sectionSpinner.setAdapter(dataAdapter2);


            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }

        });

        sectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1,
                    int position, long arg3) {

                // TODO Auto-generated method stub

                // spinner.setSelection(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

    }

    private void findViewsById() {
        fromDateEtxt = (EditText) findViewById(R.id.etxt_fromdate);
        fromDateEtxt.setInputType(InputType.TYPE_NULL);
        fromDateEtxt.requestFocus();

        // toDateEtxt = (EditText) findViewById(R.id.etxt_todate);
        // toDateEtxt.setInputType(InputType.TYPE_NULL);
    }

    private void setDateTimeField() {
        fromDateEtxt.setOnClickListener(this);
        // toDateEtxt.setOnClickListener(this);

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

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

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

    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onClick(View view) {
        if (view == fromDateEtxt) {
            fromDatePickerDialog.show();
        }

    }

参加1.class

public class Attend1 extends Activity {

    String data = "";
    TableLayout tl;
    TableRow tr;
    TextView label;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tl = (TableLayout) findViewById(R.id.maintable);

        final DataseData getdb = new DataseData();
        new Thread(new Runnable() {
            public void run() {
                data = getdb.getDataFromDB();
                System.out.println(data);

                runOnUiThread(new Runnable() {

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

            }
        }).start();
    }

    public ArrayList<Users> parseJSON(String result) {
        ArrayList<Users> users = new ArrayList<Users>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Users user = new Users();
                user.setId(json_data.getInt("class_name"));
                user.setClass_id(json_data.getInt("section_name"));
                user.setSection_id(json_data.getInt("section_id"));
                user.setName(json_data.getString("student_name"));
                user.setPassword(json_data.getString("rollno"));
                users.add(user);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());  
        }
        return users;
    }

    void addHeader(){

        tr = new TableRow(this);


        label = new TextView(this);
        label.setText("StudentName");
        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.addView(label,params);
        tr.addView((View)Ll); 


        TextView password = new TextView(this);
        password.setText("RollNo");
        password.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        password.setPadding(5, 5, 5, 5);
        password.setBackgroundColor(Color.RED);
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 5, 5, 5);

        Ll.addView(password,params);
        tr.addView((View)Ll); 


        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

    @SuppressWarnings({ "rawtypes" })
    public void addData(ArrayList<Users> users) {

        addHeader();

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

            Users p = (Users) 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.getName());
            label.setId(p.getId());
            label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            label.setPadding(5, 5, 5, 5);

            LinearLayout Ll = new LinearLayout(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 2, 2, 2);

            Ll.addView(label,params);
            tr.addView((View)Ll);


            TextView password = new TextView(this);
            password.setText(p.getPassword());
            password.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            password.setPadding(5, 5, 5, 5);

            Ll = new LinearLayout(this);
            params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 3, 3, 3);

            Ll.addView(password,params);
            tr.addView((View)Ll); 


            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
        }
    }

DataseData.class

public class DataseData {
    HttpPost httppost;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    Spinner classSpinner, sectionSpinner;
    public String getDataFromDB() {
        try {

            HttpPost httppost;
            HttpClient httpclient;
            httpclient = new DefaultHttpClient();
            httppost = new HttpPost(
                    "http://10.0.2.2/android_connect/save.php"); 

            nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("username",(String) classSpinner.getAdapter().getItem(classSpinner.getSelectedItemPosition())));  // $Edittext_value = $_POST['Edittext_value'];
            nameValuePairs.add(new BasicNameValuePair("password",(String) sectionSpinner.getAdapter().getItem(sectionSpinner.getSelectedItemPosition())));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            response=httpclient.execute(httppost);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost,
                    responseHandler);

            return response.trim();

        } catch (Exception e) {
            System.out.println("ERROR : " + e.getMessage());
            return "error";
        }
    }

保存.php

<?php

    mysql_connect("localhost","root",""); 
    mysql_select_db("login");

    $q=mysql_query("SELECT * from student");

    while($row=mysql_fetch_assoc($q))
            $json_output[]=$row;

    print(json_encode($json_output));

    mysql_close();

?>

最佳答案

试试这个。

发送值到下一个 Activity (最好作为 Activity 调用)

submit.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
 // here AndroidSpinnerExampleActivity.this has to be replaced with Attend.this
            Toast.makeText(AndroidSpinnerExampleActivity.this,
                      "Result : " +
                      "\nclassName : "+ String.valueOf(classSpinner.getSelectedItem()) +
                      "\nSectionName : "+ String.valueOf(sectionSpinner.getSelectedItem()), 


                      Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getApplicationContext(), Attend1.class);
            // here your sending the values to next class (better call as activity)
            i.putExtra("class_name",classSpinner.getSelectedItem());
            i.putExtra("section_name",sectionSpinner.getSelectedItem());

            startActivity(i);



        }
    });

接收 Activity

public class Attend1 extends Activity {

String data = "";
TableLayout tl;
TableRow tr;
TextView label;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tl = (TableLayout) findViewById(R.id.maintable);
 Toast.makeText(this,
                      "Result : " +
                      "\nclassName : "+ getIntent().getStringExtra("class_name") +
                      "\nSectionName : "+ getIntent().getStringExtra("section_name") , 

                      Toast.LENGTH_SHORT).show();

    final DataseData getdb = new DataseData();
    new Thread(new Runnable() {
        public void run() {
            data = getdb.getDataFromDB();
            System.out.println(data);

            runOnUiThread(new Runnable() {

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

        }
    }).start();
}

关于php - 如何通过android以表格格式显示访问另一个类中的微调器选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931406/

相关文章:

MySQL 错误似乎无法修复 : Index column size too large

java - 使用 JSON 和 MySql 使用 Android 应用程序检索数据

php - 在本地主机上使用Apache的Docker php:ERR_SSL_PROTOCOL_ERROR

php - 将外部 pdf 文档加载到 div 中

php - 异常后如何在长时间运行的进程中使用 Doctrine Entity Manager

php - mySQL bool 全文搜索不返回任何结果

java - 在Android中用手指旋转3D对象

android - Android编程中如何使用接近传感器

mysql - 当选择字段使用条件时对其进行索引?

android - 如何调试 "DialogError: The connection to the server was unsuccessful"错误?