android.view.InflateException:二进制XML文件第2行:二进制XML文件第2行:错误膨胀了类android.support.v4.widget.DrawerLayout

时间:2019-02-02 03:59:17

标签: java xml drawerlayout

在android studio 3.3中使用android食物订购应用程序时遇到此错误:

  02-01 22:23:20.751 8518-8518/com.royalkitchenabuja.royalkitchenserver E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.royalkitchenabuja.royalkitchenserver/com.royalkitchenabuja.royalkitchenserver.Home}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.v4.widget.DrawerLayout
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2583)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5765)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
 Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.v4.widget.DrawerLayout
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.royalkitchenabuja.royalkitchenserver.Home.onCreate(Home.java:84)
    at android.app.Activity.performCreate(Activity.java:6301)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2530)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2665) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499) 
    at android.os.Handler.dispatchMessage(Handler.java:111) 
    at android.os.Looper.loop(Looper.java:207) 
    at android.app.ActivityThread.main(ActivityThread.java:5765) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684) 
 Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.v4.widget.DrawerLayout
    at android.view.LayoutInflater.createView(LayoutInflater.java:645)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287) 
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 
    at com.royalkitchenabuja.royalkitchenserver.Home.onCreate(Home.java:84) 
    at android.app.Activity.performCreate(Activity.java:6301) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2530) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2665) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499) 
    at android.os.Handler.dispatchMessage(Handler.java:111) 
    at android.os.Looper.loop(Looper.java:207) 
    at android.app.ActivityThread.main(ActivityThread.java:5765) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684) 
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance(Native Method)
    at android.view.LayoutInflater.createView(LayoutInflater.java:619)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764) 
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287) 
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 
    at com.royalkitchenabuja.royalkitchenserver.Home.onCreate(Home.java:84) 
    at android.app.Activity.performCreate(Activity.java:6301) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2530) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2665) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499) 
    at android.os.Handler.dispatchMessage(Handler.java:111) 
    at android.os.Looper.loop(Looper.java:207) 
    at android.app.ActivityThread.main(ActivityThread.java:5765) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)   

这是受影响的xml文件(activity_home.xml):

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@drawable/logo2"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_home"

        android:background="@color/overlayBackground"
        app:itemTextColor="@android:color/white"
        app:itemIconTint="@android:color/white"
        app:menu="@menu/activity_home_drawer" />

</android.support.v4.widget.DrawerLayout>

这是受影响的Java文件(Home.java):

package com.royalkitchenabuja.royalkitchenserver;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.royalkitchenabuja.royalkitchenserver.Common.Common;
import com.royalkitchenabuja.royalkitchenserver.Model.Token;
import com.royalkitchenabuja.royalkitchenserver.Interface.ItemClickListener;
import com.royalkitchenabuja.royalkitchenserver.Model.Category;
import com.royalkitchenabuja.royalkitchenserver.R;
import com.royalkitchenabuja.royalkitchenserver.ViewHolder.MenuViewHolder;
import com.squareup.picasso.Picasso;

import java.util.UUID;

import info.hoang8f.widget.FButton;

public class Home extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

TextView txtFullName;

//Firebase
FirebaseDatabase database;
DatabaseReference categories;
FirebaseStorage storage;
StorageReference storageReference;
FirebaseRecyclerAdapter<Category,MenuViewHolder> adapter;

//View
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;

//Add New Menu Layout
MaterialEditText edtName;
FButton btnUpload,btnSelect;

Category newCategory;

Uri saveUri;


DrawerLayout drawer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    toolbar.setTitle("Menu Management");
    setSupportActionBar(toolbar);


    //Init Firebase
    database = FirebaseDatabase.getInstance();
    categories = database.getReference("Category");
    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showDialog();
        }
    });

    drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //Set Name for user
    View headerView = navigationView.getHeaderView(0);
    txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
    txtFullName.setText(Common.currentUser.getName());

    //Init View
    recycler_menu = (RecyclerView)findViewById(R.id.recycler_menu);
    recycler_menu.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);

    loadMenu();


    //Send token
    updateToken(FirebaseInstanceId.getInstance().getToken());


}

private void updateToken(String token) {
    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference tokens = db.getReference("Tokens");
    Token data = new Token(token,true);
    tokens.child(Common.currentUser.getPhone()).setValue(data);
}

private void showDialog() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this);
    alertDialog.setTitle("Add new Category");
    alertDialog.setMessage("Please provide full information");

    LayoutInflater inflater = this.getLayoutInflater();
    View add_menu_layout = inflater.inflate(R.layout.add_new_menu_layout,null);

    edtName = add_menu_layout.findViewById(R.id.edtName);
    btnSelect = add_menu_layout.findViewById(R.id.btnSelect);
    btnUpload = add_menu_layout.findViewById(R.id.btnUpload);

    //Event for button
    btnSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            chooseImage(); // Let user select image from Gallery and save Uri of this image
        }
    });

    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadImage();
        }
    });

    alertDialog.setView(add_menu_layout);
    alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);

    //Set button
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();

            //Here, just create new category
            if (newCategory != null)
            {
                categories.push().setValue(newCategory);
                Snackbar.make(drawer,"New category "+newCategory.getName()+" was added",Snackbar.LENGTH_SHORT)
                        .show();
            }

        }
    });
    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();
        }
    });
    alertDialog.show();

}

private void uploadImage() {
    if (saveUri != null)
    {
        final ProgressDialog mDialog = new ProgressDialog(this);
        mDialog.setMessage("Uploading...");
        mDialog.show();

        String imageName = UUID.randomUUID().toString();
        final StorageReference imageFolder = storageReference.child("images/"+imageName);
        imageFolder.putFile(saveUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        mDialog.dismiss();
                        Toast.makeText(Home.this, "Uploaded !!!", Toast.LENGTH_SHORT).show();
                        imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                //set value for newCategory if image uploads and we can get download link
                                newCategory = new Category(edtName.getText().toString(),uri.toString());

                            }
                        });
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        mDialog.dismiss();
                        Toast.makeText(Home.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        //Don't worry about this error
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                        mDialog.setMessage("Uploaded "+progress+"%");
                    }
                });
    }
}




@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Common.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null)
    {
        saveUri = data.getData();
        btnSelect.setText("Image Selected !");
    }
}

private void chooseImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Picture"),Common.PICK_IMAGE_REQUEST);
}

private void loadMenu() {
    adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(
            Category.class,
            R.layout.menu_item,
            MenuViewHolder.class,
            categories
    ) {
        @Override
        protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
            viewHolder.txtMenuName.setText(model.getName());
            Picasso.with(Home.this).load(model.getImage())
                    .into(viewHolder.imageView);

            viewHolder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    //send Category Id and Start new Activity
                    Intent foodList = new Intent(Home.this,FoodList.class);
                    foodList.putExtra("CategoryId",adapter.getRef(position).getKey());
                    startActivity(foodList);
                }
            });
        }
    };

    adapter.notifyDataSetChanged(); // Refresh data if have data changed
    recycler_menu.setAdapter(adapter);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_orders)
    {
        Intent orders = new Intent(Home.this,OrderStatus.class);
        startActivity(orders);
    }



    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}


//Update / Delete
//Press Ctrl+O

@Override
public boolean onContextItemSelected(MenuItem item) {

    if (item.getTitle().equals(Common.UPDATE))
    {
        showUpdateDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
    }
    else if (item.getTitle().equals(Common.DELETE))
    {
        deleteCategory(adapter.getRef(item.getOrder()).getKey());
    }

    return super.onContextItemSelected(item);
}

private void deleteCategory(String key) {

    //First , we need to get all food in category
    DatabaseReference foods = database.getReference("Foods");
    Query foodInCategory = foods.orderByChild("menuId").equalTo(key);
    foodInCategory.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapShot:dataSnapshot.getChildren())
            {
                postSnapShot.getRef().removeValue();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    categories.child(key).removeValue();
    Toast.makeText(this, "Item deleted !!!!", Toast.LENGTH_SHORT).show();
}


private void showUpdateDialog(final String key, final Category item) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this);
    alertDialog.setTitle("Update Category");
    alertDialog.setMessage("Please fill full information");

    LayoutInflater inflater = this.getLayoutInflater();
    View add_menu_layout = inflater.inflate(R.layout.add_new_menu_layout,null);

    edtName = add_menu_layout.findViewById(R.id.edtName);
    btnSelect = add_menu_layout.findViewById(R.id.btnSelect);
    btnUpload = add_menu_layout.findViewById(R.id.btnUpload);

    //Set default name
    edtName.setText(item.getName());

    //Event for button
    btnSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            chooseImage(); // Let user select image from Gallery and save Uri of this image
        }
    });

    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            changeImage(item);
        }
    });

    alertDialog.setView(add_menu_layout);
    alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);

    //Set button
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();

            //Update information
            item.setName(edtName.getText().toString());
            categories.child(key).setValue(item);

        }
    });
    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();
        }
    });
    alertDialog.show();
}

private void changeImage(final Category item) {
    if (saveUri != null)
    {
        final ProgressDialog mDialog = new ProgressDialog(this);
        mDialog.setMessage("Uploading...");
        mDialog.show();

        String imageName = UUID.randomUUID().toString();
        final StorageReference imageFolder = storageReference.child("images/"+imageName);
        imageFolder.putFile(saveUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        mDialog.dismiss();
                        Toast.makeText(Home.this, "Uploaded !!!", Toast.LENGTH_SHORT).show();
                        imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                //set value for newCategory if image uploads and we can get download link
                                item.setImage(uri.toString());
                            }
                        });
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        mDialog.dismiss();
                        Toast.makeText(Home.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        //Don't worry about this error
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                        mDialog.setMessage("Uploaded "+progress+"%");
                    }
                });
    }
}
}

0 个答案:

没有答案