将id设置为包含布局时强制关闭

时间:2015-01-04 16:05:53

标签: java android xml android-layout forceclose

目前,我正在开发一个由Toolbar而非常规ActionBar组成的Android项目。
我在名为Toolbar的单独layout文件中定义了tool_bar.xml,然后在我需要的每个布局中包含ToolBar

我的活动的布局文件名为acceptor.xml。 我的Java文件名是Acceptor.java

我的问题是,每当include tool_bar.xml acceptor.xml id并提供包含的布局force close error时,它就会给我一个Logcat,删除id属性后,它会顺利进行。

请帮忙!

xmlJava个文件,tool_bar.xml文件等所有必需资源均发布在以下位置:

<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/ColorPrimary" android:elevation="4dp" app:contentInsetEnd="0dp" app:contentInsetStart="0dp"> </android.support.v7.widget.Toolbar>

acceptor.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!--Attribute android:id causes the force close--> <include layout="@layout/tool_bar" android:id="@+id/action_accept"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tvAcceptorHeader2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="Below is the List of Donors you need!" android:textColor="#8A0707" android:textSize="20sp" android:textStyle="bold" /> <View android:id="@+id/sort_divider2" android:layout_width="fill_parent" android:layout_height="1dip" android:layout_below="@+id/tvAcceptorHeader2" android:background="#000000" /> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/sort_divider2" android:layout_marginBottom="10sp" android:layout_marginTop="10dp" android:cacheColorHint="#00000000" android:dividerHeight="3dp"></ListView> <RelativeLayout android:id="@android:id/empty" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/sort_divider2" android:layout_margin="10sp"> <TextView android:id="@+id/tvListEmpty" android:layout_width="match_parent" android:layout_height="match_parent" android:text="No Filters Applied. Please apply the filters below!" android:textSize="20sp" /> </RelativeLayout> </RelativeLayout> <SlidingDrawer android:id="@+id/slidingDrawer1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_gravity="center" android:content="@+id/content" android:handle="@+id/handle" android:orientation="horizontal"> <Button android:id="@+id/handle" android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/handle_sliding_closed" /> <RelativeLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10sp" android:background="#FFFFFF" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/tvAcceptorHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="5dp" android:text="Please apply the filters below to show a list of Donors!" android:textColor="#8A0707" android:textSize="20sp" android:textStyle="bold" /> <View android:id="@+id/header_divider" android:layout_width="match_parent" android:layout_height="1dip" android:layout_below="@+id/tvAcceptorHeader" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="1dp" android:background="#000000" /> <LinearLayout android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_below="@+id/header_divider" android:layout_margin="15dp" android:orientation="vertical"> <Spinner android:id="@+id/spinBGSort" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:entries="@array/bg_types_sort" android:prompt="@string/bg_prompt" android:spinnerMode="dialog" /> <AutoCompleteTextView android:id="@+id/acCitySort" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="Your City here" android:singleLine="true"></AutoCompleteTextView> <EditText android:id="@+id/etZipcodeSort" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="Your ZIP CODE here" android:singleLine="true"></EditText> <CheckBox android:id="@+id/cbLocation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:enabled="true" android:text="Use my Location" /> <Button android:id="@+id/bFilter" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_marginLeft="5dp" android:background="@drawable/button_selector" android:text="Filter" /> </LinearLayout> <View android:id="@+id/sort_divider" android:layout_width="match_parent" android:layout_height="2dip" android:layout_marginLeft="0dp" android:layout_marginRight="0dp" android:background="#000000" /> </RelativeLayout> </SlidingDrawer> </RelativeLayout>

LogCat

01-04 21:04:26.348 22744-22744/com.developit.bloodgency E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.developit.bloodgency, PID: 22744 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.developit.bloodgency/com.developit.bloodgency.AcceptorActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.developit.bloodgency.AcceptorActivity.onCreate(AcceptorActivity.java:107) at android.app.Activity.performCreate(Activity.java:5411) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)             at android.app.ActivityThread.access$800(ActivityThread.java:139)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:149)             at android.app.ActivityThread.main(ActivityThread.java:5257)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:515)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)             at dalvik.system.NativeStart.main(Native Method) 01-04 21:15:00.718 24442-24442/com.developit.bloodgency E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.developit.bloodgency, PID: 24442 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.developit.bloodgency/com.developit.bloodgency.AcceptorActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.developit.bloodgency.AcceptorActivity.onCreate(AcceptorActivity.java:107) at android.app.Activity.performCreate(Activity.java:5411) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)             at android.app.ActivityThread.access$800(ActivityThread.java:139)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:149)             at android.app.ActivityThread.main(ActivityThread.java:5257)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:515)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)             at dalvik.system.NativeStart.main(Native Method)

Acceptor.java

//package //import statements public class AcceptorActivity extends ActionBarActivity implements OnItemSelectedListener, OnClickListener, OnCheckedChangeListener, OnDrawerCloseListener, OnDrawerOpenListener { private static final String DONOR_LIST_URL = "http://bloodgency.developitltd.com/donor_list.php"; // JSON IDS: private static final String TAG_SUCCESS = "success"; private static final String TAG_DONORS = "donors"; private static final String TAG_DONOR_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_EMAIL = "email"; private static final String TAG_CONTACT = "contact_number"; private static final String TAG_BG = "blood_group"; private static final String TAG_COUNTRY = "country"; private static final String TAG_STATE = "state"; private static final String TAG_CITY = "city"; private static final String TAG_ZIP = "zip_code"; // php read comments script private static final String TAG_AREA = "area"; Button handle; SlidingDrawer sd; TextView tvListEmpty, tvAcceptorHeader; CheckBox cbLocation; Button bFilter; EditText etZipcodeSort; AutoCompleteTextView acCitySort; String blood_group_selected; String zipCode, zipCode_location, city_location, cityName; GPSTracker gps; Spinner spinBGSort; private ArrayAdapter<String> adapterSortCity; // Progress Dialog private ProgressDialog pDialog; // it's important to note that the message is both in the parent branch of // our JSON tree that displays a "Donor Available" or a "No Donor Available" // message, // and there is also a message for each individual post, listed under the // "posts" // category, that displays what the user typed as their message. // An array of all of our comments private JSONArray mDonors = null; // manages all of our comments in a list. private ArrayList<HashMap<String, String>> mDonorList; @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acceptor_screen); Toolbar actionBar = (Toolbar) findViewById(R.id.toolBar); //Line 107 actionBar.setTitle("Get Blood Donors"); actionBar.setLogo(R.drawable.ic_launcher); setSupportActionBar(actionBar); spinBGSort = (Spinner) findViewById(R.id.spinBGSort); spinBGSort.setOnItemSelectedListener(this); bFilter = (Button) findViewById(R.id.bFilter); bFilter.setOnClickListener(this); cbLocation = (CheckBox) findViewById(R.id.cbLocation); cbLocation.setOnCheckedChangeListener(this); etZipcodeSort = (EditText) findViewById(R.id.etZipcodeSort); acCitySort = (AutoCompleteTextView) findViewById(R.id.acCitySort); tvListEmpty = (TextView) findViewById(R.id.tvListEmpty); tvAcceptorHeader = (TextView) findViewById(R.id.tvAcceptorHeader); handle = (Button) findViewById(R.id.handle); sd = (SlidingDrawer) findViewById(R.id.slidingDrawer1); sd.open(); handle.setBackgroundResource(R.drawable.handle_sliding_open); sd.setOnDrawerCloseListener(this); sd.setOnDrawerOpenListener(this); String[] city_list_india = getResources().getStringArray(R.array.indian_cities); adapterSortCity = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, city_list_india); acCitySort.setAdapter(adapterSortCity); acCitySort.setThreshold(0); // create class object gps = new GPSTracker(AcceptorActivity.this); // check if GPS enabled if (gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // \n is for new line /* * Toast.makeText( getApplicationContext(), * "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, * Toast.LENGTH_LONG).show(); */ // lat,lng, your current location try { Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); zipCode_location = addresses.get(0).getPostalCode(); city_location = addresses.get(0).getLocality(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { cbLocation.setEnabled(false); // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings } if (cbLocation.isChecked()) { if (!gps.canGetLocation()) gps.showSettingsAlert(); } } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); /* * new LoadDonorList().execute("ALL Blood Groups", zipCode_location, * city_location); */ } /** * ... /** Retrieves recent post data from the server. */ public void updateJSONdata(String bg, String zipCode, String cityName) { // Instantiate the arraylist to contain all the JSON data. // we are going to use a bunch of key-value pairs, referring // to the json element name, and the content, for example, // message it the tag, and "I'm awesome" as the content.. mDonorList = new ArrayList<HashMap<String, String>>(); // Bro, it's time to power up the J parser JSONParser jParser = new JSONParser(); // Feed the beast our comments url, and it spits us // back a JSON object. Boo-yeah Jerome. JSONObject json = jParser.getJSONFromUrl(DONOR_LIST_URL); // when parsing JSON stuff, we should probably // try to catch any exceptions: try { mDonors = json.getJSONArray(TAG_DONORS); // looping through all posts according to the json object returned for (int i = 0; i < mDonors.length(); i++) { JSONObject c = mDonors.getJSONObject(i); // gets the content of each tag String name = c.getString(TAG_NAME); String email = c.getString(TAG_EMAIL); String contact_number = c.getString(TAG_CONTACT); String blood_group = c.getString(TAG_BG); String country = c.getString(TAG_COUNTRY); String state = c.getString(TAG_STATE); String city = c.getString(TAG_CITY); String zip_code = c.getString(TAG_ZIP); String area = c.getString(TAG_AREA); if (bg.equals(null) || blood_group.equals(bg) || bg.equals("ALL Blood Groups")) { if (zip_code.equals(zipCode) || zipCode.equals("")) { if (city.equalsIgnoreCase(cityName) || cityName.equals("")) { // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); map.put(TAG_NAME, name); map.put(TAG_EMAIL, email); map.put(TAG_CONTACT, contact_number); map.put(TAG_BG, blood_group); map.put(TAG_COUNTRY, country); map.put(TAG_STATE, state); map.put(TAG_CITY, city); map.put(TAG_ZIP, zip_code); map.put(TAG_AREA, area); // adding HashList to ArrayList mDonorList.add(map); // annndddd, our JSON data is up to date same with // our // array // list } } } } } catch (JSONException e) { e.printStackTrace(); } } /** * Inserts the parsed data into the listview. */ private void updateList() { // For a ListActivity we need to set the List Adapter, and in order to // do // that, we need to create a ListAdapter. This SimpleAdapter, // will utilize our updated Hashmapped ArrayList, // use our single_post xml template for each item in our list, // and place the appropriate info from the list to the // correct GUI id. Order is important here. ListAdapter adapter = new SimpleAdapter(this, mDonorList, R.layout.list_item, new String[]{TAG_NAME, TAG_EMAIL, TAG_BG, TAG_CONTACT, TAG_COUNTRY, TAG_STATE, TAG_CITY, TAG_ZIP, TAG_AREA}, new int[]{R.id.tvListName, R.id.tvListEmail, R.id.tvListBG, R.id.tvListContact, R.id.tvListCountry, R.id.tvListState, R.id.tvListCity, R.id.tvListZipCode, R.id.tvListArea}); // Optional: when the user clicks a list item we // could do something. However, we will choose // to do nothing... ListView lv = (ListView) findViewById(android.R.id.list); lv.setAdapter(adapter); lv.setBackgroundColor(Color.WHITE); lv.setCacheColorHint(Color.WHITE); if (lv.getAdapter().getCount() == 0) { lv.setEmptyView(findViewById(android.R.id.empty)); tvListEmpty .setText("No Donors to display with this Filter. Please apply another filter!"); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // This method is triggered if an item is click within our // list. For our example we won't be using this, but // it is useful to know in real life applications. } }); } } @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bFilter: try { findViewById(android.R.id.empty).setVisibility(View.INVISIBLE); blood_group_selected = spinBGSort.getSelectedItem().toString(); String zipCode = etZipcodeSort.getText().toString(); String cityName = acCitySort.getText().toString(); if (!cbLocation.isChecked()) { if (zipCode.equals("") && cityName.equals("")) { Toast.makeText(this, "Please enter atleast one of CITY or ZIP CODE", Toast.LENGTH_LONG).show(); } else new LoadDonorList().execute(blood_group_selected, zipCode, cityName); } else { zipCode = zipCode_location; cityName = city_location; new LoadDonorList().execute(blood_group_selected, zipCode, cityName); } } catch (Exception e) { e.printStackTrace(); } finally { Toast.makeText(this, "An error Occurred while fetching the Donor List", Toast.LENGTH_LONG); } break; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (cbLocation.isChecked()) { etZipcodeSort.setVisibility(View.INVISIBLE); acCitySort.setVisibility(View.INVISIBLE); } else { etZipcodeSort.setVisibility(View.VISIBLE); acCitySort.setVisibility(View.VISIBLE); } } @Override public void onDrawerOpened() { // TODO Auto-generated method stub handle.setBackgroundResource(R.drawable.handle_sliding_open); } @Override public void onDrawerClosed() { // TODO Auto-generated method stub handle.setBackgroundResource(R.drawable.handle_sliding_closed); } public class LoadDonorList extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(AcceptorActivity.this); pDialog.setTitle("Loading Donor List"); pDialog.setMessage("Please Wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... arg0) { // we will develop this method in version 2 updateJSONdata(arg0[0], arg0[1], arg0[2]); return null; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); pDialog.dismiss(); updateList(); sd.close(); } } }

{{1}}

我希望这足以解决我的问题。 提前谢谢!

0 个答案:

没有答案