onActivityResult不遵守RESULT_OK到IF条件

时间:2014-10-30 10:57:30

标签: java android

由于基线代码,我从 MainActivity 类中获取 FirstConnection 类:

Intent intent = new Intent(MainActivity.this,FirstConnection.class) ;
startActivityForResult(intent, REQUEST_CODE_INITILIZATION);

完成 FirstConnection 类的活动后,我使用以下代码返回 MainActivity 类:

Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();

然后在 MainActivity 类中,我使用以下代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_INITILIZATION) {
        if (resultCode == Activity.RESULT_OK) {  //  <= !! Problem HERE !!

           // code

        }
        if (resultCode == RESULT_CANCELED) {

           // code

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

我的问题是:当我使用 resultCode == RESULT_OK 返回 MainActivity 类时,没有办法,我的代码没有& #39;进入 IF条件,尽管此条件为真

我真的不明白,我确定 resultCode == RESULT_OK ,因为我已经检查了DEBUG模式。

是否有人有类似的问题?

谢谢!

更新

我发布了两个班级内容。

MainActivity

public class MainActivity extends Activity implements NamesAdapterListener{

    private int REQUEST_CODE_INITILIZATION = 2 ; 


    private List<TitleList> listExisting ;
    private SQliteHelper db ;
    private TextView titleV;

    private CheckBox checkPartage;
    private CheckBox checkLocal;
    private EditText input;
    private LinearLayout layout;

    private LayoutInflater mInflater;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


//        boolean resultInitilization = appInitialization();
//        if (resultInitilization == false){
//          Intent intent = new Intent(MainActivity.this,FirstConnection.class) ;
//          startActivityForResult(intent, REQUEST_CODE_INITILIZATION);
//        }      

        /**
         * Opening of the database
         */
        db = new SQliteHelper( this ) ;


        /**
         * Initialization of the local database for the 1st time of use
         */
        db.Initialized();
        if (!db.getInitialized()){
            db.setInitialized();

            Intent intent = new Intent(MainActivity.this,FirstConnection.class) ;
            startActivityForResult(intent, REQUEST_CODE_INITILIZATION);

        }
        else{


            /**
             * Get the name of the existing lists
             */
            listExisting = db.getTitleSQliteHelper();  

            /**
             * Create an ArrayAdapter for the list's names
             */
            ArrayAdapterListNames listExistingAdapter = new ArrayAdapterListNames(this,listExisting) ;


            /**
             * Ecoute des évènements sur votre liste
             */
            listExistingAdapter.addListener(this);

            /**
             * 1) Implement the ListView containing the list of TextView
             * 2) registerForContextMenu => to display a pop-up menu after a long click on a the 
             * content of the ListView (TextView) 
             */
            ListView listNames = (ListView)findViewById(R.id.ListViewMain);
            registerForContextMenu(listNames);

            /**
             * Initialisation de la liste avec les données
             */
            listNames.setAdapter(listExistingAdapter);


            /**
             * Bouton pour ouverture nouvelle liste
             */
            final Button buttonsuiv = (Button) findViewById(R.id.btnnewliste);
            buttonsuiv.setOnClickListener(new View.OnClickListener() {


                /**
                 * Dialog window to ask if the user wants to create a new list
                 */
                @Override
                public void onClick(View v) {

                    AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

                    // Instantiate the xml file
                    mInflater = (LayoutInflater) MainActivity.this.getSystemService(MainActivity.this.LAYOUT_INFLATER_SERVICE);
                    LinearLayout layout = (LinearLayout) mInflater.inflate( R.layout.dialogbox_main_activity , null) ;

                    input = (EditText)layout.findViewById(R.id.titleSet);
                    checkPartage = (CheckBox)layout.findViewById(R.id.partage);
                    checkLocal = (CheckBox)layout.findViewById(R.id.local);

                    alert.setTitle("Création d'une nouvelle liste");
                    alert.setMessage("Tapez le nom de la nouvelle liste:");

                    // Set an EditText view to get user input 
                    final EditText input = new EditText(MainActivity.this);
                    alert.setView(layout);

                    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                          String value = input.getText().toString() ;
                          // Do something with value!

                          if ( checkPartage.isChecked() ){

                              Intent intent = new Intent(MainActivity.this, ListingArticlesDropb.class);
                              intent.putExtra("Title",value);
                              startActivity(intent);

                          }
                          else if ( checkLocal.isChecked() ){
                              Intent intent = new Intent(MainActivity.this, ListingArticles.class);
                              intent.putExtra("Title",value);
                              startActivity(intent);
                          }

                      }
                    });

                    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();

                      }
                    });

                    alert.show();


                  }
            });

        }


    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_INITILIZATION) {
            if (resultCode == RESULT_CANCELED) {

                int i2 = 1 ;
//              applicationWithSharedData();

            }
            else if (resultCode == Activity.RESULT_OK) {
                int i1 = 1 ;

//              applicationNoSharedData();

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




    /**
     * Creation of a contextual menu
     */
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
            super.onCreateContextMenu(menu, v, menuInfo); 
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.main, menu);
            menu.setHeaderTitle("Désirez-vous supprimer la liste?");  
//          menu.add(0, v.getId(), 0, "Action 1");  
//          menu.add(0, v.getId(), 0, "Action 2");  
        }  

    /**
     * Action activated when a menu's item is selected
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

        switch (item.getItemId()) {
            case R.id.yes_delete:


                /**
                 * Delete the list from the database
                 */
                db.deleteListArticle(listExisting.get(info.position).id);
                Log.d("onContextItemSelected => Numéro de l'ID:",String.valueOf(info.targetView.getId()) );

                /**
                 * Delete the title list from the screen
                 */
                Log.d("onContextItemSelected","Le switch fonctionne!");
                listExisting.remove(info.position);
                ArrayAdapterListNames listExistingAdapter = new ArrayAdapterListNames(this,listExisting) ;      
                listExistingAdapter.addListener(this);

                ListView listNames = (ListView)findViewById(R.id.ListViewMain);
                registerForContextMenu(listNames);

                listNames.setAdapter(listExistingAdapter);


                return true;

            case R.id.no_delete:
                return true;

            default:
                return super.onContextItemSelected(item);
        }
    }


    public void onRestart(){
        super.onRestart();

        /**
         * Get the name of the existing lists
         */
        listExisting = db.getTitleSQliteHelper(); 

       /**
        * Create an ArrayAdapter for the list's names
        */
       ArrayAdapterListNames listExistingAdapter = new ArrayAdapterListNames(this,listExisting) ;


       /**
        * Ecoute des évènements sur votre liste
        */
       listExistingAdapter.addListener(this);

       /**
        * Récupération du composant ListView
        */
       ListView listNames = (ListView)findViewById(R.id.ListViewMain);

       /**
        * Initialisation de la liste avec les données
        */
       listNames.setAdapter(listExistingAdapter);

    }



    @Override
    public void onClickNom(TitleList item, int position) {

        if (item.TYPE_CONNECTION.equalsIgnoreCase("local")){

            Intent intent = new Intent(MainActivity.this, ListingArticles.class);
            intent.putExtra("Title",item.nom);  
            startActivity(intent);

        }
        else if (item.TYPE_CONNECTION.equalsIgnoreCase("dropbox")){

            Intent intent = new Intent(MainActivity.this, ListingArticlesDropb.class);
            intent.putExtra("Title",item.nom);  
            startActivity(intent);

        }
    }
}

FirstConnection

public class FirstConnection extends Activity {


    final private String APP_KEY = **APP_KEY** ;
    final private String APP_SECRET = **APP_SECRET** ;

    static final int REQUEST_LINK_TO_DBX = 0;  // This value is up to you

    private DbxAccountManager mAccountManager ;
    private DbxDatastoreManager mDatastoreManager;
    private DbxAccount account ;


    private SQliteHelper db ;


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


        Button btn = (Button)findViewById(R.id.button_first_connection) ;
        btn.setOnClickListener(new OnClickListener() {


            @Override
            public void onClick(View v) {

                // Set up the account manager
                mAccountManager = DbxAccountManager.getInstance(getApplicationContext(), APP_KEY, APP_SECRET);   


                // Set up the datastore manager
                if (mAccountManager.hasLinkedAccount()) {
                    try {
                        // Use Dropbox datastores
                        mDatastoreManager = DbxDatastoreManager.forAccount(mAccountManager.getLinkedAccount());

                        gatherData();

                    } catch (DbxException.Unauthorized e) {
                        System.out.println("Account was unlinked remotely");
                    }


                }
                if (mDatastoreManager == null) {
                    // Account isn't linked yet, use local datastores
                    mDatastoreManager = DbxDatastoreManager.localManager(mAccountManager);              

                    AlertDialog.Builder alert = new AlertDialog.Builder(FirstConnection.this);
                    alert.setTitle("Connection à Dropbox");
                    alert.setMessage("L'initialisation de l'application sert à vous synchroniser avec l'espace de données partagées.\r\n"
                            + "Souhaitez-vous synchroniser votre application?");

                    alert.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        mAccountManager.startLink((Activity)FirstConnection.this, REQUEST_LINK_TO_DBX);

                      }
                    });

                    alert.setNegativeButton("Non", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) {

                          Intent returnIntent = new Intent();
                          setResult(RESULT_CANCELED, returnIntent);
                          finish();


                      }
                    });


                    alert.show();
                }

            }



        });


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_LINK_TO_DBX) {
            if (resultCode == Activity.RESULT_OK) {
                account = mAccountManager.getLinkedAccount();
                Toast.makeText(this, "onActivityResult", Toast.LENGTH_LONG).show();

                try {
                    // Migrate any local datastores to the linked account
                    mDatastoreManager.migrateToAccount(account);
                    // Now use Dropbox datastores
                    mDatastoreManager = DbxDatastoreManager.forAccount(account);

                    gatherData();

                } catch (DbxException e) {
                    e.printStackTrace();
                }
            } else {
                // Link failed or was cancelled by the user
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }


    }


    private void gatherData(){

        db = new SQliteHelper( this ) ;
        Set<DbxDatastoreInfo> datastorePresent = null ;

        try {
            datastorePresent = mDatastoreManager.listDatastores();
        } catch (DbxException e1) {
            e1.printStackTrace();
        }

        Iterator<DbxDatastoreInfo> datastoreLoop = datastorePresent.iterator() ;
        while (datastoreLoop.hasNext()){

            TitleList tit = new TitleList(datastoreLoop.next().id) ;
            tit.setConnectDropbox();
            db.addLists(tit);

        }

        mDatastoreManager.shutDown();

          Intent returnIntent = new Intent();
          boolean syncOK = true ;
          returnIntent.putExtra("result", syncOK) ;
          setResult(RESULT_CANCELED, returnIntent);
          finish();
//        startActivity(returnIntent);
    }



}

2 个答案:

答案 0 :(得分:0)

MainActivity

上添加此方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case REQUSET_CODE_YOUR:
        if (resultCode == RESULT_OK) {
            // write here code via **RESULT_OK**
        }
        break;

    default: // none of these
        break;
    }
}

然后在FirstConnection屏幕之后作为par写入代码,无论你需要什么方法。

setResult(RESULT_OK); // important

答案 1 :(得分:0)

你在第一篇文章中提到过 Intent returnIntent = new Intent(); setResult(RESULT_OK,returnIntent);

用于FirstConnection类,在上面的FirstConnection代码中我找到了你在哪里使用它,如果你已经使用过它就完全正确了。如果条件为真,它是合乎逻辑的继续,唯一的错误可能发生在&#34;如果&#34;如果您使用了&#34; =&#34;而不是&#34; ==&#34; ,而是指定条件检查。