从mysql数据库中填充两个相互依赖的微调器

时间:2012-06-22 22:06:47

标签: android mysql

我有两个旋转器一个用于省,另一个用于城市,如果我在省旋转器中选择豪登,第二个旋转器必须显示约翰内斯堡,比勒陀利亚,百夫长,如果我在省选择KZN,我希望第二个旋转器显示Petermaritsburg,Durban,乌伦迪

这是我尝试使用的代码,但根本没有工作。我会帮助您提供帮助

int ct_id;
    String[] ct_name = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.extras);

        provins = (Spinner) findViewById(R.id.spinprovince);
        city = (Spinner) findViewById(R.id.spincity);

        save = (Button) findViewById(R.id.btnsave);

            String result = null;
            InputStream is = null;
            StringBuilder sb = null;
            // http post
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2/php/ttz.php");
                // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection" + e.toString());
            }
            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");
                String line = "0";
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            // paring data
            JSONArray jArray;
            try {
                jArray = new JSONArray(result);
                JSONObject json_data = null;
                ct_name = new String[jArray.length()];
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    ct_id = json_data.getInt("idprovince");
                    ct_name[i] = json_data.getString("provincename");


        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,ct_name);

         aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    provins.setAdapter(aa);


                }
            } catch (JSONException e1) {
                Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG)
                        .show();
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
}

}

2 个答案:

答案 0 :(得分:1)

试试此代码......

    public class MainActivity extends Activity {
InputStream is=null;
String result=null;
String line=null;

String[] roll_no,name;  

Spinner spinner1,spinner2;



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

spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
final List<String> list1 = new ArrayList<String>();
final List<String> list2 = new ArrayList<String>();

Button b=(Button) findViewById(R.id.button1);

b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v)
{
                // TODO Auto-generated method stub

try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/spinner.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;
roll_no = new String[JA.length()];       
name = new String[JA.length()];

for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
roll_no[i] = json.getString("roll_no");
name[i]=json.getString("name");
}
Toast.makeText(getApplicationContext(), "sss",Toast.LENGTH_LONG).show();

for(int i=0;i<roll_no.length;i++)
{
list1.add(roll_no[i]);
list2.add(name[i]);
}

spinner_fn();

}
catch(Exception e)
{

Log.e("Fail 3", e.toString());
//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, roll_no);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter1);


ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getApplicationContext(),
                                android.R.layout.simple_spinner_item, name);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter2);


spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{
// TODO Auto-generated method stub

spinner2.setSelection(position);

}

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

});


spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub

spinner1.setSelection(position);

}

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

}

别忘了给予Androidmanifest权限:

 <uses-permission android:name="android.permission.INTERNET"/>

你的spinner.php文件:

  <?php
$host='127.0.0.1';
$uname='root'_name;
$pwd='password';
$db='android';
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$r=mysql_query("select * from class",$con);
while($row=mysql_fetch_array($r))
{
$cls[]=$row;
//echo $fin."<br>";
}
print(json_encode($cls));
mysql_close($con);
?>

答案 1 :(得分:0)

请参阅this tutorial如何从下拉菜单中获取MYSQL中的数据 [来自PHP和MySQL的DropDownList / Android Spinner使用JSON