-3

enter image description here

I have this error by pressing the "note" (cardview). The delete action should be on the toolbar and not up it. Can you help me? Since i cannot post the activity here i post the url: https://github.com/Heromine/tempapp1/blob/master/MainActivity.java Sorry If you need more info just ask. Thank you for the help

public class MainActivity extends RoboActionBarActivity
    implements NavigationView.OnNavigationItemSelectedListener
    {
private static final int NEW_NOTE_RESULT_CODE = 4;
private static final int EDIT_NOTE_RESULT_CODE = 5;
@InjectView(android.R.id.empty)   private TextView emptyListTextView;
@InjectView(android.R.id.list)    private ListView listView;
@InjectView(R.id.fab) private FloatingActionButton addNoteButton;

@Inject private NoteDAO noteDAO;

private ArrayList<Integer> selectedPositions;
private ArrayList<NotesAdapter.NoteViewWrapper> notesData;
private NotesAdapter listAdapter;
private ActionMode.Callback actionModeCallback;
private ActionMode actionMode;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar); //       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Snackbar.make(view, "Nota in salvataggio...", Snackbar.LENGTH_LONG)
              //      .setAction("Action", null).show();

                // Crear una nota nueva
                startActivityForResult(EditNoteActivity.buildIntent(MainActivity.this), NEW_NOTE_RESULT_CODE);
        }

    });
    selectedPositions = new ArrayList<>();
    setupNotesAdapter();
    setupActionModeCallback();
    setListOnItemClickListenersWhenNoActionMode();
    updateView();

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

    SharedPreferences settings = getSharedPreferences("prefs", 0);
    boolean firstRun = settings.getBoolean("firstRun", true);
     if ( firstRun )
    {  // here run your first-time instructions, for example :
        Intent intent = new Intent(this, MyIntro.class);
        startActivity(intent);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("firstRun", false);
        editor.commit();
    }

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.action_settings:
            startActivity(new Intent("android.intent.action.SettingsActivity"));
            return true;

        case R.id.action_donate:
            Snackbar.make(this.findViewById(android.R.id.content), "Questo contenuto non è ancora disponibile", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            //startActivity(new Intent("android.intent.action.DonateActivity"));
            return true;

        default:
            return super.onOptionsItemSelected(item);

    }


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



@SuppressWarnings("StatementWithEmptyBody")

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

    if (id == R.id.nav_camara) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

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

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

    } else if (id == R.id.nav_share) {
        Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=notes.service.com.servicenotes"));
        startActivity(i2);

    } else if (id == R.id.action_bug){
        Intent intent = new Intent(this, Gitty.class);
        startActivity(intent);
        return true;

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == NEW_NOTE_RESULT_CODE) {
        if (resultCode == RESULT_OK) addNote(data);
    }
    if (requestCode == EDIT_NOTE_RESULT_CODE) {
        if (resultCode == RESULT_OK) updateNote(data);
    }

    super.onActivityResult(requestCode, resultCode, data);
}

/** Crea la llamada al modo contextual. */
private void setupActionModeCallback() {
    actionModeCallback = new ActionMode.Callback() {

        /** {@inheritDoc} */
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            setListOnItemClickListenersWhenActionMode();
            // inflar menu contextual
            mode.getMenuInflater().inflate(R.menu.context_note, menu);
            return true;
        }

        /** {@inheritDoc} */
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Nada
            return false;
        }

        /** {@inheritDoc} */
        @Override
        public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                // borrar notas solo si hay notas a borrar; sino se acaba el modo contextual.
                case R.id.action_delete:
                    if (!selectedPositions.isEmpty()) {
                        new AlertDialog.Builder(MainActivity.this)
                                .setMessage(getString(R.string.delete_notes_alert, selectedPositions.size()))
                                .setNegativeButton(android.R.string.no, null)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        deleteNotes(selectedPositions);
                                        mode.finish();
                                    }
                                })
                                .show();
                    } else mode.finish();
                    return true;
                default:
                    return false;
            }
        }

        /** {@inheritDoc} */
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // Regresar al modo normal
            setListOnItemClickListenersWhenNoActionMode();
            resetSelectedListItems();
        }
    };
}

/** Inicializa el adaptador de notas. */
private void setupNotesAdapter() {
    notesData = new ArrayList<>();
    for (Note note : noteDAO.fetchAll()) {
        NotesAdapter.NoteViewWrapper noteViewWrapper = new NotesAdapter.NoteViewWrapper(note);
        notesData.add(noteViewWrapper);
    }
    listAdapter = new NotesAdapter(notesData);
    listView.setAdapter(listAdapter);
}

/** Actualiza la vista de esta actividad cuando hay notas o no hay notas. */
private void updateView() {
    if (notesData.isEmpty()) { // Mostrar mensaje
        listView.setVisibility(View.GONE);
        emptyListTextView.setVisibility(View.VISIBLE);
    } else { // Mostrar lista
        listView.setVisibility(View.VISIBLE);
        emptyListTextView.setVisibility(View.GONE);
    }
}

/**
 * Agrega una nota a lista y la fuente de datos.
 *
 * @param data los datos de la actividad de edición de notas.
 */
private void addNote(Intent data) {
    Note note = EditNoteActivity.getExtraNote(data);
    noteDAO.insert(note);
    NotesAdapter.NoteViewWrapper noteViewWrapper = new NotesAdapter.NoteViewWrapper(note);
    notesData.add(noteViewWrapper);
    updateView();
    listAdapter.notifyDataSetChanged();
}
/**
 * Borra notas de la lista y de la fuente de datos.
 *
 * @param selectedPositions las posiciones de las notas en la lista.
 */
private void deleteNotes(ArrayList<Integer> selectedPositions) {
    ArrayList<NotesAdapter.NoteViewWrapper> toRemoveList = new ArrayList<>(selectedPositions.size());
    // Primero borra de la base de datos
    for (int position : selectedPositions) {
        NotesAdapter.NoteViewWrapper noteViewWrapper = notesData.get(position);
        toRemoveList.add(noteViewWrapper);
        noteDAO.delete(noteViewWrapper.getNote());
    }
    // Y luego de la vista (no al mismo tiempo porque pierdo las posiciones que hay que borrar)
    for (NotesAdapter.NoteViewWrapper noteToRemove : toRemoveList) notesData.remove(noteToRemove);
    updateView();
    listAdapter.notifyDataSetChanged();
}

/**
 * Actualiza una nota en la lista y la fuente de datos.
 *
 * @param data los datos de la actividad de edición de notas.
 */
private void updateNote(Intent data) {
    Note updatedNote = ViewNoteActivity.getExtraUpdatedNote(data);
    noteDAO.update(updatedNote);
    for (NotesAdapter.NoteViewWrapper noteViewWrapper : notesData) {
        // Buscar la nota vieja para actulizarla en la vista
        if (noteViewWrapper.getNote().getId().equals(updatedNote.getId())) {
            noteViewWrapper.getNote().setTitle(updatedNote.getTitle());
            noteViewWrapper.getNote().setContent(updatedNote.getContent());
            noteViewWrapper.getNote().setUpdatedAt(updatedNote.getUpdatedAt());
        }
    }
    listAdapter.notifyDataSetChanged();
}

/** Reinicia las notas seleccionadas a no seleccionadas y limpia la lista de seleccionados. */
private void resetSelectedListItems() {
    for (NotesAdapter.NoteViewWrapper noteViewWrapper : notesData) noteViewWrapper.setSelected(false);
    selectedPositions.clear();
    listAdapter.notifyDataSetChanged();
}

/**
 * Inicializa las acciones de la lista al hacer click en sus items cuando NO esta activo el
 * modo contextual.
 */
private void setListOnItemClickListenersWhenNoActionMode() {
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Ver la nota al hacer click
            startActivityForResult(ViewNoteActivity.buildIntent(MainActivity.this, notesData.get(position).getNote()), EDIT_NOTE_RESULT_CODE);
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            // Iniciar modo contextual para selección de items
            notesData.get(position).setSelected(true);
            listAdapter.notifyDataSetChanged();
            selectedPositions.add(position);
            actionMode = startSupportActionMode(actionModeCallback);
            actionMode.setTitle(String.valueOf(selectedPositions.size()));
            return true;
        }
    });
}

/**
 * Inicializa las acciones de la lista al hacer click en sus items cuando esta activo el menu
 * contextual.
 */
private void setListOnItemClickListenersWhenActionMode() {
    listView.setOnItemLongClickListener(null);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Agregar items a la lista de seleccionados y cambiarles el fondo.
            // Si se deseleccionan todos los items, se acaba el modo contextual
            if (selectedPositions.contains(position)) {
                selectedPositions.remove((Object) position); // no quiero el índice sino el objeto
                if (selectedPositions.isEmpty()) actionMode.finish();
                else {
                    actionMode.setTitle(String.valueOf(selectedPositions.size()));
                    notesData.get(position).setSelected(false);
                    listAdapter.notifyDataSetChanged();
                }
            } else {
                notesData.get(position).setSelected(true);
                listAdapter.notifyDataSetChanged();
                selectedPositions.add(position);
                actionMode.setTitle(String.valueOf(selectedPositions.size()));
            }
        }
    });
}

}

Jonathan I
  • 240
  • 1
  • 4
  • 18

2 Answers2

1

In manifest you will declare that you want to use "MyAppTheme" as style.

<application
        ..
        android:theme="@style/MyAppTheme"
        ..>

Notice that you need to remove similar line for .MainActivity in manifest. Currently you close the tag and manifest structure is not clean.

Now most important: In styles define new style as follow:

<style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="windowActionModeOverlay">true</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

</style>

That would be solution and it will insure that ActionMode items are doesn't "push" down Toolbar.


Few more important things:

  • Localize all your strings (don't hardcode half in english, half italian)
  • Your new best friend is ctrl+alt+L on Win or cmd+alt+L on mac. This shortcutwill auto format code in classes and xmls for you (At the moment code in your project is hard to read because there is no alignment and it looks messy)
  • Consider using Dagger2 or simpler, but less powerful ButterKnife instead of RoboJuice. If you didn't take this project from somebody else (like it looks) you will know what I am talking about
  • You shouldn't hardcode api keys and publish them on github. It is not secure and anybody who see those can do anything with your accounts. I should make this bold.
  • You shouldn't commit apk to repo if you don't want to give app for free (by code seems like you didn't planed but apk is commited)
  • In general you need to organise better Android Studio project and pay attention what you commit. Now there is a lot of mess in that repo
  • Don't use blindly other people code that you don't understand.
Ewoks
  • 12,285
  • 8
  • 58
  • 67
  • Thanks for everything, the error was in the manifest because i assigned a theme to an activity and not to the application – Jonathan I Dec 06 '15 at 14:32
0

Assuming that your theme looks similar to the following:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Try the following:

In your manifest, where you declare your activity, declare the Theme of the activity to be AppTheme.NoActionBar...

    <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar">

That will get rid of the 2nd ActionBar at the top. If you DO want that ActionBar, then you can try the following:

toolbar.inflateMenu(R.menu.main);

right after you create the toolbar.

Let me know if that works.

C2H6O
  • 166
  • 2
  • 13