工具栏崩溃应用程序上的设置按

时间:2017-06-16 09:40:02

标签: java android xml android-layout navigation-drawer

2天是我正在尝试解决此问题的当前时间,但仍然没有解决方案,基本上我创建了一个简单的导航抽屉,它有一个工具栏,浮动操作按钮和一个导航(android studio的默认活动)。 / p>

之后我尝试改变它,我在样式上编辑了它的图标:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimaryDark">@color/nephritis</item>
    <item name="colorControlActivated">@color/emerald</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
    <item name="android:spinnerStyle">@style/mySpinnerItemStyle</item>
</style>


<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_user</item>
    <item name="android:tint">@color/white</item>
</style>

我认为我做了一些破坏我的工具栏的更改,所以基本上我将工具栏和其他一些东西包括在我的主要活动中:

我的主要活动

<?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"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_plant_feed"
        app:layout_widthPercent="100%"
        app:layout_heightPercent="8%"
        app:layout_marginTopPercent="0%"
        app:layout_marginLeftPercent="0%" />


    <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_plant_feed"
        app:menu="@menu/activity_plant_feed_drawer"
        android:background="@color/white"/>

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

然后我有了包含的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.afcosta.inesctec.pt.android.PlantFeed">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/emerald"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:backgroundTint="#f1c40f"
        android:src="@android:drawable/ic_menu_camera" />

    <include layout="@layout/content_plant_feed" />

</android.support.design.widget.CoordinatorLayout>

我的活动课程:

public class PlantFeed extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,PlantFeedAdapter.OnItemClickListener {

    //initialize fields

    String token;

    ArrayList<PlantPhotoUser> photos = new ArrayList<>();

    VolleyService mVolleyService;
    IResult mResultCallback = null;
    final String GETREQUEST = "GETCALL";

    String connectionTxt;

    String URL;

    String date;
    String lat;
    String lon;
    String alt;

    PlantFeedAdapter plantFeedAdapter;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plant_feed);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        connectionString connection = ((connectionString) getApplicationContext());
        connectionTxt = connection.getGlobalVarValue();

        URL = connectionTxt + "/fotos";


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(PlantFeed.this,CameraCapture.class);
                startActivity(i);
            }
        });

        DrawerLayout 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.setDrawerListener(toggle);
        toggle.syncState();

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

        recyclerView = (RecyclerView)findViewById(R.id.recycleView2);
        recyclerView.setHasFixedSize(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        plantFeedAdapter = new PlantFeedAdapter(getApplicationContext(), photos,PlantFeed.this);
        recyclerView.setAdapter(plantFeedAdapter);

        token = checkForToken();

        initVolleyCallback();

        mVolleyService = new VolleyService(mResultCallback,this);

        mVolleyService.getDataVolley(GETREQUEST,URL,token);

    }

    void initVolleyCallback(){
        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType,JSONObject response) {
                Log.d("HELLL","hi1");
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                PlantPhotoUser plantPhotoUser;
                Log.d("HELLLL","hi");
                for (int i=0; i < response.length(); i++) {
                    try {
                        JSONObject object = response.getJSONObject(i);
                        Log.d("objeto",object.toString());

                        int userId = object.getInt("userId");
                        Log.d("objeto",String.valueOf(userId));
                        String username = object.getJSONObject("user").getString("username");
                        Log.d("objeto",String.valueOf(username));
                        int plantId = object.getInt("plantId");
                        Log.d("objeto",String.valueOf(plantId));
                        String specie = object.getJSONObject("plant").getString("specie");
                        Log.d("objeto",String.valueOf(specie));

                        String path = object.getString("image");
                        Log.d("objeto",String.valueOf(path));
                        int fotoId = object.getInt("id");

                        if(object.getString("date") != null){
                            date = object.getString("date");
                        }

                        if(object.getString("lat") != null){
                            lat = object.getString("lat");
                        }

                        if(object.getString("lon") != null){
                            lon = object.getString("lon");
                        }

                        if(object.getString("altitude") != null){
                            alt = object.getString("altitude");
                        }

                        plantPhotoUser = new PlantPhotoUser(fotoId,plantId,userId,path,specie,date,lat,lon,alt,username);
                        photos.add(plantPhotoUser);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                plantFeedAdapter.notifyDataSetChanged();

            }

            @Override
            public void notifyError(String requestType,VolleyError error) {
                Log.d("FAIL",error.toString());
            }
        };
    }

    public String checkForToken() {
        SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
        String tokenKey = getResources().getString(R.string.token);
        String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
        return token;
    }

    @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.plant_feed, 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_camera) {
            Intent i = new Intent(PlantFeed.this,CameraCapture.class);
            startActivity(i);
        } else if (id == R.id.nav_gallery) {
            Intent i = new Intent(PlantFeed.this,PlantFeed.class);
            startActivity(i);
        } else if (id == R.id.nav_slideshow) {
            Intent i = new Intent(PlantFeed.this,FamilyLibrary.class);
            startActivity(i);
        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        }

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

    @Override
    public void onRowClick(int position, String name, int id, View view) {

    }

    @Override
    public void onTitleClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,PhotosForPlant.class);
        i.putExtra("plantId",String.valueOf(id));
        startActivity(i);
    }

    @Override
    public void onImageClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,PhotosForPlant.class);
        i.putExtra("plantId",String.valueOf(id));
        startActivity(i);
    }

    @Override
    public void onReportClicked(int position, int id, String name, View clickedview) {
        Log.d("HELLLO","HELLOO");
        showDialogReport(id,name);
    }



    @Override
    public void onUserIconClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,UserProfile.class);
        i.putExtra("userId",id);
        startActivity(i);
    }

    @Override
    public void onUsernameClicked(int position, int id, View clickedview) {
        Intent i = new Intent(this,UserProfile.class);
        i.putExtra("userId",id);
        startActivity(i);
    }

    @Override
    public void onAvaliationClicked(int position, int id, String name, View clickedview) {

    }


    private void showDialogReport(int id, String name) {
        Log.d("HELLLO","HELLOO");
        AlertDialog.Builder builder = new AlertDialog.Builder(PlantFeed.this);
        builder.setTitle(name);
        builder.setMessage("Tem a certeza que pretende reportar a fotografia?");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //TODO reportar base de dados
            }
        });
        builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

最后是菜单布局:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"/>
</menu>

我想显示菜单,但它从未显示,它之前崩溃了,我得到了这个堆栈跟踪:

FATAL EXCEPTION: main
                                                                                         Process: com.example.afcosta.inesctec.pt.android, PID: 12537
                                                                                         java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                                             at android.support.v7.view.menu.ListMenuItemView.setTitle(ListMenuItemView.java:127)
                                                                                             at android.support.v7.view.menu.ListMenuItemView.initialize(ListMenuItemView.java:113)
                                                                                             at android.support.v7.view.menu.MenuAdapter.getView(MenuAdapter.java:100)
                                                                                             at android.support.v7.view.menu.MenuPopup.measureIndividualMenuWidth(MenuPopup.java:160)
                                                                                             at android.support.v7.view.menu.StandardMenuPopup.tryShow(StandardMenuPopup.java:153)
                                                                                             at android.support.v7.view.menu.StandardMenuPopup.show(StandardMenuPopup.java:187)
                                                                                             at android.support.v7.view.menu.MenuPopupHelper.showPopup(MenuPopupHelper.java:290)
                                                                                             at android.support.v7.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:175)
                                                                                             at android.support.v7.widget.ActionMenuPresenter$OpenOverflowRunnable.run(ActionMenuPresenter.java:803)
                                                                                             at android.os.Handler.handleCallback(Handler.java:751)
                                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                                             at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

我在堆栈跟踪上没有任何关于这些名称的活动,它们存在是因为导航创建了它们internaly所以我不知道如何避免这个错误,任何帮助?

适配器代码:

package com.example.afcosta.inesctec.pt.android.Adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.afcosta.inesctec.pt.android.R;
import com.example.afcosta.inesctec.pt.android.modelView.PlantPhotoUser;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by FilipeCosta on 29/05/2017.
 */

public class PlantFeedAdapter extends RecyclerView.Adapter<PlantFeedAdapter.ViewHolder> {

    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onRowClick(int position, String name, int id, View view);
        void onTitleClicked(int position, int id, View clickedview);
        void onImageClicked(int position,int id, View clickedview);
        void onReportClicked(int position, int id,String name, View clickedview);
        void onUserIconClicked(int position, int id, View clickedview);
        void onUsernameClicked(int position, int id, View clickedview);
        void onAvaliationClicked(int position, int id,String name, View clickedview);

    }

    private ArrayList<PlantPhotoUser> photos;
    private Context context;

    public PlantFeedAdapter(Context context, ArrayList<PlantPhotoUser> photos, OnItemClickListener listener) {
        this.photos = photos;
        this.context = context;
        this.listener = listener;
    }

    @Override
    public PlantFeedAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.plant_feed_row, viewGroup, false);
        return new ViewHolder(view);
    }


    @Override
    public void onBindViewHolder(final PlantFeedAdapter.ViewHolder viewHolder, final int i) {
        viewHolder.name.setText(photos.get(i).getSpecie());
        viewHolder.username.setText(photos.get(i).getUsernName());
        viewHolder.data.setText(photos.get(i).getDate().split("T")[0]);
        Log.d("data123",(photos.get(i).getDate().toString()));

        String urlFoto = "http://fe1b7efd.ngrok.io/" + photos.get(i).getPath();

        if(urlFoto.toLowerCase().contains("public/")){
            urlFoto = urlFoto.replace("public/","");
        }

        viewHolder.userIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onUserIconClicked(viewHolder.getAdapterPosition(), photos.get(i).getUserId(), view);
                }
            }
        });

        viewHolder.username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onUsernameClicked(viewHolder.getAdapterPosition(),photos.get(i).getUserId(), view);
                }
            }
        });

        viewHolder.plantImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onImageClicked(viewHolder.getAdapterPosition(), photos.get(i).getIdPlant(), view);
                }
            }
        });


        viewHolder.name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onTitleClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),v);
                }
            }
        });

        viewHolder.reportImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onReportClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
                }
            }
        });

        /*viewHolder.avaliationFoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onAvaliationClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
                }
            }
        });*/



        Picasso.with(context)
                .load(urlFoto)
                .resize(300, 300)
                .into(viewHolder.plantImg);
    }

    @Override
    public int getItemCount() {
        return photos.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView name;
        private ImageView userIcon;
        private TextView avaliationFoto;
        private ImageView plantImg;
        private ImageView foto;
        private TextView username;
        private ImageView reportImage;
        private TextView data;
        public ViewHolder(View view) {
            super(view);
            data = (TextView)view.findViewById(R.id.data);
            name = (TextView) view.findViewById(R.id.plantName);
            userIcon = (ImageView)view.findViewById(R.id.userIcon);
            plantImg = (ImageView)view.findViewById(R.id.plantPhoto);;
            username = (TextView)view.findViewById(R.id.password);
            reportImage = (ImageView)view.findViewById(R.id.cameraForbiden);

        }
    }


}

0 个答案:

没有答案