从导航栏中选择项目时 - 应用程序崩溃

时间:2015-12-06 13:02:25

标签: android android-studio fragment navigation-drawer android-adapterview

这是MainActivity的代码:

package com.example.amit.java5776_7546_8412;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import entities.Book;
import model.backend.Backend;
import model.backend.BackendFactory;


public class MainActivity extends AppCompatActivity/* implements View.OnClickListener*/ {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private CharSequence mTitle;
    private CharSequence mDrawerTitle;
    private ActionBarDrawerToggle mDrawerToggle;
    private Toolbar topToolBar;  
    private MenuItem mSearchAction;
    private boolean isSearchOpened = false;

    // Search list:
    private ListView searchResultList;
    private ArrayAdapter<Book> adapter;
    private ArrayList<Book> bookList;
    private SearchView searchView;
    private Backend backend;
    private ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backend = BackendFactory.getInstance(getApplicationContext());

        mTitle = mDrawerTitle = getTitle();

        topToolBar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(topToolBar);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        String[] titles = getResources().getStringArray(R.array.drawer_titles);
        List<ItemObject> drawerItems = new ArrayList<>();
        drawerItems.add(new ItemObject(titles[0], R.mipmap.login));
        drawerItems.add(new ItemObject(titles[1], R.mipmap.clock));
        drawerItems.add(new ItemObject(titles[2], R.mipmap.coins));
        drawerItems.add(new ItemObject(titles[3], R.mipmap.message));
        drawerItems.add(new ItemObject(titles[4], R.mipmap.settings));

        mDrawerList.setAdapter(new CustomAdapter(this, drawerItems));

        mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                actionBar = getSupportActionBar();
                if (actionBar != null)
                    actionBar.setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                actionBar = getSupportActionBar();
                if(actionBar != null)
                    actionBar.setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.setDrawerIndicatorEnabled(true);
        actionBar = getSupportActionBar();
        if(actionBar != null)
        {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // make Toast when click
                selectItemFragment(position);
            }
        });

        // Search List:
        searchResultList = (ListView)findViewById(R.id.lvBooks);
        bookList = new ArrayList<>();
        adapter = new ArrayAdapter<Book>(this, R.layout.row_layout, bookList){
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView =  View.inflate(MainActivity.this, R.layout.row_layout, null);
                }

                ImageView picture = (ImageView) convertView.findViewById(R.id.book_picture);
                TextView title = (TextView) convertView.findViewById(R.id.book_name);
                TextView author = (TextView) convertView.findViewById(R.id.book_author);
                TextView genre = (TextView) convertView.findViewById(R.id.book_genre);
                TextView price = (TextView) convertView.findViewById(R.id.book_price);

                Book book = this.getItem(position);
                picture.setImageResource(book.getBookPicture());
                title.setText(book.getBookName());
                author.setText(book.getAuthorName());
                genre.setText(book.getGenre());
                price.setText(Double.toString(book.getPrice()));

                return convertView;
            }
        };
        searchResultList.setAdapter(adapter);
        try {
            Book bd1 = new Book(R.mipmap.shulhan_aruh, "Genre 1", "Book 1", "Author 1", 100);
            backend.addBook(bd1);
            Book bd2 = new Book(R.mipmap.kaf_hahaim, "Genre 1", "Book 2", "Author 2", 89);
            adapter.addAll(backend.getBooksList());
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        // Click on item in book list:
        searchResultList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startActivity(new Intent(MainActivity.this, Details.class));
            }
        });



        // initItemByListView(2);
    }

    // TODO change sign in to sign out when signed
    private void selectItemFragment(int position){

        Fragment fragment = null;
        switch(position) {
            default:
            case 0:
                startActivity(new Intent(this, Login.class));
                return;
            case 1:
                fragment = new PurchaseHistoryFragment();
                break;
            case 2:
                fragment = new DefaultFragment();
                break;
            case 3:
                fragment = new DefaultFragment();
                break;
            case 4:
                fragment = new DefaultFragment();
                break;
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.lvBooks, fragment).commit();

        mDrawerList.setItemChecked(position, true);
//        setTitle(titles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        actionBar = getSupportActionBar();
        if(actionBar != null)
            actionBar.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);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @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, menu);
        return true;
    }

    @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);

        mSearchAction = menu.findItem(R.id.action_search);
        searchView = (SearchView)mSearchAction.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                adapter.clear();
                adapter.addAll(backend.searchForBook(query));
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });


        return super.onPrepareOptionsMenu(menu);
    }

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


        switch (id) {
            case R.id.action_search:
                handleMenuSearch();
                return true;
        }

        return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
    }


    protected void handleMenuSearch(){
        actionBar = getSupportActionBar(); //get the actionbar

        if(isSearchOpened){ //test if the search is open
            if(actionBar != null)
            {
                actionBar.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
                actionBar.setDisplayShowTitleEnabled(true); //show the title in the action bar
            }

            // add the search icon in the action bar
            mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_search));

            isSearchOpened = false;
        }
        else
        { // open the search entry
            if(actionBar != null)
            {
                actionBar.setDisplayShowCustomEnabled(true); //enable it to display a
                // custom view in the action bar.
                // action.setCustomView(R.layout.search_bar);//add the custom view
                actionBar.setDisplayShowTitleEnabled(false); //hide the title
            }

            // add the close icon
            mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_search));

            isSearchOpened = true;
        }
    }

    @Override
    public void onBackPressed() {
        if(isSearchOpened) {
            handleMenuSearch();
            return;
        }
        super.onBackPressed();
    }
}

当选择导航抽屉中的一个项目(第一个除外)时,程序会崩溃 我试图解决它很长一段时间 我认为(并且不确定)问题出在getView()函数中。

这是logcat:

FATAL EXCEPTION: main
java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
    at android.widget.AdapterView.addView(AdapterView.java:451)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1083)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)

我很难理解应用程序在哪一行崩溃 无论如何,这是应用程序崩溃前最新命令的顺序:

  1. mDrawerLayout.closeDrawer(mDrawerList);
  2. selectItemFragment(位置);在mDrawerList.setOnItemClickListener下(新的AdapterView.OnItemClickListener()
  3. 然后转到AdapterView.java
  4. 下的getOnItemClickListener()
  5. 然后此代码在AbsListView.java中:

                if (incrementalDeltaY != 0) {
                    // Coming back to 'real' list scrolling
                    if (mScrollY != 0) {
                        mScrollY = 0;
                        invalidateParentIfNeeded();
                    }
    
  6. 此代码位于Handler.java中:

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    
  7. 然后在Looper.java中循环并崩溃:

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
    
  8. 希望您能通过上述信息找到解决方案。

0 个答案:

没有答案