Hello and good luck to everyone.
I am using Intent Activity in my project. And are having bugs with it.
As follows: I have a list of the order of Activity:
A (Main) -> B (Login or SignUp) -> C (Menu) -> D (ListFoodOfMenu) -> E
(DetailsFood)
From A-B-C-D or in many different order does not occur
error.
But, since D-E has an error, the backgroud that I set for the xml
layout disappears throughout the application, replacing it with the
system color.
Who has a solution to help me and what to do to handle this error. Thank you.
This is a UI when there are no errors and then the UI is faulty:
UI is not faulty
UI is faulty
This is my code Intent:
A-B:
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent moveToSignUp = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(moveToSignUp);
finishActivity(1);
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent moveToSignIn = new Intent(getApplicationContext(), SignInActivity.class);
startActivity(moveToSignIn);
finishActivity(1);
}
});
B-C:
Intent moveToHome = new Intent(getApplicationContext(), Home.class);
Common.currentUser = user;
startActivity(moveToHome);
C-D:
//Get CategoryID and send to new Activity:
Intent moveToFoodList = new Intent(getApplicationContext(), FoodListActivity.class);
//Because CategoryID is Key, so we just get key of this item:
moveToFoodList.putExtra("CategoryID", adapter.getRef(position).getKey());
startActivity(moveToFoodList);
D-E:
//Start Activity FoodDetails
Intent moveToFoodDetails = new Intent(getApplicationContext(), FoodDetailsActivity.class);
moveToFoodDetails.putExtra("FoodId", searchAdapter.getRef(position).getKey());
// Send FoodId to FoodDetailsActivity
moveToFoodDetails.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(moveToFoodDetails);
E-D (At this point the error has occurred):
btnCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Database(getApplicationContext()).addToCart(new Order(
"", //Id tự tăng
Common.currentUser.getPhone(),
FoodId,
currentFood.getName(),
numberButton.getNumber(),
currentFood.getPrice(),
currentFood.getDiscount()
));
finish();
Toast.makeText(FoodDetailsActivity.this, "Added To Cart", Toast.LENGTH_SHORT).show();
}
});
I have struggled with this error for months and still can not figure
out how to fix it. We look forward to much help from Pro. Sincerely
thank.
It is because you are having library 'com.cepheuen.elegant-number-button:lib:1.0.2' & that library also has background resource named background.xml which is being override with your background.jpg, when you reach FoodDetailsActivity screen.
Solution : Rename your background.jpg to background_1.jpg.
Don't use getApplicationContext() at all places.
Use Activity's object like SignUpActivity.this or SignInActivity.this.
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 am building a login system in android and i need to accomplish the following:
save userdata on the local storage
when a user is created and i press on the button it needs to dynamically create a radiobutton with the user name and short name in it.
I have already managed to accomplish these things, but the only problem i have now is that i want to to have 2 classes, one where you register your account and the other where the radiobuttons with the user data is displayed. So my question: how can i program the calss in such a way that when i press on the register button that it creates the radiobuttons in a different class.
beneath is the code of the classes:
enter code here
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Save:
Intent I = new Intent();
I.putExtra(
I.setClass(this, ShowUsers.class);
startActivity(I);
break;
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Start other Activity
switch (v.getId()) {
case R.id.create:
Intent intent = new Intent();
intent.setClass(Main.this, Register.class);
startActivity(intent);
break;
}
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("editTextName,editTextPassword,editTextshortname");
// and get whatever type user account id is
}
}
}
when i click the save button it needs to create the radio button in the main class, now the question is how can i accomplish this?
If the second class is an Activity, then one solution is to send it an Intent with the data it needs to create the radio buttons. You do this by creating an Intent object, calling any of its setExtra() methods, then calling startActivity() with the Intent. Check out the Android API docs for more details.
Here is my onCreate() method. I am trying to pass a variable from one intent to this intent. That works fine. When I press back button and go back to previous intent to change the value, then the application crashes. And also when I change the orientation, the application crashes. I am getting "Nullpointer exception" at the pp.getData() method. It passes null argument into the function. How can I overcome this? do I need to add any other details?
public void onCreate(Bundle savedInstanceState) {
// get intent data
Intent i = getIntent();
setQuery(i.getExtras().getString("query"));
Log.v("query:", getQuery());
userquery = getQuery();
super.onCreate(savedInstanceState);
setContentView(R.layout.product_view_layout);
try {
pp = new Parser(userquery);
productData = pp.getData(asynctask, userquery);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mProductViewPagerAdapter = new ProductViewPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mProductViewPagerAdapter);
}
If the "query" extra doesn't exist in the Intent then it will return null. You should perform a null check to make sure you don't get nullPointerExceptions.
String query = i.getExtras().getString("query"));
if(query == null) {
setQuery("");
}
else {
setQuery(query);
}
If you want to receive results in the first activity you have to user this"
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
}
also when you start the first activity you have to start it startActivityForResult.
On back set the result as RESULT_OK or RESULT_CANCEL. look in tho activity on developers android.
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