我正在尝试使用Android Eclipse制作一个项目,而且我是新手。
这是我的问题:
我有一个表,其列为id,service_name,price,detail。我已经知道如何从Spinner获取数据。
我想问一下,在选择Spinner时,我是如何查询数据并将其显示到我的TextView中的txtPrice和txtDetail。
这是我的代码,我从androidhive.info获得,谢谢!
public class TransactionActivity extends Activity implements OnItemSelectedListener {
private Button btnAddNewService;
//private TextView txtService;
private Spinner spinnerService;
// array list for spinner adapter
private ArrayList<ServiceList> servicesList;
ProgressDialog pDialog;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://localhost/food_api/new_category.php";
// Url to get all categories
private String URL_CATEGORIES = "http://localhost/FlawlessAdmin/storescripts/create_transaction/get_service.php";
////////////////////////////////
private EditText editTextService;
List<String> listService=new ArrayList<String>();
////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction);
btnAddNewService = (Button) findViewById(R.id.btnTransact);
spinnerService = (Spinner) findViewById(R.id.spinService);
editTextService = (EditText) findViewById(R.id.txtService);
servicesList = new ArrayList<ServiceList>();
// spinner item select listener
spinnerService.setOnItemSelectedListener(this);
editTextService=(EditText) findViewById(R.id.txtService);
// Add new Service click event
btnAddNewService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (editTextService.getText().toString().trim().length() > 0) {
// new category name
String newService = editTextService.getText().toString();
// Call Async task to create new category
new AddNewService().execute(newService);
} else {
Toast.makeText(getApplicationContext(),
"Please enter service name", Toast.LENGTH_SHORT)
.show();
}
}
});
new GetCategories().execute();
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
editTextService.setText("");
for (int i = 0; i < servicesList.size(); i++) {
lables.add(servicesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerService.setAdapter(spinnerAdapter);
//////////////Copying from spinner to EditText
listService.addAll(lables);
}
/**
* Async task to get all food categories
* */
private class GetCategories extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TransactionActivity.this);
pDialog.setMessage("Fetching service categories..");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("services");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
ServiceList cat = new ServiceList(catObj.getInt("id"),
catObj.getString("service_name"));
servicesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
/**
* Async task to create a new food category
* */
private class AddNewService extends AsyncTask<String, Void, Void> {
boolean isNewCategoryCreated = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TransactionActivity.this);
pDialog.setMessage("Creating new services..");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(String... arg) {
String newCategory = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", newCategory));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
isNewCategoryCreated = true;
} else {
Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (isNewCategoryCreated) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// fetching all categories
new GetCategories().execute();
}
});
}
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
/////////////////////////////////////
String strAge=listService.get(position).toString();
editTextService.setText(strAge);
/////////////////////////////////////
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}}
我知道我提供的代码没有价格和细节的参考。我的表格列是id,service_name,价格和详细信息。我想要的活动是为service_name设置一个Spinner,为价格和细节设置TextView。现在,我的问题是当我选择service_name时,TextView应该显示相同的价格和细节。谢谢。谢谢你的帮助!
公共类ServiceList {
private int id;
private String name;
public ServiceList(){}
public ServiceList(int id, String name){
this.id = id;
this.name = name;
}
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
}
答案 0 :(得分:0)
如果您希望ServiceList
类包含price
和detail
属性,则需要将它们添加到现有类中,并为属性创建setter和getter。为方便起见,您还可以创建另一个构造函数。我假设price
属性是String
。
public class ServiceList {
private int id;
private String name;
private String price;
private String detail;
public ServiceList(){}
public ServiceList(int id, String name){
this.id = id;
this.name = name;
}
public ServiceList(int id, String name, String price, String detail){
this.id = id;
this.name = name;
this.price = price;
this.detail = detail;
}
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setPrice(String price){
this.price = price;
}
public void setDetail(String detail){
this.detail = detail;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
public String getPrice(){
return this.price;
}
public String getDetail(){
return this.detail;
}
}
将ServiceList
异步任务类的doInBackground
方法中的GetCategories
构造函数修改为新创建的ServiceList
构造函数。
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("services");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
int id = catObj.getInt("id");
String serviceName = catObj.getString("service_name");
String detail = catObj.getString("detail");
String price = catObj.getString("price");
ServiceList cat = new ServiceList(id, serviceName, price, detail);
servicesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
在onItemSelected
方法中,根据需要设置price
和detail
的文字。
我的建议是你考虑正确学习Java和Android。我推荐Udacity上的Java和Android类。您可以选择免费选项,因此您无需付费。
我希望这会有所帮助。