Android:Intent重新启动活动而不是指向主要活动

时间:2016-11-26 18:02:02

标签: java android android-studio

在我的应用中,我们有一个EnterPin活动,可以将引脚保存在SharedPreference中,并将其与您输入的内容进行比较。如果它是正确的,意图会将您带到MainActivity并传​​递一个带有键的真正布尔值"已验证"

出于某种原因,在模拟器和我的s7上,输入正确的引脚(通过调试确认)后,它只是重新启动EnterPinActivity。

最令人讨厌的部分是它有时会起作用,有时却不起作用。我不明白可能导致这个问题的原因。

EnterPin.java

public class EnterPin extends AppCompatActivity {
//Used to check if there is a pin
SharedPreferences preferences;

//Title of the private file for the pin
public final String PINFILE = "PinFile";

private int pin;

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

    pin = getPinFromFile();

    //TODO::add similar check for security questions in case they exit the app during creation
    //If the user did not create a pin, send to create one and end this activity
    if(pin == -1) {
        forceCreatePin();
        finish();
    }

    Button logBtn = (Button)findViewById(R.id.logBtn);
    Button forgotBtn = (Button)findViewById(R.id.forgotPin);
}

public void onClick(View v){
    if(v.getId() == R.id.logBtn){
        EditText pinIn = (EditText) findViewById(R.id.enterPin);
        String pinStr = pinIn.getText().toString();
        if (pinStr.length() == 4) {
            int pinInt = Integer.parseInt(pinStr);
            if (pin == pinInt) {
                //Login
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("verified", true);
                startActivity(intent);
                finish();
            } else {
                //clear input and notify user of wrong pin
                pinIn.setText("");
                Toast toast = Toast.makeText(getApplicationContext(), "Incorrect PIN", Toast.LENGTH_SHORT);
                toast.show();
            }
        } else {
            pinIn.setText("");
            Toast toast = Toast.makeText(getApplicationContext(), "PIN must be 4 characters", Toast.LENGTH_SHORT);
            toast.show();
        }
    }else if(v.getId() == R.id.forgotPin){
        Intent intent = new Intent(getApplicationContext(), ForgotPIN.class);
        startActivity(intent);
        finish();
    }

}

private int getPinFromFile() {
    preferences = getSharedPreferences(PINFILE, MODE_PRIVATE);
    //Returns value at key "pin" if it exists, -1 if pin is not created
    return preferences.getInt(PINFILE, -1);
}

private void forceCreatePin() {
    Intent intent = new Intent(this, CreatePin.class);
    startActivity(intent);
}
}

MainActivity.java

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

    //get verified key from intent activity was started with, set false if key not found
    isVerified = getIntent().getBooleanExtra("verified", false);
    if (!isVerified) {
        forceEnterPin();
    }

 //We create the db in the main class
 try {
     db = this.openOrCreateDatabase("budgetDB", MODE_PRIVATE, null);
     System.out.println("Succes!!!!!!!");

 }
 catch(Exception e)
 {
     System.out.println("It got caught....");
     Log.e("BudgetDatabase ERROR", "Error Creating/Loading database");
 }
    Database budDB = new Database(db);
    budDB.createTables();


    //Loading variables, settings the first fragment to the home screen
    spendableInc = loadSpendableInc();
    FragmentTransaction trans = getFragmentManager().beginTransaction();
    HomeFragment homeFragment = new HomeFragment();
    trans.add(R.id.frag_container, homeFragment, "home").commit();


    //Settings functionality for the bottom navigation bar
    final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frag_container);
    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        FragmentManager manager = getFragmentManager();
        final FragmentTransaction transaction = manager.beginTransaction();
        //Handling clicks on home, transaction, or overview
        switch (item.getItemId()) {
            case R.id.action_home:
                HomeFragment homeFragment = new HomeFragment();
                transaction.replace(R.id.frag_container, homeFragment, "home").commit();
                break;
            case R.id.action_transactions:
                TransactionFragment transactionFragment = new TransactionFragment();
                transaction.replace(R.id.frag_container, transactionFragment, "transaction").commit();
                break;
            case R.id.action_overview:
                OverviewFragment overviewFragment = new OverviewFragment();
                transaction.replace(R.id.frag_container, overviewFragment, "overview").commit();
                break;
        }
        return false;
    }
});

}

/**
 * Auto-generated method for toolbar
 * @param menu
 * @return
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

/**
 * Auto-generated method for toolbar
 * @param item
 * @return
 */
@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;
    } else if (id == R.id.logout) {
        forceEnterPin();
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void saveSpendableInc(float amt) {
    SharedPreferences.Editor editor = getSharedPreferences(SPENDABLE_INCOME, MODE_PRIVATE).edit();
    editor.putFloat(SPENDABLE_INCOME, amt);
    editor.commit();
}

public float loadSpendableInc() {
    SharedPreferences prefs = getSharedPreferences(SPENDABLE_INCOME, MODE_PRIVATE);
    return prefs.getFloat(SPENDABLE_INCOME, MODE_PRIVATE);
}

public void createIncome(View view) {
    Intent intent = new Intent(this, CreateIncome.class);
    intent.putExtra(SPENDABLE_INCOME, spendableInc);
    startActivity(intent);
}

public void createExpense(View view) {
    Intent intent = new Intent(this, CreateExpense.class);
    intent.putExtra(SPENDABLE_INCOME, spendableInc);
    startActivity(intent);
}

/**
 * Closes the database when the application is terminated
 * Set verified to false to force
 */
@Override
protected void onDestroy(){
    super.onDestroy();
    db.close();
    getIntent().putExtra("verified", false);
    idleStart = 0;
    idleFinish = 0;
}

//Forces user to create pin and ends the main activity so the user can't use the back button to get to home screen
private void forceEnterPin() {
    getIntent().putExtra("verified", false);
    Intent intent = new Intent(this, EnterPin.class);
    startActivity(intent);
    //finish();
}

@Override
protected void onPause(){
    super.onPause();
    Calendar tmpCalendar = Calendar.getInstance();
    idleStart = tmpCalendar.get(Calendar.MINUTE);
}

@Override
protected void onStop(){
    super.onStop();
    Calendar tmpCalendar = Calendar.getInstance();

    //If app went straight to stop phase, start at 0
    //If app started at pause and then went to stop, add time from before
    if(idleStart == 0)
        idleStart = tmpCalendar.get(Calendar.MINUTE);
    else
        idleStart += tmpCalendar.get(Calendar.MINUTE);
}

@Override
protected void onResume(){
    super.onResume();
    //Use calendar object to get the current time in minutes
    Calendar tmpCalendar = Calendar.getInstance();
    idleFinish = tmpCalendar.get(Calendar.MINUTE);
    if(idleFinish - idleStart >= 30)
        forceEnterPin();

    //Reset idle times because user started app again
    idleStart = 0;
    idleFinish = 0;
}
}

1 个答案:

答案 0 :(得分:-1)

答案:在您开始为您开展活动之前,请先阅读您使用的API。