私は ActionBarSherlock ライブラリを使用してアプリにナビゲーション ドロワーを実装します。次に、ナビゲーション ドロワーが表示される MainActivity というメイン クラスがあり、その中にすべてのフラグメントをインスタンス化しました。getActivity() メソッドがメイン クラス (MainActivity) を返すため、frament "novopedido" (NovoPedido.java) のスピナーを設定できません。
MainActivity.java 内:Fragment novopedido = new NovoPedido();
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, home);
break;
case 1:
ft.replace(R.id.content_frame, novopedido);
break;
case 8:
ft.replace(R.id.content_frame, configs);
break;
case 10:
ft.replace(R.id.content_frame, capture);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Get the title followed by the position
setTitle(title[position]);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
NovoPedido.java 内
btnBuscarProduto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
buscarProduto();
}
}).start();
}
});
void buscarProduto(){
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.1.101/android/busca.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("busca", edtBuscaProduto.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
if(response.equalsIgnoreCase("Vazio")){
Toast toast = Toast.makeText(getActivity(), "Nada foi encontrado", Toast.LENGTH_SHORT);
toast.show();
}
else{
List<String> list = new ArrayList<String>();
String[] responseArray = response.split("\\|");
System.out.println("Itens do response: "+response);
for (int i =0; i<responseArray.length; i++){
list.add(responseArray[i]);
System.out.println("Item Adicionado: "+responseArray[i]);
}
System.out.println("responseArray.length: "+responseArray.length);
System.out.println("responseArray: "+responseArray);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
ArrayAdapter<String> spinnerArrayAdapter = arrayAdapter;
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spnProdutos.setAdapter(spinnerArrayAdapter);
System.out.println("Activity: "+getActivity());
}
} catch(NetworkOnMainThreadException e) {
// System.out.println("Erro de network: "+e.getMessage());
}catch(Exception e){
Toast toast = Toast.makeText(getActivity(), "Erro: "+e.getMessage(), Toast.LENGTH_SHORT);
toast.show();
}
}