starting an activity from onCreate or onStart - android

I have an activity that is themed as Theme.Dialog. I want to have this activity started off the main activity during the latter's onCreate or onStart (depending on some conditions that are checked first). My problem is that when the "dialog" activity is started this way it doesn't display. I get a blank activity.
Manifest snippet:
<activity android:name="CredentialsDialog"
android:label="Credentials"
android:theme="#android:style/Theme.Dialog">
</activity>
Dialog layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="25dp"
android:gravity="center_vertical|center_horizontal">
<EditText android:id="#+id/txt_username"
android:hint="Your username"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
<EditText android:id="#+id/txt_password"
android:hint="Your password"
android:password="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>
CredentialsDialog snippet:
public class CredentialsDialog extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.credentials_dialog);
getWindow().setTitle("This is just a test");
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);
Bundle extras = getIntent().getExtras();
String user = extras.getString("user");
String pass = extras.getString("pass");
// get handle on EditText fields
final EditText textUser = (EditText) findViewById(R.id.txt_username);
final EditText textPass = (EditText) findViewById(R.id.txt_password);
// pre-populate dialog username EditText with username if it exists
if (user != "") {
textUser.setText(user);
}
// pre-populate dialog password EditText with password if it exists
if (pass != "") {
textPass.setText(pass);
}
}
}
MainActivity snippet:
(in either onCreate or onStart)
if (!loginData()) {
loginDialog();
} else {
bLoggedIn = qrzLogin();
toggleUi();
}
(snip...)
public void loginDialog() {
Intent i = new Intent(this, CredentialsDialog.class);
i.putExtra("user", MainActivity.user);
i.putExtra("pass", MainActivity.pass);
startActivity(i);
}
In MainActivity, if I called loginDialog() a second time immediately after the first, the second would work while the first would be a blank activity. What am I doing wrong? Opinions welcome too. :)
Thanks,
Doug

Switching to overriding onCreateDialog and onPrepareDialog allowed me to add a TextWatcher to the EditText fields in my AlertDialog. This was the end goal anyway. Also, I have to say I like the dialog handling via onCreateDialog/onPrepareDialog. You can teach an old dog new tricks afterall!

Related

why my listview give me null error in custom drawerlayout? [duplicate]

I have code:
public class HelloWorld extends Activity {
private Button buttonOk;
private Button buttonCancel;
private OnClickListener buttonOkListener = new OnClickListener() {
public void onClick(View v){
EditText editText = (EditText)findViewById(R.id.input);
CharSequence textFromInput = (CharSequence) editText.getText();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context,textFromInput,duration);
toast.show();
}
};
private OnClickListener buttonCancelListener = new OnClickListener() {
public void onClick(View v){
EditText editText = (EditText)findViewById(R.id.input);
CharSequence textFromInput = (CharSequence) editText.getText();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context,textFromInput,duration);
toast.show();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// ToDo add your GUI initialization code here
setContentView(R.layout.main);
buttonOk = (Button)findViewById(R.id.buttonOk);
buttonCancel = (Button)findViewById(R.id.buttonCancel);
buttonOk.setOnClickListener(buttonOkListener);
buttonCancel.setOnClickListener(buttonCancelListener);
}
}
and the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Wpisz swoje imiÄ™:"/>
<EditText
android:id="#+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/editbox_background"
android:layout_below="#id/label"/>
<Button
android:id="#+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/input"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="OK" />
<Button
android:id="#+id/buttonCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/buttonOk"
android:layout_alignTop="#id/buttonOk"
android:text="Anuluj" />
</RelativeLayout>
Line with buttonCancel.setOnClickListener(buttonCancelListener); throws an Exception because buttonCancel is null. What i am doing wrong?
there is no problem with your codes, by right everything should work as per normal.
The most common mistake of encountering null via findViewById() method is when you forgot to call setContentView() or called it for the wrong layout.
I suggest cleaning your project and try again!!!!
I was having the same trouble, but after cleaning my project and running it again it works perfectly.
I'm not 100% sure but you are calling the findviewbyid's in the class initialisation. I think this code is called before the onCreate method so the view's cannot be found. Initializing the listeners in the oncreate method should work.
At times there are few points to be considered!
This can always happen even for experienced developers as well. I would suggest few points below,
Check that the findViewById is added in the appropriate life cycle of the activity or fragment which ever under consideration.
Also verify if the layout is inflated correctly and that the valid layout is set in the setContentView - which was incorrect in my case.
Also as mentioned above there are some cases where cleaning the project could help resolve this issue.

In android, How to resume previous activity , on button click from second activity

I have a form to be filled by user and next button "Next" in Activity1.
When user clicks "Next" button second activity Activity2 is started.
In Activity2 i have previous button "Previous".(* not device back button)
So when user clicks " Previous" button, Activity1 should be opened with the entered details in the form.
Activity1 should not be refreshed.
Seached alot on stackoverflow but no luck..!!!
Why don't you use startActivityForResults and then in the started activity finish()
In the started activity you have access to your intent in the onCreate method getIntent(); then you can use setResult(Activity.RESULT_OK, result); or setResult(Activity.RESULT_OK); (For canceled Activity.RESULT_CANCELED) to return result code and data and after you set the result you call finish and then return (code doesn't exit the methods if I remember correctly).
Then in the first activity you get the result and handle what to do with it in:
onActivityResult(int requestCode, int resultCode, Intent data)
Another option:
You could also use the logic for back button pressed calling the method from your code: super.onBackPressed();
Edit
As I promised here's an Example
Two activities - first one have two TextViews and a button next that launches the second activity -> in the second activity two EditTexts in which you enter some data which is then returned to the first activity when you press previous button. If you press back button instead of previous button, you enter in the canceled logic which is not doing anything in the example there is only a comment.
MainActivity
TextView textViewFirstName;
TextView textViewFamilyName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewFirstName = (TextView)findViewById(R.id.first_name_edit_text);
textViewFamilyName = (TextView)findViewById(R.id.family_name_edit_text);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//requestCode here is 12345 that we passed when we started SecondActivity
if(resultCode == Activity.RESULT_OK){
String resultFirstName = data.getStringExtra("firstName");
String resultFamilyName = data.getStringExtra("familyName");
textViewFirstName.setText(resultFirstName);
textViewFamilyName.setText(resultFamilyName);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Canceled logic
}
}
public void nextButtonClick(View view) {
Intent i = new Intent(view.getContext(), SecondActivity.class);
//If you want you could pass some additional data, like which action to take
//if you're reusing the second activity for more than one use case
i.putExtra("someAdditionalData", "Some string that you want to pass");
//12345 is int that you pass and will be returned as requestCode in onActivityResult
startActivityForResult(i, 12345);
}
SecondActivity
EditText editTextFirstName;
EditText editTextFamilyName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editTextFirstName = (EditText)findViewById(R.id.first_name_edit_text);
editTextFamilyName = (EditText)findViewById(R.id.family_name_edit_text);
Bundle bundle = getIntent().getExtras();
String someAdditionalData = bundle.getString("someAdditionalData");
}
public void previousButtonClick(View view) {
Intent returnIntent = new Intent();
returnIntent.putExtra("firstName", editTextFirstName.getText().toString());
returnIntent.putExtra("familyName", editTextFamilyName.getText().toString());
setResult(RESULT_OK, returnIntent);
finish();
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:text="Main"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:hint="First name"
android:id="#+id/first_name_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:hint="Family name"
android:id="#+id/family_name_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:onClick="nextButtonClick"
android:text="Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
second_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SecondActivity">
<TextView
android:text="Second"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:hint="First name"
android:id="#+id/first_name_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:hint="Family name"
android:id="#+id/family_name_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:onClick="previousButtonClick"
android:text="Previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
On previousButton onClickListener you can call finish();
This will close the current activity and reload the previous one from the stack. This is a quick hack.
Try overriding onBackPressed method inside second activity and call it on click event of previous button
Inside Activity 2
#Override
public void onBackPressed()
{
super.onBackPressed();
}
And call this on previous button click event
buttonPrevious.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
I would refrain from using finish(); cuz it kills the activity from where it's called. Try to use:
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
instead of finish();

Closing a "Pop-Up like" activity

I made this app, it gives notification to user. Notification is just a string. Sometimes a string can be long so I tried to show that string in a pop-up layout.
Like this, my xml:
<activity
android:name="com.dot.Popup"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Dialog">
</activity>
My layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#aeb25e" >
<TextView
android:id="#+id/notif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="asd"
android:padding="5dp"
android:textColor="#1D331C"
android:textSize="15sp"
android:textStyle="bold"
android:typeface="serif" />
</RelativeLayout>
And the code:
public class Popup extends Activity {
String notif;
Intent sender;
TextView popup_notif;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.popup);
sender=getIntent();
notif=sender.getExtras().getString("notif_ana");
popup_notif = (TextView) findViewById(R.id.notif);
popup_notif.setText(notif);
}
}
So here is my problem, I can display first item of string array (notifications), when second notification comes and I click, I display the previous screen. How can I refresh the string array, or kill the activity to call next string array, etc?
Thanks I hope I explanied good enough.
To close Activity you need to call finish(). And instead of activity i'd use rather Toast (with perhaps custom layout) or one of numerous libraries providing toast alterantives. Using activity here may be slightly overkill
try getting the intent and extras in the onResume() function and update the TextView in onResume() function of the activity.
public class Popup extends Activity {
String notif;
Intent sender;
TextView popup_notif;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.popup);
popup_notif = (TextView) findViewById(R.id.notif);
}
#Override
protected void onResume() {
super.onResume();
sender=getIntent();
notif=sender.getExtras().getString("notif_ana");
popup_notif.setText(notif);
}
}

Android SetText Null pointer Exception

I've just begin Android development and I'm sure you can help with this (I'm sorry about my bad English)
I have a main activity, and at a certain moment i want to call another activity, in wich a want to change a textview with some message. At this moment I get a Null pointer Exception if I dont put
setContentView(R.layout.register);
But when I put that line, I see for a milisecond correctly the Register activiy with my new text "Android2" and then jump again to a register activity with no text. I mean I draw it twice.
I hope I have explained enough.
The question is Where do I have to put setcontentview and with what layaout.
Thank you very much, Daniel
I show you some code:
My main activity has this method:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
{
Intent i = new Intent(this, register.class);
startActivity(i);
setContentView(R.layout.register);
TextView text = (TextView) findViewById(R.id.texto);
try {
text.setText("Android2");
}catch(Exception e) {
Log.i("Log", e.getMessage()+"Error!"); // LogCat message
}
}
//super.onActivityResult(requestCode, resultCode, data);
}
My second activity class called register:
public class register extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
}
}
The register Interface is register.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/about_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/register" />
<TextView
android:id="#+id/texto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/continue_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/save" />
<Button
android:id="#+id/new_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/repeat" />
</LinearLayout>
</LinearLayout>
What you basically do is the following:
you prepare an intent to start another activity
you start the activity you prepared the intent for
you set the current activity's content to R.layout.register
you get the textView (on the current activity)
you set the text of the textView to Android2
And, at this moment the new activity appears on the screen. Please note that your code is not correct, since you manipulate UI elements in the current activity and you expect changes on the newly started activity.
Move this code
TextView text = (TextView) findViewById(R.id.texto);
try {
text.setText("Android2");
}catch(Exception e) {
Log.i("Log", e.getMessage()+"Error!"); // LogCat message
}
to the register activity's onCreate() method.
BTW, usually, when you create a class, it's name should begin with a capital letter according to the standards.
You have two different activities. One of them is using the register.xml view, and the second one is trying to access the register view. The view only exists in your "register" activity. The other activity seems to have no view? That's probably why you're getting NULL.
You should merge those two classes together, since it looks like you're trying to access texto from the same view.
So, to summarise, findViewById should be called from within the activity that calls setContentView.
Remove this line and it should work
startActivity(i);
Not sure why you are calling that as an external activity.
Otherwise move below code to your register class
setContentView(R.layout.register);
TextView text = (TextView) findViewById(R.id.texto);
try {
text.setText("Android2");
}catch(Exception e) {
Log.i("Log", e.getMessage()+"Error!"); // LogCat message
}
}

Update EditText after Button is clicked

This EditText is inside an Activity that is part of a TabHost within the main Activity. It's just supposed to be 4 tabs with an EditText and two Buttons on each, one to increment and one to decrement the EditText field. However, if I ever try to setText() on one of the EditText boxes, the app crashes. So when I call setText() in onCreate() it crashes. Any help would be greatly appreciated!
<EditText
android:label="#+id/LifeForP1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoText="true"
android:cursorVisible="false"
android:background="#null"
android:textColor="#999999"
android:color="#null"
android:layout_x="90px"
android:layout_y="0px"
android:textSize="250px"
android:maxLength="3"
android:capitalize="sentences"
android:layout_weight="1"
android:freezesText="true"
android:text="20"
/>
public class ActivityTab1 extends Activity {
private EditText lifeView;
int p1Life = 20;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content1layout);
lifeView = (EditText) findViewById(R.id.LifeForP1);
lifeView.setText(getString(R.string.lifeStart)); //Error here
}
#Override
protected void onResume() {
super.onResume();
}
public void p1GainLifeListener(View view) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("test gain 1");
alertDialog.show();
//String show = String.format("", Integer.toString(++p1Life));
//lifeView.setText(show);
}
In your xml, change
android:label="#+id/LifeForP1" to
android:id="#+id/LifeForP1"
When you bind your EditBox in code you reference to
findViewById(R.id.LifeForP1);
This means the EditBox needs an ID.
If you change the android:label to an android:id your code will run fine

Categories

Resources