I'm having trouble closing my toast message that I'm creating in the activity BarcodeActivity after I pass over the intent to another class, UPCHandler. Since I can't pass toasts through intents, I haven't been able to find a way to manipulate the toast message from the UPCHandler intent.
BarcodeActivity:
public void didScanBarcode(String barcode, String symbology)
{
// Remove non-relevant characters that might be displayed as rectangles
// on some devices. Be aware that you normally do not need to do this.
// Only special GS1 code formats contain such characters.
String cleanedBarcode = "";
for (int i = 0 ; i < barcode.length(); i++)
{
if (barcode.charAt(i) > 30)
{
cleanedBarcode += barcode.charAt(i);
}
}
try
{
//stops scanner
mBarcodePicker.stopScanning();
Log.e("CleanedUPC", cleanedBarcode);
/* Toast Setup */
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Fetching your results...");
Toast toast = BarcodeActivity.toast;
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
#Override
public String dataRetreived()
{/*
Intent i = new Intent(getApplicationContext(), UPCHandler.class);
Bundle bundle = new Bundle();
bundle.put("value", inputTransacVal.getText());
i.putExtras(bundle);
startActivity(i);*/
ItemsDto idt = hand.getFirstUpc();
if (idt == null)
{
Log.e("BarcodeActivity:didScanBarcode", "UPC is NULL");
toast.cancel();
}
else
{
Intent intn_display = new Intent("com.ahold.scan.DISPLAYSCREEN");
Intent intn_warning = new Intent("com.ahold.scan.WARNINGSCREEN");
ImageLoader imgLoad = new ImageLoader(idt.getImageUrl(), context, idt)
*/
}
return null;
}
});
}
catch(Exception e)
{
//throws an error message to logcat if it catches one
Log.e("IntentStartError", e.toString());
}
}
There are two things you can try to do:
Close the toast before switching activities, pass an indication in your intent that the toast needs to be reshown, and show it in the new activity.
Pass the toast. Put it in a static variable somewhere, and in your new activity cancel it if it's not null. Keep in mind that it might be null, because Android can kill your process and start it again between activities.
Hi there I am new to Android Programming
I am trying to create an application in which, the user clicks button on the first page
the text color in the buttons change color and the change is reflected in another activity page.
To do this I have
1) one fragment class(BookLockerFragment) which reference to an xml file containing the buttons
2) The parent activity file (TabActivity.java)
3) The activity file to reflect the change ( complainResponse.java)
Here is the code:
LodgeComplaintFragment.java
ArrayList<String>userSelectedOptions = new ArrayList<String>();
if(btnSis.getCurrentTextColor()==Color.BLUE){
userSelectedOptions.add("SIS");
}
Button but = (Button) root.findViewById(R.id.searchButton);
.....
but.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
buttonListener.onMakeBookingButtonPressed(userSelectedOptions);
}
});
TabMainActivity.java
public void onMakeBookingButtonPressed(ArrayList<String> list) {
// TODO Auto-generated method stub
Intent intent = new Intent(TabMainActivity.this,
complainResponse.class);
intent.putStringArrayListExtra("userSelectOptions",list);
startActivity(intent);
}
complainResponse.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
setContentView(R.layout.complainresponse);
userInput = intent.getStringArrayListExtra("userSelectOptions");
// Creates the window used for the UI
if (userInput != null) {
if (userInput.get(0) != null) {
textview1 = (TextView) findViewById(R.id.textView1);
textview1.setText(userInput.get(0));
}
}
}
Error occurs at this line:
if (userInput != null) {
//of complainResponse.java
Logcat:
java.lang.IndexOutOfBoundsException
Please help
There's nothing in the ArrayList that you pass to your activity.
I suspect this bit of code isn't being executed -
if(btnSis.getCurrentTextColor()==Color.BLUE){
userSelectedOptions.add("SIS"); <------------ never gets here
}
To verify this, run the application in debug mode, and place a breakpoint at the if statement
userInput.get(0) != null
this is the cause of error in my opinion, list can be initialized but empty.
instead you should use,
if (!userInput.isEmpty())
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.
my code is
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Log.d("response", "starting city connection");
HttpPost httppost = new HttpPost(
"http://10.0.2.2/wic3/wic2/mobile/verifyUser");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
sessionResponse = SignUpActivity.httpclient.execute(httppost,
responseHandler);
Log.d("session response", "" + sessionResponse);
if (sessionResponse.equals("true")) {
Intent intent = new Intent(SignUpActivity.this,
FeedListViewActivity.class);
startActivity(intent);
}
} catch (Exception e) {
Log.e("error", "Error in http connection" + e.toString());
}
.............
my question is can i skip the 1st activity(or screen) and directly load some other screen depending on any condition???my intention was to load the home page (skip the login page) if a session already exists....in my case the sessionResponse is true but i still get the login page
Instead of the following code
Intent intent = new Intent(SignUpActivity.this,FeedListViewActivity.class);
startActivity(intent);
Simply put setContentView(). setContentView() is the method that displays the screen in android to the User Interface. If you dont call this method then nothing will be displayed. You will see only a blank screen. Modify your above code as follows
if (sessionResponse.equals("true"))
setContentView(R.layout.screen1);
else
setContentView(R.layout.screen2);
Yes you can Don't set View using setContentView and check the condition and nevigate to the desired activity and finish your first activity. But if your Condition is false you have to handle that too otherwise nothing will be displayed.
I have a problem with a progressbar spinner:
ProgressBarSpinner spinner = new ProgressBarSpinner();
spinner.execute(Spin);
Login LoginUser = new Login();
if(LoginUser.LoginUser(UserNameValue.getText().toString(), PasswordValue.getText().toString())) {
MessageBox("Login information", "You've been successfully logged in, press OK to continue.");
Document XMLInfo = null;
Passphrase = PasswordValue.getText().toString();
try {
XMLInfo = XMLfromString(LoginUser.ProfileXML);
XML_ProfileParser(XMLInfo);
TickerString = FillProfileSlider(XMLInfo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Spin.setVisibility(ProgressBar.GONE);
setContentView(R.layout.profile);
TextView ProfileTicker = (TextView)findViewById(R.id.ProfileTicker);
TextView UserInformation = (TextView)findViewById(R.id.NameInfo);
TextView MoneyLabel = (TextView)findViewById(R.id.MoneyInfo);
UserInformation.setText(ProfileInfo.get("FirstName") + " " + ProfileInfo.get("LastName"));
MoneyLabel.setText(ProfileInfo.get("Money") + " Kr");
if(Integer.parseInt(ProfileInfo.get("Messages")) >= 1) {
ImageView MessageImage = (ImageView)findViewById(R.id.MailImage);
MessageImage.setOnClickListener(ImageListener);
MessageImage.setVisibility(ImageView.VISIBLE);
}
ProfileTicker.setText(Html.fromHtml(TickerString));
}
else {
Spin.setVisibility(ProgressBar.GONE);
MessageBox("Login information", "The submitted login information seems to be invalid.");
}
This gets executed when users click login. Spin is a global progressbar variable. Below is the Async class that is used to handle the spinner.
private class ProgressBarSpinner extends AsyncTask<ProgressBar, Integer, ProgressBar>
{
protected ProgressBar doInBackground(ProgressBar...Spinner) {
return Spinner[0];
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(ProgressBar Spinner) {
Spinner.setVisibility(ProgressBar.VISIBLE);
Spinner.showContextMenu();
}
}
To the problem: If I try to write
Spin.setVisibility(ProgressBar.GONE);
after the logins authorization the spinner does not get displayed at all. But if I remove the ProgressBar.Gone part the spinner is displayed.
But if that part is present is seems that the application "hangs" before it continues (either logging the user in or displaying an error message telling that the username or password is wrong).
What can the problem be?
I know for sure that the login is not done so fast that the spinner does not get time to be displayed before it is set to GONE.
You need to set your spinner to visible before creating your AsyncTask and hide it in onPostExecute, something like:
mySpinner.setVisibility(View.VISIBLE);
myAsyncTask.Execute(); // etc, etc
myAsyncTask:
protected void onPostExecute(ProgressBar Spinner) {
Spinner.setVisibility(View.GONE);
}