如何使用本地数据库中的微调器获取基于城市的信息

时间:2017-03-08 07:30:44

标签: android android-sqlite spinner android-spinner

我有来自服务器的城市和区域列表,我在本地数据库中添加了它们。现在我想显示城市从本地数据库中获取并基于本地数据库我想按城市显示区域。我已经完成了代码,但问题是我只获得了一个基于城市的区域,当我选择任何其他城市然后选择区域时它会显示我之前添加的区域。我无法正常工作。

// db的代码

       String CREATE_CITY_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CITY + "("
    + KEYCITY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + CITY_ID + " TEXT,"
    + CITY_NAME + " TEXT," + AREA_ID + " TEXT,"
    + AREA_NAME + " TEXT" + ")";
 db.execSQL(CREATE_CITY_TABLE);

//添加新城市

public void addCity(CityAreaModel cityAreaModel)
 {


    SQLiteDatabase cityDb = this.getWritableDatabase();
    ContentValues values = new ContentValues();
     values.put(CITY_ID,cityAreaModel.getCityId());
  values.put(CITY_NAME,cityAreaModel.getCityName());
  values.put(AREA_ID,cityAreaModel.getAreaId());
    values.put(AREA_NAME,cityAreaModel.getAreaName());


// Inserting Row
  cityDb.insert(TABLE_CITY, null, values);
     cityDb.close(); // Closing database connection
 }

//获取所有城市

   public List<CityAreaModel> getAllCities() {
     List<CityAreaModel> cityList = new ArrayList<CityAreaModel>();
// Select All Query
String selectQuery = "SELECT  * FROM " + TABLE_CITY;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
    do {
        CityAreaModel object = new CityAreaModel();

        object.setCityId(cursor.getString(1));
        object.setCityName((cursor.getString(2)));
        object.setAreaId(cursor.getString(3));
        object.setAreaName(cursor.getString(4));

        // Adding contact to list
        cityList.add(object);
    } while (cursor.moveToNext());
}

// return contact list
return cityList;

}

//以城市方式获取所有区域

   public List<CityAreaModel> getAllArea(String cityId) {
List<CityAreaModel> cityList = new ArrayList<CityAreaModel>();
// Select All Query
String selectQuery = "select * from " + TABLE_ADDRESS + " where " + CITY_ID + " = '" + cityId + "'";
Log.i("adressupdate",   "getAllArea() selectQuery: " + selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
    do {
        CityAreaModel object = new CityAreaModel();

        object.setCityId(cursor.getString(1));
        object.setCityName((cursor.getString(2)));
        object.setAreaId(cursor.getString(3));
        object.setAreaName(cursor.getString(4));

        // Adding contact to list
        cityList.add(object);
    } while (cursor.moveToNext());
}

// return contact list
return cityList;

}

//类的微调器的代码

      cityAreaModelsList = db.getAllCities();
    for (int i = 0; i < cityAreaModelsList.size(); i++) {
     cityList.add(cityAreaModelsList.get(i).getCityName());

      }


       cityAdapetr = new ArrayAdapter<String>(getApplicationContext(),
    android.R.layout.simple_spinner_item, cityList);
       cityAdapetr.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  select_city.setAdapter(cityAdapetr);
    select_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String cityId = (String) cityAreaModelsList.get(position).getCityId();


    areaModelList = db.getAllArea(cityId);

        List<CityAreaModel> areamodellist = new ArrayList<CityAreaModel>();
        areamodellist = db.getAllArea(cityId);

    for(int i =0;i< areamodellist.size();i++)
    {
         areaList.add(areamodellist.get(i).getAreaName());
    }


        areaAdapter = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_spinner_item, areaList);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        select_location.setAdapter(areaAdapter);


}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

});

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

  String  areaName = (String) areaList.get(position);
    if(areaName.equals("Select Location"))
    {
        areaId = "0";
    }

    else{



        areaId = (String) areaList.get(position);

        if(areaName.equals("Vasundhara Enclave"))
        {
            areaId = "1";
        }
        else if(areaName.equals("New Ashok Nagar"))
        {
            areaId ="2";
        }
        else if(areaName.equals("Mayur Vihar-1"))
        {
            areaId = "3";
        }
        else
            areaId = "4";

    }
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

});

//选择城市和地区时遇到问题。此外,我想知道如何在选择列表顶部“选择城市”和“选择区域”字段

4 个答案:

答案 0 :(得分:0)

您可以使用 SimpleCursorAdapter 代替使用ArrayAdapter,这样可以省去将光标循环到List中的步骤。

// after getting the cursor
SimpleCursorAdapter cityAdapter = new SimpleCursorAdapter(
            context, // Activity's context or getActivity() if in a fragment
            android.R.layout.simple_spinner_item,
            cursor,
            new String[] { COL_NAME_OF_THE_CITY },
            new int[] { android.R.id.text1 },
            0);

每当您想获得城市ID时,您都可以致电:

Cursor cursor = (Cursor) cityAdapter.getItem(selectedSipnnerPosition);
if (cursor!=null && cursor.moveToPosition(selectedSipnnerPosition)) {
    String cityId = cursor.getString(CITY_ID_COLUMN_INDEX);
}

请注意,要使用 SimpleCursorAdapter ,您必须在TABLE_CITY中将BaseColumns._ID作为整数主键。

答案 1 :(得分:0)

您的cityAreaModelsList不是String类型,但您的ArrayAdapter是String类型

答案 2 :(得分:0)

试试这个:

 select_city.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
        int position, long id) {
    // Here you get the current item (a CityModel object) that is selected by its position
    CityAreaModel model = adapter.getItem(position);
    // Here you can do the action you want to...
    Toast.makeText(MainActivity.this, "ID: " + model.getId(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapter) {  
    }
});

你必须为微调器使用自定义适配器

    public class CustomAdapter extends ArrayAdapter<CityAreaModel>{

    // Your sent context
    private Context context;
    // Your custom values for the spinner (CityAreaModel)
    private CityAreaModel[] values;

    public CustomAdapter(Context context, int textViewResourceId,
            CityAreaModel[] values) {
        super(context, textViewResourceId, values);
        this.context = context;
        this.values = values;
    }

    public int getCount(){
       return values.length;
    }

    public CityAreaModel getItem(int position){
       return values[position];
    }

    public long getItemId(int position){
       return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView label = new TextView(context);
        label.setTextColor(Color.BLACK);
        label.setText(values[position].getName());
        return label;
    }

    @Override
    public View getDropDownView(int position, View convertView,
            ViewGroup parent) {
        TextView label = new TextView(context);
        label.setTextColor(Color.BLACK);
        label.setText(values[position].getName());
        return label;
    }
}

将其用作:

 private CustomAdapter adapter;

   adapter = new CustomAdapter(MainActivity.this,
            android.R.layout.simple_spinner_item,
            cityAreaModelsList);
   spinner = (Spinner) findViewById(R.id.spinner_id);
   spinner.setAdapter(adapter); /

答案 3 :(得分:0)

表示apinner顶部的“选择城市”和“选择区域”字段:

ArrayAdapter<String> adapter;
groupName = (ArrayList<String>) getIntent().getSerializableExtra("groupName");

adapter = new ArrayAdapter<String>(this,R.layout.spinner_item) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    if (position == getCount()) {
                        ((TextView)v.findViewById(android.R.id.text1)).setText("");
                        ((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount()));
                        ((TextView) v.findViewById(android.R.id.text1)).setHintTextColor(Color.parseColor("#999999"));
                    }
                    return v;
                }
                public int getCount() {
                    return super.getCount()-1;
                }
            };
            adapter.setDropDownViewResource(R.layout.selecteditem);
            adapter.addAll(groupName);
            spin.setAdapter(adapter);
            spin.setSelection(adapter.getCount());

spinner_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:layout_centerHorizontal="true"
    android:drawableEnd="@drawable/downarrow"
    android:drawableRight="@drawable/downarrow"
    android:textSize="16sp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:textColor="#000"/>

selecteditem.xml:

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center_vertical"
    android:paddingLeft="10dp"
    android:paddingStart="10dp"
    android:paddingEnd="0dp"
    android:paddingRight="0dp"
    android:textColor="#000000"
    android:textSize="16sp"
    android:checked="false" />