I've extended Deitel's "Flag Quiz" (Android for Programmers...App Driven...) to (among other things) allow user to display a small flag for comparison with the given flag. The user taps SHOW FLAG and then gets a list of countries, taps one, and it's returned and shown (as ... shown below).
The only problem I'm having is that after tapping the desired country, the Settings preferences screen shows (see below). I guess this is because SHOW FLAG is part of it, but I want the next thing the user sees after selecting country from list is to be the screen above. There is no need to see the screen below, so there's definitely no reason to have to press the back button--how to avoid?
FYI, here is a trace and relevant code snippets (I can think of no reason to show any xml):
MainActivity.java:
07-06 17:25:48.305 32269-32269/com.dslomer64.flagquiz W/opOptionsItemSelected? item is <Show flag> -----------------------
07-06 17:25:48.350 32269-32269/com.dslomer64.flagquiz W/Here's where? to get flag
07-06 17:25:48.688 32269-32269/com.dslomer64.flagquiz W/onOptionsItemSelected? Show flag showFlag is true
`FlagActivity.java`:
07-06 17:25:48.768 32269-32269/com.dslomer64.flagquiz W/FlagAct? onCreate
07-06 17:25:51.707 32269-32269/com.dslomer64.flagquiz W/returnToA from FlagAct? Anguilla!!!
`SettingsActivity`:
07-06 17:25:51.751 32269-32269/com.dslomer64.flagquiz W/onCreate? SettingsActivity
(not me)
07-06 17:25:51.783 32269-32269/com.dslomer64.flagquiz W/Resources? Converting to string: TypedValue{t=0x10/d=0x3 a=-1}
07-06 17:25:51.786 32269-32269/com.dslomer64.flagquiz W/Resources? Converting to string: TypedValue{t=0x10/d=0x7d0 a=-1}
`MainActivity.java`:
07-06 17:25:55.554 32269-32269/com.dslomer64.flagquiz W/entering? onActivityResult in MainActivity
07-06 17:25:55.569 32269-32269/com.dslomer64.flagquiz W/onActResult? in Main Act show one flag Anguilla
`QuizFragment.java`:
07-06 17:25:55.591 32269-32269/com.dslomer64.flagquiz W/in showAFlag? country: Anguilla
MainActivity.java, which is where Preferences are kept and options are selected
and result of calling FlagActivity (onActivityResult) is processed:
#Override public boolean onOptionsItemSelected(MenuItem item){
Log.w("opOptionsItemSelected", "item is <" + item.getTitle() + "> -----------------------");
Intent preferencesIntent = new Intent(this, SettingsActivity.class);
startActivity(preferencesIntent);
Button getData = (Button)findViewById(R.id.button2);
Intent intent = new Intent(
MainActivity.this,
FlagActivity.class
);
startActivityForResult(intent, 0);
Log.w("onOptionsItemSelected", "" + item.toString() + " showFlag is " + showFlag);
return super.onOptionsItemSelected(item); // to SettingsActivity.onCreate
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data ) {
Log.w("entering","onActivityResult in MainActivity");
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == Activity.RESULT_OK){
String enteredData = data.getStringExtra("Data");
Toast.makeText(getApplicationContext(), "Returned " + enteredData, Toast.LENGTH_SHORT).show();;
country = enteredData;
Log.w("onActResult "," in Main Act show one flag " + country);
quizFragment.showAFlag(country);
// ABOVE IS WHERE FLAG IS SHOWN ^^^
}
}
FlagActivity.java, which is where the listview is processed:
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flag);
Log.w("FlagAct", " onCreate");
flagAdapter = new ArrayAdapter<String>(this, R.layout.list_item, flagArray);
setListAdapter(flagAdapter);
getListView().setOnItemClickListener(itemClickListener);
}
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String country = ((TextView) view).getText().toString();
Intent result = new Intent();
result.putExtra("Data", country);
setResult(Activity.RESULT_OK, result);
Toast.makeText(getApplicationContext(), country + "!!!", Toast.LENGTH_SHORT).show();
Log.w("returnToA from FlagAct", country + "!!!");
finish();
}
}; // end itemClickListener
.
SettingsActivity.java:
public class SettingsActivity extends Activity // hosts SettingsFragment in portrait mode
{
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w("onCreate", "SettingsActivity");
setContentView(R.layout.activity_settings);
}
Set an Preference.OnPreferenceChangeListener using the setOnPreferenceChangeListener() method.
Then, when the country is changed, call the finish() method to exit your activity
I fixed my problem by modifying onOptionsItemSelected, but I did not do so in terms of how I asked the Question.
showFlag = (item.toString().equals("Show flag"));
if(showFlag) // If the Settings buttonpress requested a flag,
{ // start the activity for it
Intent intent = new Intent(
MainActivity.this,
FlagActivity.class
);
startActivityForResult(intent, 0);
} // but don't start a preferences activity.
else // But if the Settings buttonpress was NOT 'Show flag',
{ // start a preferences activity.
Intent preferencesIntent = new Intent(this, SettingsActivity.class);
startActivity(preferencesIntent);
};
I still don't know (and don't need to) how to "dismiss" a Settings screen.
But it would be good to know how to do so, if it's possible.
Related
I am making a quiz app, my MainActivity(main menu) launches QuestionActivity using startActivityForResult, in QuestionActivity (Question text and answer buttons). After the user has answered the question, I want to send a boolean back a to MainActivity to update the score which then can be pushed into the next intent, in the Question Activity, I display the score in the Actionbar.
The problem is when I answer one question, setResult and Finish Runs but onActivityResult does not, after I answer all questions then OnActivityResult runs 10 times.
How can I get onActivityResult to run after I answer each question, not at the end?
Do I need to use intent flags?
Extra Info
In MainActivity, when the user starts the quiz:
//Called when user clicks quiz
//Creates the list of questions and then asks them.
public void makeQuiz(View view) {
//Pick the questions for the quiz
question[] quiz = new question[10]; //A quiz with 10 questions
for (int i = 0; i < quiz.length; i++) {
quiz[i] = myDBHelper.pickQuestion();
askQuestion(view, quiz[i],i,qscore);
Log.d("Asked question", Integer.toString(i));
}
}
Ask Question is used to start the QuestionActivity:
//Creates a question and then passes it though to the question view.
public boolean askQuestion(View view, question q, int questionNum, int qscore){
question q1 = q;
Log.d("Correct Ans",q.CorrectAns);
Intent question = new Intent(this, QuestionActivity.class);
Bundle extras = new Bundle();
extras.putString("QUESTION", q.QuestionText);
extras.putString("MODULE", q.Module);
extras.putString("CORRECT_ANS",q.CorrectAns);
extras.putString("ANS1", q.WAns[0]);
extras.putString("ANS2", q.WAns[1]);
extras.putString("ANS3", q.WAns[2]);
extras.putInt("qscore",qscore);
question.putExtras(extras); //Passing the question to the QuestionActivity
startActivityForResult(question,1);
return true;
}
In QuestionActivity, When the user answers the question correctly:
//Pass back that we got the correct answer
resultIntent = new Intent();
resultIntent.putExtra("ANSWER",true);
setResult(1, resultIntent);
Log.d("True", "Set result has been called");
finish();
Back in MainActivity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
//Check which event we are responding to
Log.d("onActivityResult", "called"); //This never runs
if(resultCode == 1){
//Do something with the intent
//if q is correct, update the score in shared prefrences,
Boolean result = data.getBooleanExtra("ANSWER",false);
Log.d("ANSWER IS ", Boolean.toString(result));
qscore += result ? 1:0; //This updated score is then pushed into the next intent so it can be displayed in the next question activity.
}
}
Alright so this is your problem you start the activity for result with:
startActivityForResult(question,questionNum);
so questionNum is your requestCode
but when you finish the QuestionActivity you finish it like this:
setResult(Activity.RESULT_OK, resultIntent);
so here your request code is the value of Activity.RESULT_OK
you need them to be equal.
Edit:
for your request in the comment look at this:
private static final int REQUEST_CODE = 123131;
private Stack<Intent> intentStack = new Stack<>();
//Called when user clicks quiz
//Creates the list of questions and then asks them.
public void makeQuiz(View view) {
//Pick the questions for the quiz
question[] quiz = new question[10]; //A quiz with 10 questions
for (int i = 0; i < quiz.length; i++) {
quiz[i] = myDBHelper.pickQuestion();
askQuestion(view, quiz[i], i, qscore);
Log.d("Asked question", Integer.toString(i));
}
startActivityForResult(intentStack.pop(), REQUEST_CODE);
}
//Creates a question and then passes it though to the question view.
public boolean askQuestion(View view, question q, int questionNum, int qscore) {
question q1 = q;
Log.d("Correct Ans", q.CorrectAns);
Intent question = new Intent(this, QuestionActivity.class);
Bundle extras = new Bundle();
extras.putString("QUESTION", q.QuestionText);
extras.putString("MODULE", q.Module);
extras.putString("CORRECT_ANS", q.CorrectAns);
extras.putString("ANS1", q.WAns[0]);
extras.putString("ANS2", q.WAns[1]);
extras.putString("ANS3", q.WAns[2]);
extras.putInt("qscore", qscore);
question.putExtras(extras); //Passing the question to the QuestionActivity
intentStack.push(question);
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check which event we are responding to
if (resultCode == RESULT_OK) {
//Do something with the intent
//if q is correct, update the score in shared prefrences,
Boolean result = data.getBooleanExtra("ANSWER", false);
Log.d("ANSWER IS ", Boolean.toString(result));
qscore += result ? 1 : 0;
if(!intentStack.isEmpty()){
startActivityForResult(intentStack.pop(), REQUEST_CODE);
}
}
}
GOAL
What I am trying to do:
Click on my search button and my database is queried with the results passed in. If nothing is found, we are taken to an activity which says so, but if results are found they are loaded into a list.
What I have done
When I click on the search button I call startActivityForResult then this intent calls an activity (whose layout consist of a list_view). The search button also pass along my parameters and query my database.
if there are no results then an activity saying "No Records" is displayed"
and if there are records the else condition is true and the records are loaded in the list
PROBLEM
The problem I am experiencing is, when the list is loaded, if I want to go back to my search form, I must press the back button a total of three times. I am not entirely sure but I believe this strange behavior is stemming from me not returning a result to the started activity when the else clause is invoked.
I have placed what I think is the important part of my code below, would appreciate any assistance
Main Activity
private void startStudentQuery() {
Intent intent = new Intent(getBaseContext(), retrieveStudentData.class);
intent.putExtra("firstname", firstname);
intent.putExtra("lastname", lastname);
//startActivity(intent);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
Intent X = new Intent();
X.setClass(getBaseContext(),NotFound.class);
startActivity(X);
}
}
retrieveStudent Activity
//this activity is a listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_student)
}
//Left out some code, just showing the main parts
public class StudentAsynTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//return result to show Activity if no records are found
if (jsonArray.length() == 0) {
Intent intent=new Intent();
setResult(2,intent);
finish();
} else {//Show list if records are found
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jRealObject = jsonArray.getJSONObject(i);
Student student = new Student ();
student.setFirstname(jRealObject.getString("f_name"));
student.setLastname(jRealObject.getString("l_name"));
student.setImage(jRealObject.getString("image"));
studentList.add(student);
}
}
In startStudentQuery, you should call startActivityForResult only, but now you have called retrieveStudentData twice.
Update: Thank you all for attempting to help me solve this bug. I am still unsure as to the cause, I was able to roll back to a previous commit and continue development from there. This previous commit did show the same bug, however after I commented out button.performClick() it went away. Strangely, this does not work on the most recent commit.
I still do not understand this bug and would appreciate any more assistance in helping determine the root cause. My greatest fear would be to inadvertently re-introduce it.
I have the most crazy error I have ever seen.
The OnCreate method is being called over and over again, freezing my application and giving me a slight flicker. The only solution is then to exit to the home screen and force quit the application from the settings menu.
Here is what is happening in detail:
Application starts (Main Activity)
Main Activity calls the Second Activity
Second Activity calls onCreate, sets up as normal
Second Activity randomly decides to exit onCreate <-- I think this what's happening
Second Activity's onCreate gets called again. It doesn't ever return to the Main Activity.
I have run a debugger, it appears that the second activity successfully completes the onComplete/onResume sequence, then decides to exit and restart.
Has anybody ever heard of this behavior before?
I haven't noticed any exceptions being thrown. Also, in the course of debugging, I did go ahead and check those locations that you see as silent fail. (this is the older code before I littered it with print statements)
UPDATE: When attempting to stop the process, I must turn on airplane mode. This means it has something to do with this code block (Second Activity)
else if (Network.haveNetworkConnection(Login.getContext()) && Login.checkClientId())
{...}
With no internet, it will hit the else statement and does not display this behavior.
CODE:
onResume() of the Main Activity, where I call the Second Activity:
#Override
public void onResume()
{
super.onResume();
//Check If logged in, else go to login page
Login.setContext(getApplicationContext());
//Reset Notification Number
GCMIntentService.cancelNotifications();
/** GO TO LOGIN **/
if(!Login.isLoggedIn())
{
//If user is not logged in, open login page
System.out.println("RESUMING MAIN AND STARTING LOGIN INTENT");
Intent intent = new Intent(ActivityMain.this, ActivityLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else
{
Login.setupStuffOnce();
Event.pullEvents(); //Get New Events
//Update ListView
updateMainFeed();
}
}
This is the Second Activity:
public class ActivityLogin extends Activity
{
private String postData;
//private Context c;
//final Timer timer = new Timer();
//Facebook Stuff
private Facebook facebook = new Facebook(Config.FBAPPID);
private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
//Layout Stuff
EditText username, password;
Button loginButton, signupButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Open Database
Login.setContext(getApplicationContext());
Database.open(getApplicationContext());
}
/*
* #Override public void onPause() { s }
*/
#Override
public void onResume()
{
super.onResume();
// shouldn't put here but oh well
init();
//If coming from ActivitySignup
if(Transfer.username != null)
{
username.setText(Transfer.username);
password.setText(Transfer.password);
Transfer.password = null;
Transfer.username = null;
loginButton.performClick();
}
}
public void init()
{
Login.getUserLoggedIn();
if (Login.isLoggedIn())
{
//Do Any Additional Setup
Login.setupStuffOnce();
// If user is logged in, open main
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else if (Network.haveNetworkConnection(Login.getContext()) && Login.checkClientId())
{
// Else, Make User Login
// Inflate Login and Present Website
String clientid = Login.getClientId();
System.out.println("clientid:" + clientid);
//System.exit(0);
postData = "mobile=1&client_id="+Login.getClientId();
// Inflate the view
setContentView(R.layout.activitylogin3);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
//Inflate the Button
loginButton = (Button) findViewById(R.id.loginButton);
signupButton = (Button) findViewById(R.id.signupButton);
signupButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(ActivityLogin.this, ActivitySignup.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int res = Login.sendLogin(username.getText().toString(), password.getText().toString());
if(res == 202)
{
//Login Successful
//Check if facebooked.
if(Login.isFacebooked())
{
//Just go to main
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//Are these flags necessary?
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else
{
//Go to facebook login page
//Intent intent = new Intent(ActivityLogin.this, ActivityFBLogin.class);
//startActivity(intent);
//Login via Facebook
doFacebook();
}
} else
{
System.out.println("Login Failed: "+res);
if(res == 405)
{
Toast.makeText(getApplicationContext(), "Incorrect Username/Password", Toast.LENGTH_SHORT).show();
password.setText("");
}
else
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show(); //Not entirely true in all cases i think
}
/*Login.getUserLoggedIn();
if(Login.isLoggedIn())
{
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Please Login Above", Toast.LENGTH_SHORT).show();
}*/
}
});
} else
{
// Not Logged In and No Internet Access
setContentView(R.layout.activitylogintext);
EditText text = (EditText) findViewById(R.id.text);
text.setText("No Internet Connection Detected\n requires internet to login");
Button button = (Button) findViewById(R.id.refreshButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Login.getUserLoggedIn();
if(Network.haveNetworkConnection(Login.getContext()))
{
Intent intent = new Intent(ActivityLogin.this, ActivityLogin.class);
//intent.setFlags();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "No Internet Access Detected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void doFacebook()
{
facebook.authorize(this, Config.facebookPermissions, new DialogListener() {
#Override
public void onComplete(Bundle values) {
/*SharedPreferences.Editor editor = state.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
*/
//Input into database
Login.saveAccessToken(facebook.getAccessToken());
Login.setFB(facebook.getAccessToken());
//Login.sendAccessToken(facebook.getAccessToken());
//Intent into Main Activity
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Error: "+error.getErrorType(), Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e) {
Toast.makeText(getApplicationContext(), "Error: "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {}
});
}
public boolean checkForUserID(Context c)
{
try{
String res = Network.getUrl("www.website.com/mobile.php?got_user=1&client_id="+Login.getClientId());
JSONObject json = JSON.constructObject(res);
if(JSON.handleCode(json))
{
if(json.getString("type").equals("userid"))
{
Login.setLogin(json.getString("data"));
return true;
}
}
} catch(Exception e)
{
//Silent Fail
}
return false;
}
}
I believe that the problem will be resolved if you finish your MainActivity after you call SecondActivity. The problem probably is that the onResume event is immediatelly fired when you resume your MainActivity. That is because the MainActivity was probably destroyed and recreated while it was in background. Another solution would be to save your Activity's state with onSaveInstanceState. See here for more information.
Check this code in your activity:
Button button = (Button) findViewById(R.id.refreshButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(Network.haveNetworkConnection(Login.getContext()))
{
Intent intent = new Intent(ActivityLogin.this, ActivityLogin.class);
//intent.setFlags();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "No Internet Access Detected", Toast.LENGTH_SHORT).show();
}
}
});
Here you are calling ActivityLogin itself.
That's why the onCreate() is being called again and again.
I had a similar problem once. The problem occurred because I made configuration changes without declaring them in the android:configChanges attribute of the <activity> tag (and hence it recreates itself the whole time).
For example, if you change the locale manually you need to add locale to android:configChanges!
It seems to me there is a good chance for endless cycling here if Login is not properly shared between the activities, causing Login.isLoggedIn() to return true in ActivityLogin but false in ActivityMain.
A few critical factors are where your Login object is located, is it static, how is it referenced between Activities? It is entirely possible that ActivityMain is being destroyed while ActivityLogin is active; storing the Login data in SharedPreferences or a database, or otherwise persisting it is important. How does isLoggedIn() resolve (determine its return value?)
Suggestion 1: Consider making use of the Singleton pattern (if you haven't already.)
Suggestion 2: While discouraged, you could store Login at the Application level.
Suggestion 3: You can try using Intent.FLAG_ACTIVITY_SINGLE_TOP to reduce the likelyhood of a new ActivityMain being created - which might not have access to Login, again depending on how you have it stored.
ActivityMain
onResume() {
if(!Login.isLoggedIn()) {
/* Not logged in, launch ActivityLogin! */
Intent intent = new Intent(ActivityMain.this, ActivityLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
ActivityLogin
onResume() { /* ... */ init(); }
init() {
Login.getUserLoggedIn();
if (Login.isLoggedIn()) {
/* Internet - launch ActivityMain! */
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // <--- suggested addition
startActivity(intent);
else if (Network.haveNetworkConnection(Login.getContext()) && Login.checkClientId()) {
/* No internet, the user was unable to login. */
}
I think your main problem is with you onResume function as it gets called each time it comes back into view (eg: you start second activity, finish it, main activity onResume is called again. If you finish your second activity (or it quietly crashes for some reason) you will go back to your mainActivity and call onResume (which will start the cycle all over again).
Now i dont know if you are finishing activity 2 somehow but I would check that.
EDIT:
ALso I would put some logcats here
if (Login.isLoggedIn())
{
//Do Any Additional Setup
Login.setupStuffOnce();
// If user is logged in, open main
Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i("Some Tag", "Starting Main Activity From Activity 2");
startActivity(intent);
}
The above adding of the log.i will allow you to know if this is where the error happens, and you can go from there.
I had similar problem where the activity would be recreated all the time. Re-installing the app wouldn't help, but restarting the phone did the job.
I have ListView contains two TextViews(say t1,t2) and that ListView is created by xml, which is inflate in the Activity.
My requirment is, that if the user clicks on a ListView item, which contains t1 a new Activity should and when clicking on an item, which contains t2 start another Activity.
But problem is, that it is not working when I am clicking at any of ListView items, it moves to same Activity in both case.
My code (as - inside getView() method):
mylayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
if (listType == 1) {
Log.v("active", "On Click " + (position));
Intent intent = new Intent(VoucherActiveScreen.this,MyVoucherDetailPage.class);
intent.putExtra("selectedIndex", position);
intent.putExtra("listType", listType);
startActivity(intent);
}
else if (listType == 3) {
//String str = offerPrice.getText().toString();
//System.out.println(str);
if (voucherOffer.getIs_redeem().toString().equals("1"))
{
System.out.println(voucherOffer.getIs_redeem().toString()+"if Rate"); //its working when click listview which contains Rate
Intent intratedeal=new Intent(getBaseContext(),RateDeal.class);
intratedeal.setClass(getBaseContext(), RateDeal.class);
startActivityForResult(intratedeal, 1);
}
else
{
System.out.println(voucherOffer.getIs_redeem().toString()+"else View"); //its working when click listview which contains View
Intent intratevendor=new Intent(getBaseContext(),RateVendor.class);
//intratevendor.setClass(getBaseContext(), RateVendor.class);
startActivityForResult(intratevendor, 1);
}
/*Intent intent = new Intent(
VoucherActiveScreen.this,
MyVoucherDetailPage.class);
intent.putExtra("listType", listType);
intent.putExtra("selectedIndex", position);*/
Log.v("inactiveeeeeeeeeeeeeeeeee", "On Click " + (position));
//startActivity(intent);
}
} catch (Exception e) {
// TODO: handle exception
}
}
});
please any one help...
control is going right if-else block but intent is not redirecting same Activity
You can setFlags in your intent like this:
Intent intent = new Intent(VoucherActiveScreen.this,MyVoucherDetailPage.class);
intent.putExtra("selectedIndex", position);
intent.putExtra("listType", listType);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
The snippet above will start a new activity task. See this link:
http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NEW_TASK
I need help in geting results back from intent launched from
preference screen
// Intent preference
DevicePref =
getPreferenceManager().createPreferenceScreen(this);
// Show a Screen with list of Devices Discovered
Intent i = new Intent(this,getDevice.class);
DevicePref.setIntent(i);
DevicePref.setTitle("Select Device");
DevicePref.setSummary(mSelectedDevice);
deviceOptionsCat.addPreference(DevicePref);
I want user to select device... In preference screeen I show "Select
Device" .. when user clicks that, another screen is launched by intent
where all devices are listed. User selects the device.
Now how do I know user selected which device? And I want to update
that in the summary.
Pls. let me know
Thanks
I got the answer, Hope it will help someone like me...
Do not mention intent while creating preference like I did in above code.. Mention intent on OnPreferenceClickListener and then do StartActivityForResult()
// Intent preference
DevicePref = getPreferenceManager().createPreferenceScreen(this);
// Show a Screen with list of Devices Discovered
DevicePref.setOnPreferenceClickListener(onPreferenceClick);
DevicePref.setTitle("Select Device");
DevicePref.setSummary(mSelectedDevice);
deviceOptionsCat.addPreference(DevicePref);
Then create OnPreferenceClickListner and here do StartActivityFromResult()
OnPreferenceClickListener onPreferenceClick = new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (preference ==DevicePref )
{
Intent i = new Intent(DevuiceOptions.this,getDevice.class);
DevicePref.setIntent(i);
startActivityForResult(i,CHOOSE_DEVICE);
}
return true;
}
};
Finally to get the result handle onActivityResult and update Summary field.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode) {
case Constants.CHOOSE_DEVICE:
{
if (data!=null )
{
Bundle b = data.getExtras();
mSelectedDevice = (String) b.get("Name");
UpdatePreferences();
}
}
}
}
Thanks