我是LoopJ Android Asynchronous-Http-Client的新手。我想出了如何使用我的PHP Web服务从数据库中获取数据。
我的ServiceHandler:
public class ServiceHandler {
private static String BASE_URL="http:/my/url/";
private static String GET_CAT= BASE_URL+"get_cat.php";
private static AsyncHttpClient client= new AsyncHttpClient();
public static void getAllCat(RequestParams params,AsyncHttpResponseHandler asyncHttpResponseHandler
){
client.get(GET_CAT,params,asyncHttpResponseHandler);};}
我的AddBookActivity:在这个类中,我使用getAllCat从数据库中获取类别,但现在我如何填充我的微调器?
public class AddBookActivity extends AppCompatActivity {
ServiceHandler client = new ServiceHandler();
private Spinner spCat;
@Override
protected void onResume() {
super.onResume();
getAllCat();
}
private void getAllCat(){
client.getAllCat(null, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode,cz.msebera.android.httpclient.Header[] headers, JSONArray response) {
try {
for (int i=0; i<response.length();i++){
Categories cat = new Categories();
JSONObject obj =response.getJSONObject(i);
cat.setName(obj.getString("name"));
}
}catch (Exception e){
e.printStackTrace();
}}} ); }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spCat=(Spinner)findViewById(R.id.spinnercatname);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
答案 0 :(得分:0)
如果您只想填写类别名称列表 - 而不是JSONArray
- 那么您可以将getAllCat()
更改为以下内容:
private void getAllCat(){
client.getAllCat(null, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode,cz.msebera.android.httpclient.Header[] headers, JSONArray response) {
try {
List<String> categoryNames = new ArrayList<String>();
for (int i=0; i<response.length();i++){
JSONObject obj =response.getJSONObject(i);
String categoryName = obj.getString("name");
categoryNames.add(categoryName);
}
//now that you have populated the array of category names - you can create the adapter for the spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryNames);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCat.setAdapter(spinnerAdapter);
spinnerAdapter.notifyDataSetChanged();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
但是,如果您想使用JSONArray,那么您将需要一个“特殊”适配器。我最近回答了一个类似的问题。请检查here for possible solution。 我希望这会有所帮助。
答案 1 :(得分:0)
将此代码写入onSuccess方法
for(int a=1,b=1,c=2,d=5;a<4,b<10;a++,b++)//initialize variables and using , between expression
{
cout<<a<<" "<<b<<endl;
}