我有一个在我的主要活动中调用的customviewadapter来构建一个菜单滑块。
我的问题是:我如何在物品上添加物品“dataList”。
如果我是从CustomViewAdapter创建的,那么当我完成从谷歌获取地点的过程时:
MainActivity prueba2 = new MainActivity();
prueba2.onCreate(null);
它抛出了一个nullpointer异常
如果我这样做:
MainActivity prueba2 = new MainActivity();
prueba2.onPrepareOptionsMenu(null);
当我想添加像这部分这样的项目时,它会抛出一个错误:
for(int i=0;i<s1.size();i++){
dataList.add(new DrawerItem("Sitios2", R.drawable.ic_action_good));
也有nullpointerexception。
s1获取地点列表但不能在第一个循环中向菜单添加项目:( 我必须初始化对象?使用此getMenuInflater()。inflate(R.menu.main,menu);?
一些帮助会被贬低。
这是我的CustomViewAdapter:
public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> {
Context context;
List<DrawerItem> drawerItemList;
int layoutResID;
public static String type;
public CustomDrawerAdapter(Context context, int layoutResourceID,
List<DrawerItem> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
DrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView) view
.findViewById(R.id.drawer_itemName);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);
drawerHolder.spinner = (Spinner) view
.findViewById(R.id.drawerSpinner);
drawerHolder.title = (TextView) view.findViewById(R.id.drawerTitle);
drawerHolder.headerLayout = (LinearLayout) view
.findViewById(R.id.headerLayout);
drawerHolder.itemLayout = (LinearLayout) view
.findViewById(R.id.itemLayout);
drawerHolder.spinnerLayout = (LinearLayout) view
.findViewById(R.id.spinnerLayout);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);
if (dItem.isSpinner()) {
drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
drawerHolder.spinnerLayout.setVisibility(LinearLayout.VISIBLE);
List<SpinnerItem> userList = new ArrayList<SpinnerItem>();
userList.add(new SpinnerItem(R.drawable.user1, "Airport"));
userList.add(new SpinnerItem(R.drawable.user1, "ATM"));
userList.add(new SpinnerItem(R.drawable.user1, "Bank"));
userList.add(new SpinnerItem(R.drawable.user1, "Bus Station"));
userList.add(new SpinnerItem(R.drawable.user1, "church"));
userList.add(new SpinnerItem(R.drawable.user1, "doctor"));
userList.add(new SpinnerItem(R.drawable.user1, "Airport"));
userList.add(new SpinnerItem(R.drawable.user1, "hospital"));
userList.add(new SpinnerItem(R.drawable.user1, "mosque"));
userList.add(new SpinnerItem(R.drawable.user1, "movie Theate"));
userList.add(new SpinnerItem(R.drawable.user1, "hindu Temple"));
userList.add(new SpinnerItem(R.drawable.user1, "restaurant"));
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(context,
R.layout.custom_spinner_item, userList);
final Double Lat2 = 25.751188242782035;
final Double Lng2 = -100.3097140789032;
drawerHolder.spinner.setAdapter(adapter);
drawerHolder.spinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
if(arg0.getSelectedItemPosition()==0){
type = "airport";
// setPlaceTag puto = new setPlaceTag();
setPlaceTag.setChangedStat(true);
setPlaceTag.setTag(type);
// MainActivity prueba = new MainActivity();
// prueba.onPrepareOptionsMenu(null);
//set atm string
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+Lat2+","+Lng2);
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=ba");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
if(arg0.getSelectedItemPosition()==1){
String type = "atm";
setPlaceTag.tag = type;
// MainActivity prueba = new MainActivity();
// prueba.onPrepareOptionsMenu(null);
//set atm string
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+Lat2+","+Lng2);
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=ba");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
// Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show();
}
if(arg0.getSelectedItemPosition()==2){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==3){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==4){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==5){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==6){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==7){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==8){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==9){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==10){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
if(arg0.getSelectedItemPosition()==11){
Toast.makeText(context, "User Changed", Toast.LENGTH_SHORT).show(); }
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
} else if (dItem.getTitle() != null) {
drawerHolder.headerLayout.setVisibility(LinearLayout.VISIBLE);
drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
drawerHolder.title.setText(dItem.getTitle());
Log.d("Getview","Passed4");
} else {
drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
drawerHolder.itemLayout.setVisibility(LinearLayout.VISIBLE);
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
dItem.getImgResID()));
drawerHolder.ItemName.setText(dItem.getItemName());
Log.d("Getview","Passed5");
}
return view;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
@Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
// mMapView.clear();
// notificacion(Results.toString());
/* mMapView.addMarker(new MarkerOptions()
.position(new LatLng(Lat3,Lng3))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker1))
.title(Lugar)
.snippet(Desc));
*/
// sendPlaces obj = new sendPlaces();
// obj.setList(list);
setPlaceTag.List = list;
MainActivity prueba2 = new MainActivity();
prueba2.onCreate(null);
//o = false;
// Intent redirect = new Intent(context,MainActivity.class);
// context.startActivity(redirect);
//((Menu) map).clear();
for(int i=0;i<list.size();i++){
// Creating a marker
// MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
// LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
// markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
// markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
// mMapView.addMarker(markerOptions);
}
}
}
private static class DrawerItemHolder {
TextView ItemName, title;
ImageView icon;
LinearLayout headerLayout, itemLayout, spinnerLayout;
Spinner spinner;
}
}
这是我的MainActivity:
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
public List<HashMap<String, String>> list;
private boolean isChangedStat = false;
private static final int MENUITEM = Menu.FIRST;
private String wei;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Add Drawer Item to dataList
dataList.add(new DrawerItem(true)); // adding a spinner to the list
// list =
//for(int i=0;i<list.size();i++){ //}
dataList.add(new DrawerItem("Closed sites")); // adding a header to the list
dataList.add(new DrawerItem("Sitios", R.drawable.ic_action_good));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
if (dataList.get(0).isSpinner()
& dataList.get(1).getTitle() != null) {
SelectItem(2);
} else if (dataList.get(0).getTitle() != null) {
SelectItem(1);
} else {
SelectItem(0);
}
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//Toast.makeText(getApplicationContext(), "wei estas en resume", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Toast.makeText(getApplicationContext(), "vato estas en onpause", Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
//menu.clear();
/* String s = setPlaceTag.tag;
Boolean check = setPlaceTag.isChangedStat;
if(check.equals(true)){
List<HashMap<String, String>> s1 = setPlaceTag.List;
if(!s1.equals(null)){
for(int i=0;i<s1.size();i++){
dataList.add(new DrawerItem("Sitios2", R.drawable.ic_action_good));
getMenuInflater().inflate(R.menu.main, menu);
}
}
} */
return super.onPrepareOptionsMenu(menu);
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 2:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
.get(possition).getImgResID());
break;
case 3:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 4:
fragment = new FragmentTwo();
args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 5:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
.get(possition).getImgResID());
break;
case 7:
fragment = new FragmentTwo();
args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 8:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
.get(possition).getImgResID());
break;
case 9:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 10:
fragment = new FragmentTwo();
args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 11:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
.get(possition).getImgResID());
break;
case 12:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 14:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 15:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 16:
fragment = new FragmentTwo();
args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment) .commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
Toast.makeText(getApplicationContext(), "estas en main activity modificando spinner", Toast.LENGTH_SHORT).show();
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (dataList.get(position).getTitle() == null) {
SelectItem(position);
}
Toast.makeText(getApplicationContext(), "diste click a sitios", Toast.LENGTH_SHORT).show();
}
}
}