2014-04-08 3 views
0

간단한 도서 목록 신청서를 작성하려고합니다. 앱 문제는 다음과 같습니다. 주 활동에서 '새 책 활동'으로 이동 한 다음 '저장'버튼을 클릭하면 주로 돌아옵니다. 하지만 여기에서 '뒤로'하드웨어 버튼을 누르면 '새 책 활동'으로 돌아갑니다. 이 문제를 어떻게 해결할 수 있습니까?안드로이드 문제 해결 닫기 버튼으로 주요 활동을 닫습니다

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

} 

편집 :

여기 NewBookActivity 코드 : 당신 당신의 주요 활동으로 돌아가 startActivity(...)를 호출하는 것보다 오히려

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();  
} 
} 
+0

NewBookActivity의 저장 단추 클릭 처리기 코드를 공유 할 수 있습니까? –

답변

1

, finish() 전화 여기

는 MA 코드입니다 NewBookActivity에서 저장 버튼을 클릭하십시오.

또는 매니페스트의 기본 활동에 android:launchMode="singleTask"을 추가하면 기본 활동으로 돌아가서 작업 스택을 지울 때마다 언제든지 취소 할 수 있습니다.

+0

감사합니다. 어제이 솔루션에 대해 생각하고있었습니다. 최대한 빨리 시도하겠습니다! :) – d33pcode

+0

NewBookActivity 코드를 약간 추가하겠습니다. – d33pcode

+0

그게 효과가 있었나요? 또한 NewBookActivity 대신 MainActivity 코드를 다시 추가 한 것처럼 보입니다. – dharms