从微调器中选择项目后如何显示数据库数据?

时间:2016-04-12 06:43:45

标签: android

我想在reg_farmer表中显示人员详细信息。如果我从微调器中选择一个项目,我想显示与数据库中该项目相对应的数据。

这是我的Android MainActivity.class文件..

public class MainActivity extends AppCompatActivity {

//Declaring an Spinner
private Spinner spinner,spinner2;

//An ArrayList for Spinner Items
private ArrayList<String> states;
private ArrayList<String> district;

//JSON Array
private JSONArray States;
private JSONArray District;


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

    //Initializing the ArrayList
    states = new ArrayList<String>();
    district = new ArrayList<String>();

    //Initializing Spinner
    spinner = (Spinner) findViewById(R.id.spinner);
    spinner2 = (Spinner) findViewById(R.id.spinner2);

    //Adding an Item Selected Listener to our Spinner
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String sid="";
            try {
                //Getting object of given index
                JSONObject json = States.getJSONObject(position);

                //Fetching id from that object
                sid = json.getString("id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            getDistrict(sid);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Toast.makeText(MainActivity.this,"Nothing Selected",Toast.LENGTH_SHORT).show();
        }
    });

    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String Dname="";
            try {
                //Getting object of given index
                JSONObject json = District.getJSONObject(position);

                //Fetching name from that object
                Dname = json.getString("dname");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Toast.makeText(MainActivity.this,Dname,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Toast.makeText(MainActivity.this,"Empty",Toast.LENGTH_SHORT).show();

        }
    });

    //This method will fetch the States data from the URL
   getStates();

}

private void getStates(){
    //Creating a string request
    StringRequest stringRequest = new StringRequest(Request.Method.POST,Config.DATA_State,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        States = j.getJSONArray("States");


                        for(int i=0;i< States.length();i++){
                            try {
                                //Getting json object
                                JSONObject state = States.getJSONObject(i);

                                //Adding the name of the state to array list
                                MainActivity.this.states.add(state.getString("name"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        //Setting adapter to show the items in the spinner
                        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, states));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            });

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void getDistrict(final String sid){
    //Creating a string request
    StringRequest dRequest = new StringRequest(Request.Method.POST,Config.DATA_District,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        Log.i("tagconvertstr", "[" + response + "]");
                        j = new JSONObject(response);

                        boolean error = j.getBoolean("error");

                        // Check for error node in json
                        if (!error) {
                            //Storing the Array of JSON String to our JSON Array
                            District = j.getJSONArray("District");

                            //Toast.makeText(MainActivity.this, District.toString(), Toast.LENGTH_SHORT).show();
                            district.removeAll(district);
                            for (int i = 0; i < District.length(); i++) {
                                try {
                                    //Getting json object
                                    JSONObject dist = District.getJSONObject(i);
                                    //Adding the name of the district to array list
                                    MainActivity.this.district.add(dist.getString("dname"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            //Setting adapter to show the items in the spinner
                            spinner2.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, district));
                        }else {

                            String errorMsg = j.getString("error_msg");
                            Toast.makeText(MainActivity.this,
                                    errorMsg, Toast.LENGTH_LONG).show();
                        }
                        } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("state_id", sid);
            return params;
        }

    };

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(dRequest);
}
}

这是我的Config.java文件..在这个文件中,我给出了获取微调器项目的URL ..

public class Config {
//JSON URL
public static final String DATA_State = "http://10.0.3.2/cof/state.php";
public static final String DATA_District = "http://10.0.3.2/cof/district.php";

}

我想显示这样的详细信息..我想查看人物的代码,姓名和手机号码,当我从微调器中选择区域和状态时 I want to display the details like this.. I want to view code,name and mobile number of the person when i choose the district and state from the spinner

2 个答案:

答案 0 :(得分:0)

我猜您正在尝试与本地数据库通信。从永恒数据库获取数据需要3个步骤。

  1. 创建数据库 - 它可以是本地使用像wamp这样的服务,也可以存在于实际服务器上。

  2. 创建webservice - 在此步骤中,您需要创建一个Webservice,它与您的数据库交互并响应您的Android代码。它包括制作配置。 php文件存储您的服务器&amp;数据库信息,然后你有你的实际anyname.php文件,其中包括config.php文件,从数据库获取数据的代码,并回复到Android应用程序。

  3. 从android调用webservice - 在这一步中,您实际上是从代码中调用webservice来从中检索数据。

  4. 现在我们可以从您提供的代码中看到。您可能已完成大部分或全部步骤。据我说你准备好了你的数据库。您已经显示了包含两个php文件的config文件夹,这些文件显示您已准备好php文件。

    现在要调试,首先尝试在浏览器中打开链接,看看是否有任何结果。如果您正确获取信息,则表示您已正确放置文件。现在尝试在logcat中打印volley的结果,看看你的应用程序中是否有数据。如果一切正常,那么你只需要处理微调器监听器。如果这些步骤中的任何一个失败,请告诉我们。

答案 1 :(得分:0)

首先,您必须检索所有数据,然后将它们添加到数组列表中,以便再次获取信息,

您可以查看该示例,它确实可以满足您的要求,

def decompose(amount, bills, lst = None):  # fix here - supply the possible bills as well
    lst = lst or []
    if amount == 0:                      # fix - when amount == 0 you are done
        return lst

    if amount >= bills[0]:      # fix - as long as bills[0] can be deducted, do so (>=)
        lst += [bills[0]]       # bill[0] is already addded no need to do below again
        amount = amount - bills[0]
        return decompose(amount, bills, lst ) # fix - supply same bills, 
    return decompose(amount, bills[1:], lst ) # fix - bill[0] too big, supply bills[1:]

bills = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
print(decompose(523, bills)) 

现在将数据添加到数组中之后,您可以使用此方法

[500, 20, 2, 1]

当然不要忘记在onCreate中添加此行

 private void retrieveJSON() {


    StringRequest stringRequest = new StringRequest(
            Request.Method.GET,
            URLstring,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    Log.d("strrrrr", ">>" + response);

                    try {

                        JSONObject obj = new JSONObject(response);
                        goodModelArrayList = new ArrayList<>();

                            JSONArray dataArray  = obj.getJSONArray("data");

                            for (int i = 0; i < dataArray.length(); i++) {



                                PMenus playerModel = new PMenus();

                                JSONObject dataobj = dataArray.getJSONObject(i);



                                playerModel.setName(dataobj.getString("name"));
                                playerModel.setCountry(dataobj.getString("country"));
                                playerModel.setCity(dataobj.getString("city"));
                                playerModel.setImgURL(dataobj.getString("imgURL"));



                                goodModelArrayList.add(playerModel);



                            }
                            for (int i = 0; i < goodModelArrayList.size(); i++){
                                names.add(goodModelArrayList.get(i).getName().toString());
                            }

                            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(AddPatient.this, simple_spinner_item, names);
                            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
                            PmSpinner.setAdapter(spinnerArrayAdapter);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

    // request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);


}

并这样定义

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String item = parent.getItemAtPosition(position).toString() ;
            String city = goodModelArrayList.get(position).getCity().toString() ;
            String country = goodModelArrayList.get(position).getCountry().toString() ;



            testnotes.setText(item);
            testno.setText(city);
            testprice.setText(country);


        }