Java 在Android Studio中添加导航菜单后,应用程序崩溃

Java 在Android Studio中添加导航菜单后,应用程序崩溃,java,xml,android-studio,Java,Xml,Android Studio,请看一下我的源代码,我的应用程序在添加导航菜单后崩溃了。你能告诉我是怎么回事吗?我一直在谷歌上搜索,但没有找到解决这个问题的办法?多谢各位 我的主要活动如下: package com.example.rssreader; import android.app.Fragment; import android.app.FragmentManager; import android.app.SearchManager; import android.content.Intent; import an

请看一下我的源代码,我的应用程序在添加导航菜单后崩溃了。你能告诉我是怎么回事吗?我一直在谷歌上搜索,但没有找到解决这个问题的办法?多谢各位

我的主要活动如下:

package com.example.rssreader;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private android.support.v4.app.ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        ReadRss readRss = new ReadRss(this, recyclerView);
        readRss.execute();

        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.contents);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer


        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new android.support.v4.app.ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            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) {
            selectItem(0);
        }

        getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @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;
        }
        // Handle action buttons
        switch(item.getItemId()) {
            case R.id.action_websearch:
                // create intent to perform web search for this planet
                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                // catch event that there's no activity to handle intent
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_CONTENT_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @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 toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Fragment that appears in the "content_frame", shows a planet
     */
    public static class PlanetFragment extends Fragment {
        public static final String ARG_CONTENT_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_content, container, false);
            int i = getArguments().getInt(ARG_CONTENT_NUMBER);
            String planet = getResources().getStringArray(R.array.contents)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                    "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;

        }
    }

}
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#ccc"/>

</android.support.v4.widget.DrawerLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textColor="#113d5e"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:gravity="center"
    android:padding="32dp" />
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:gravity="center"
    android:padding="32dp" />
package com.example.rssreader;
导入android.app.Fragment;
导入android.app.FragmentManager;
导入android.app.SearchManager;
导入android.content.Intent;
导入android.content.res.Configuration;
导入android.os.Bundle;
导入android.support.v4.view.GravityCompat;
导入android.support.v4.widget.DrawerLayout;
导入android.support.v7.app.AppActivity;
导入android.support.v7.widget.RecyclerView;
导入android.support.v7.widget.Toolbar;
导入android.support.v7.app.ActionBar;
导入android.view.LayoutInflater;
导入android.view.MenuInflater;
导入android.view.view;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.ViewGroup;
导入android.widget.AdapterView;
导入android.widget.ArrayAdapter;
导入android.widget.ImageView;
导入android.widget.ListView;
导入android.widget.Toast;
导入java.util.Locale;
公共类MainActivity扩展了AppCompatActivity{
私人抽屉布局mDrawerLayout;
私有列表视图mDrawerList;
私有android.support.v4.app.ActionBarDrawerToggle mDrawerToggle;
私有字符序列mDrawerTitle;
私有字符序列mTitle;
私有字符串[]mplanettiles;
回收视图回收视图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=(recyclerView)findViewById(R.id.recyclerView);
ReadRss-ReadRss=new-ReadRss(this,recyclerView);
execute();
mTitle=mDrawerTitle=getTitle();
mPlanetTitles=getResources().getStringArray(R.array.contents);
mDrawerLayout=(抽屉布局)findViewById(R.id.抽屉布局);
mDrawerList=(ListView)findViewById(R.id.left\u抽屉);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//设置抽屉打开时覆盖主要内容的自定义阴影
mDrawerLayout.setDrawerShadow(R.drawable.drawer\u shadow,GravityCompat.START);
//使用项目设置抽屉的列表视图,然后单击listener
mDrawerList.setAdapter(新阵列适配器,
R.布局图.抽屉(列表项,MPLANETITLES);
setOnItemClickListener(新的DrawerItemClickListener());
//启用ActionBar应用程序图标作为切换导航抽屉的操作
//ActionBarDrawerToggle将适当的交互连接在一起
//在滑动抽屉和操作栏应用程序图标之间
mDrawerToggle=new android.support.v4.app.ActionBarDrawerToggle(
此,/*主机活动*/
mDrawerLayout,/*抽屉布局对象*/
R.drawable.ic_抽屉,/*导航抽屉图像替换“Up”插入符号*/
R.string.drawer\u open,/*“open drawer”描述,用于辅助功能*/
R.string.drawer\u close/*“close drawer”可访问性说明*/
) {
公共无效onDrawerClosed(视图){
getActionBar().setTitle(mTitle);
InvalidateOptions SMenu();//创建对OnPrepareOptions SMenu()的调用
}
打开图纸上的公共空白(视图抽屉视图){
getActionBar().setTitle(mDrawerTitle);
InvalidateOptions SMenu();//创建对OnPrepareOptions SMenu()的调用
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
如果(savedInstanceState==null){
选择项目(0);
}
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
MenuInflater充气机=getMenuInflater();
充气机。充气(右布局主菜单);
返回super.onCreateOptions菜单(菜单);
}
/*调用InvalidateOptions菜单()时调用*/
@凌驾
公共布尔值OnPrepareOptions菜单(菜单){
//如果导航抽屉打开,则隐藏与内容视图相关的操作项
boolean-DrawerLayout=mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerropen);
返回super.onPrepareOptions菜单(菜单);
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//操作栏home/up操作应打开或关闭抽屉。
//ActionBarDrawerToggle会处理好的。
如果(MDRAWERTOGLE.onOptionsItemSelected(项目)){
返回true;
}
//手柄动作按钮
开关(item.getItemId()){
案例R.id.action_网站搜索:
//创建对这个星球执行web搜索的意图
意向意向=新意向(意向.行动\网络\搜索);
//捕获没有可处理的活动的事件
if(intent.resolveActivity(getPackageManager())!=null){
星触觉(意向);
}否则{
Toast.makeText(this,R.string.app_不可用,Toast.LENGTH_LONG.show();
}
返回true;
违约:
返回super.onOptionsItemSelected(项目);
}
}
/*在导航抽屉中单击ListView的listner*/
私有类DrawerItemClickListener实现ListView.OnItemClickListener{
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
选择项目(位置);
}
}
私有void selectItem(内部位置){
//更新m
package tk.mattercast.myapplication;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


public class ReadRss extends AsyncTask<Void, Void, Void> {
    Context context;
    String address = "http://www.oecd.org/corruption/index.xml";
    ProgressDialog progressDialog;
    ArrayList<FeedItem>feedItems;
    RecyclerView recyclerView;
    URL url;
    public ReadRss(Context context,RecyclerView recyclerView) {
        this.recyclerView=recyclerView;
        this.context = context;
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Fetching Data...");
    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
        MyAdapter adapter=new MyAdapter(context,feedItems);
        recyclerView.setLayoutManager(new LinearLayoutManager(context) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return null;
            }
        });
        recyclerView.addItemDecoration(new VerticalSpace(50));
        recyclerView.setAdapter(adapter);

    }

    @Override
    protected Void doInBackground(Void... params) {
        ProcessXml(Getdata());

        return null;
    }

    private void ProcessXml(Document data) {
        if (data != null) {
            feedItems=new ArrayList<>();
            Element root = data.getDocumentElement();
            Node channel = root.getChildNodes().item(1);
            NodeList items = channel.getChildNodes();
            for (int i = 0; i < items.getLength(); i++) {
                Node cureentchild = items.item(i);
                if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
                    FeedItem item=new FeedItem();
                    NodeList itemchilds = cureentchild.getChildNodes();
                    for (int j = 0; j < itemchilds.getLength(); j++) {
                        Node cureent = itemchilds.item(j);
                        if (cureent.getNodeName().equalsIgnoreCase("title")){
                            item.setTitle(cureent.getTextContent());
                        }else if (cureent.getNodeName().equalsIgnoreCase("description")){
                            item.setDescription(cureent.getTextContent());
                        }else if (cureent.getNodeName().equalsIgnoreCase("pubDate")){
                            item.setPubDate(cureent.getTextContent());
                        }else if (cureent.getNodeName().equalsIgnoreCase("link")){
                            item.setLink(cureent.getTextContent());
                        }
                    }
                    feedItems.add(item);





                }
            }
        }
    }

    public Document Getdata() {
        try {
            url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            Document xmlDoc = builder.parse(inputStream);
            return xmlDoc;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}