Pergunta

I'm trying to work at a simple book listing application. The app problem is that: if i move from Main Activity to 'New Book Activity', then I click on 'save' button, it comes back to Main. But if I press 'back' hardware button from here, it comes back to 'New Book Activity'. How can I fix this?

Here's the MA code:

package com.ecpay.book_database_test;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;

import android.view.KeyEvent;

import com.ecpay.book_database_test.DbAdapter;

public class MainActivity extends Activity implements ActionBar.TabListener {

Button newbook_btn;
Button empty_btn;
TextView nobooks_txt;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
 * derivative, which will keep every loaded fragment in memory. If this
 * becomes too memory intensive, it may be best to switch to a
 * {@link android.support.v13.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

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

    // Switch to NewbookActivity through newbook_btn
    newbook_btn = (Button)findViewById(R.id.newbook_btn);
    newbook_btn.setOnClickListener(
            new View.OnClickListener() {
                    public void onClick(View aView) {
                           Intent toAnotherActivity = new Intent(aView.getContext(), NewbookActivity.class);
                           startActivityForResult(toAnotherActivity, 0);
                    }
            }
    );

    // Check if Database has registered data, to check if nobook_txt has to be shown or not
    nobooks_txt = (TextView)findViewById(R.id.textView1);
    final File DatabaseFile = new File("/data/data/com.ecpay.book_database_test/databases/mydatabase.db"); 
    if (DatabaseFile.exists()) {
        nobooks_txt.setVisibility(View.INVISIBLE);
        //nobooks_text.setVisibility(View.VISIBLE);
        //nobooks_text.setVisibility(View.GONE);
    }

    // Empty all the Database through empty_btn
    empty_btn = (Button)findViewById(R.id.empty_btn);
    empty_btn.setOnClickListener(
            new View.OnClickListener() {
                    public void onClick(View aView) {
                        DbAdapter db = new DbAdapter(getApplicationContext());
                        db.open();
                        DatabaseFile.delete();
                        db.fetchAllBooks();
                        db.close();
                    }
            }
    );

    // Display Database values
    ListView BookList = (ListView)findViewById(R.id.listView1);
    DbAdapter db = new DbAdapter(getApplicationContext());
    db.open();
    Cursor cursor = db.fetchAllBooks();
    startManagingCursor(cursor);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.book, cursor, new String[]{DbAdapter.KEY_TITLE,DbAdapter.KEY_AUTHOR},new int[]{R.id.booktitle,R.id.bookauthor});
    BookList.setAdapter(adapter);
    int TitleCol = cursor.getColumnIndex(DbAdapter.KEY_TITLE);
    int AuthorCol = cursor.getColumnIndex(DbAdapter.KEY_AUTHOR);
    if(cursor.moveToFirst()) {
            while (cursor.moveToNext());
    }
    db.close();
}

@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) {
    // 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();
    return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
        // below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        TextView textView = (TextView) rootView
                .findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
}
    @Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

}

EDIT:

Here's the NewBookActivity code:

package com.ecpay.book_database_test;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import com.ecpay.book_database_test.DbAdapter;

public class MainActivity extends Activity {

Button newbook_btn;
Button empty_btn;
TextView nobooks_txt;

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

    // Switch to NewbookActivity through newbook_btn
    newbook_btn = (Button)findViewById(R.id.newbook_btn);
    newbook_btn.setOnClickListener(
            new View.OnClickListener() {
                    public void onClick(View aView) {
                           Intent toAnotherActivity = new Intent(aView.getContext(), NewbookActivity.class);
                           startActivityForResult(toAnotherActivity, 0);
                    }
            }
    );

    // Check if Database has registered data, to check if nobook_txt has to be shown or not
    nobooks_txt = (TextView)findViewById(R.id.textView1);
    final File DatabaseFile = new File("/data/data/com.ecpay.book_database_test/databases/mydatabase.db"); 
    if (DatabaseFile.exists()) {
        nobooks_txt.setVisibility(View.INVISIBLE);
    }

    // Empty all the Database through empty_btn
    empty_btn = (Button)findViewById(R.id.empty_btn);
    empty_btn.setOnClickListener(
            new View.OnClickListener() {
                    public void onClick(View aView) {
                        DbAdapter db = new DbAdapter(getApplicationContext());
                        db.open();
                        DatabaseFile.delete();
                        db.close();
                    }
            }
    );

    // Display Database values
    ListView BookList = (ListView)findViewById(R.id.listView1);
    DbAdapter db = new DbAdapter(getApplicationContext());
    db.open();
    Cursor cursor = db.fetchAllBooks();
    startManagingCursor(cursor);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.book, cursor, new String[]{DbAdapter.KEY_TITLE,DbAdapter.KEY_AUTHOR},new int[]{R.id.booktitle,R.id.bookauthor});
    BookList.setAdapter(adapter);
    if(cursor.moveToFirst()) {
            while (cursor.moveToNext());
    }
    db.close();    
}   
}
Foi útil?

Solução

Rather than calling startActivity(...) to go back to your main activity, call finish() when you click the save button in your NewBookActivity.

Alternatively, you can add android:launchMode="singleTask" to your main activity in your manifest so that any time you go back to the main activity it clears the task stack.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top