我希望从SQLite数据库中选择COMPANY_ID作为Spinner Value并将其烘烤以备将来使用。 谁能帮助我或建议我如何获得COMPANY_ID
这是活动代码
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener {
DatabaseHelper databaseHelper;
Context context;
NestedScrollView nestedScrollView;
private ProgressDialog pdialog;
RequestQueue requestQueue;
private Spinner appCompatSpinner;
private ArrayList<DataCompany> dataCompanies;
private ArrayList<Company> labels;
private ArrayList<Data> data;
private ArrayList<BankInfo> bankInfos;
private EditText InsureName, BankHypotical;
private MaterialRippleLayout NextButtonmaterialRippleLayout, SaveButtonmaterialRippleLayout, materialRippleNext;
private String SpinnerData;
private NameAdapter nameAdapter;
private List<BankInfo> names;
protected ViewDialog viewDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snv_main);
viewDialog = new ViewDialog(this);
viewDialog.setCancelable(false);
appCompatSpinner = findViewById(R.id.selectSpinner_Bank_List);
context = this;
databaseHelper = new DatabaseHelper(context);
appCompatSpinner.setOnItemSelectedListener(this);
// loadSpinnerData();
if (Utils.isNetworkAvailable(getApplicationContext())) {
Call<NewInsuranceModel> call = RetrofitClient
.getInstance().getApi().newInsuranceModel("get_new_insurance_fields");
showProgressDialog();
call.enqueue(new Callback<NewInsuranceModel>() {
@Override
public void onResponse(Call<NewInsuranceModel> call, retrofit2.Response<NewInsuranceModel> response) {
NewInsuranceModel newInsuranceModel = response.body();
hideProgressDialog();
if (newInsuranceModel.getStatus().toString().equalsIgnoreCase("true")) {
dataCompanies = new ArrayList<DataCompany>();
dataCompanies.add(new DataCompany("Select Insurance Company"));
try {
for (int i = 0; i < dataCompanies.size(); i++) {
DataCompany dataCompany = newInsuranceModel.getDataCompany().get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(dataCompany);
dataCompanies.add(newInsuranceModel.getDataCompany().get(i));
initCustomSpinner();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, newInsuranceModel.getMsg() + "", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<NewInsuranceModel> call, Throwable t) {
hideProgressDialog();
Toast.makeText(MainActivity.this, " Again Error", Toast.LENGTH_LONG).show();
}
});
} else {
loadSpinnerData();
}
nestedScrollView = findViewById(R.id.nestedScrollView);
InsureName = findViewById(R.id.text_insured_name);
BankHypotical = findViewById(R.id.text_bank_hypothecation);
NextButtonmaterialRippleLayout = findViewById(R.id.next_button_main_activity);
NextButtonmaterialRippleLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NextPage();
}
});
}
private void loadSpinnerData() {
databaseHelper = new DatabaseHelper(getApplicationContext());
try {
ArrayList<Company> labels = databaseHelper.getAllLabels();
ArrayAdapter dataAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, labels);
appCompatSpinner.setAdapter(dataAdapter);
appCompatSpinner.setPrompt("Select Insurance Company");
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SpinnerData = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public class SaveIntoDatabase extends AsyncTask<DataCompany, DataCompany, Boolean> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(DataCompany... params) {
DataCompany dataCompany = params[0];
databaseHelper.addDataCompany(dataCompany);
return null;
}
}
protected void hideProgressDialog() {
viewDialog.dismiss();
}
protected void showProgressDialog() {
viewDialog.show();
}
protected void showProgressDialog(String message) {
showProgressDialog();
}
private void initCustomSpinner() {
CustomSpinnerAdapter customSpinnerAdapter = new CustomSpinnerAdapter(MainActivity.this, dataCompanies);
appCompatSpinner.setAdapter(customSpinnerAdapter);
appCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SpinnerData = parent.getItemAtPosition(position).toString();
// Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
// sstate = (String) parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public class CustomSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
private final Context activity;
private ArrayList<DataCompany> asr;
public CustomSpinnerAdapter(Context context, ArrayList<DataCompany> asr) {
this.asr = asr;
activity = context;
}
public int getCount() {
return asr.size();
}
public Object getItem(int i) {
return asr.get(i);
}
public long getItemId(int i) {
return (long) i;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(MainActivity.this);
txt.setPadding(16, 16, 16, 16);
txt.setTextSize(18);
txt.setGravity(Gravity.CENTER);
txt.setText(asr.get(position).getCompanyName());
txt.setTextColor(Color.parseColor("#2196F3"));
return txt;
}
public View getView(int i, View view, ViewGroup viewgroup) {
TextView txt = new TextView(MainActivity.this);
txt.setGravity(Gravity.CENTER);
txt.setPadding(16, 16, 16, 16);
txt.setTextSize(14);
txt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down_white_24dp, 0);
txt.setText(asr.get(i).getCompanyName());
txt.setTextColor(Color.parseColor("#FFFFFF"));
return txt;
}
}
private void NextPage() {
String editInsureName = InsureName.getText().toString();
String editBankHypotical = BankHypotical.getText().toString();
int pos = appCompatSpinner.getSelectedItemPosition();
if (pos == 0) {
Snackbar snackbar = Snackbar
.make(nestedScrollView, "Select Insurance Company", Snackbar.LENGTH_LONG);
snackbar.show();
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
appCompatSpinner.requestFocus();
} else if (TextUtils.isEmpty(editInsureName)) {
Snackbar snackbar = Snackbar
.make(nestedScrollView, "Enter Insured Name / Society Name", Snackbar.LENGTH_LONG);
snackbar.show();
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
InsureName.requestFocus();
} else if (TextUtils.isEmpty(editBankHypotical)) {
Snackbar snackbar = Snackbar
.make(nestedScrollView, "Enter Bank Hypothecation With", Snackbar.LENGTH_LONG);
snackbar.show();
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
BankHypotical.requestFocus();
} else {
Intent nextIntent = new Intent(MainActivity.this, FarmerInformationActivity.class);
// nextIntent.putExtra("id", dataCompanies.get(appCompatSpinner.getSelectedItemPosition()).getId());
nextIntent.putExtra("id", labels.get(appCompatSpinner.getSelectedItemPosition()).getCompanyId());
nextIntent.putExtra("farmer_insure_name", InsureName.getText().toString());
nextIntent.putExtra("farmer_bank_hypo", BankHypotical.getText().toString());
startActivity(nextIntent);
Snackbar snackbar = Snackbar.make(nestedScrollView, "Saved Successfully", Snackbar.LENGTH_LONG);
snackbar.show();
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
}
}
在SQLite中保存数据从JSON此处是代码
public class SaveIntoDatabase extends AsyncTask<DataCompany, DataCompany, Boolean> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(DataCompany... params) {
DataCompany dataCompany = params[0];
databaseHelper.addDataCompany(dataCompany);
return null;
}
}
数据库帮助程序类
我正在通过Json在Sqlite数据库中添加值,这是代码
public void addDataCompany(DataCompany dataCompany) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COMPANY_ID, dataCompany.getId() + "");
contentValues.put(COMPANY_NAME, dataCompany.getCompanyName() + "");
// contentValues.put(BANK_COLUMN, bank);
try {
db.insert(TABLE_NAME_OFFLINE_LOAD_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
db.close();
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME_OFFLINE_LOAD_DATA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
预先感谢
答案 0 :(得分:2)
您必须创建自定义模型类(getter和setter)。例如公司
将所有数据存储在getAllLabels()方法的List<Company> labels = new ArrayList<Company>()
中。
在onItemSelected之后
SpinnerData = getAllLabels()。get(position).COMPANY_ID(在您的模型类Company中)
您将获得所选商品的SpinnerData COMPANY_ID
答案 1 :(得分:2)
创建模型类公司
public class Company {
String companyId,companyName;
public Company(String companyId, String companyName) {
this.companyId = companyId;
this.companyName = companyName;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
@Override
public String toString() {
return companyName;
}
}
进行以下更改 loadSpinnerData()方法
private void loadSpinnerData() {
databaseHelper = new DatabaseHelper(getApplicationContext());
try {
labels = databaseHelper.getAllLabels();
ArrayAdapter dataAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, lables);
appCompatSpinner.setAdapter(dataAdapter);
appCompatSpinner.setPrompt("Select Insurance Company");
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SpinnerData = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
对 getAllLabels()方法
进行以下更改 public ArrayList<Company> getAllLabels(){
ArrayList<Company> labels = new ArrayList<Company>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME_OFFLINE_LOAD_DATA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String companyId = cursor.getString(cursor.getColumnIndex(COMPANY_ID));
String companyName = cursor.getString(cursor.getColumnIndex(COMPANY_NAME));
labels.add(new Company(companyId,companyName);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
要获取当前所选项目的公司ID
labels.get(appCompatSpinner.getSelectedItemPosition())。getCompanyId();
答案 2 :(得分:0)
请参阅此代码
这是从sqlite db获取微调器中选定状态的状态ID的示例代码。
步骤1:从状态表中获取所有列的状态列表
public List<String> getStates(){
List<String> states = new ArrayList<String>();
// Select Query
String selectQuery = "SELECT * FROM " + STATE_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
states.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
return states;
}
第2步:从微调器适配器获取选定的状态值。
spinnerstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
sstate = (String) parent.getItemAtPosition(position);
sstateid=salesDB.getstateid(sstate);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
第3步:使用参数作为状态值调用此salesDB.getstateid(sstate)方法。
public String getstateid(String states){
String stateid="";
String selectQuerys = "SELECT * FROM state WHERE state_name = '"+states+"'";
SQLiteDatabase db = this.getReadableDatabase();
try
{
Cursor cursor = db.rawQuery(selectQuerys, null);
if (cursor.moveToFirst()) {
do {
stateid=cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
catch (SQLException s)
{
Log.v("Exception",s.toString());
}
db.close();
return stateid;
}