OnActivityResult не соблюдает условие RESULT_OK через IFJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 OnActivityResult не соблюдает условие RESULT_OK через IF

Сообщение Anonymous »

Я получаю класс FirstConnection из класса MainActivity благодаря базовому коду:

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) { // , нет никакого способа, мой код не попадает в условие IF[/b], несмотря на то, что это условие истинно!

Я действительно не понимаю, но я уверен, что resultCode == RESULT_OK, потому что я проверял в режиме DEBUG.

Есть ли у кого-нибудь подобная проблема?

Спасибо!

ОБНОВЛЕНИЕ

Я публикую содержимое обоих классов.

MainActivity
public class MainActivity extends Activity implements NamesAdapterListener{

private int REQUEST_CODE_INITILIZATION = 2 ;

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

}
}
}


Первое подключение

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 datastorePresent = null ;

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

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

}


Подробнее здесь: https://stackoverflow.com/questions/266 ... -condition
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»