using custom_dialog.dismiss() force closes app - java

i have just started with android but have done some c# which seems very similar to java
in short, the problem lies in the closeDialog method
I am not very familiar with view/viewgroup so please dont bombard me with incorrect usage of objects, etc.
in short, i am creating a simple app which i hope to improve on (it is basically the start of a huge project)
the _showhint dialog opens fine, and shows the "hint" as expected, but the closeDialog force closes the app, I have no idea why
package com.example.app;
import android.app.Activity;
import android.app.Dialog;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private WebView webView;
final Activity activity = this;
public Uri imageUri;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageImageURI = null;
private TextView lblAnswer, lblWelcome;
private EditText edtInput;
public TextView showText ;
public Button btnShowHint, btnCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtInput = (EditText) findViewById(R.id.edtInput) ;
lblWelcome = (TextView) findViewById(R.id.lblWelcome) ;
lblAnswer = (TextView) findViewById(R.id.lblAnswer) ;
btnShowHint = (Button) findViewById(R.id.btnHelp);
btnCalculate = (Button) findViewById(R.id.btnShow) ;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void calculate(View vw)
{
String [] arrEditStore = new String[edtInput.length()] ;
String arrOperators [] = {"+", "-", "*", "/", "(", ")"} ;
}
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
EDIT: ADDED "this" to final Dialog dialog = new Dialog(this)

I have discovered what has caused the problem
GIVEN CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
SOULTION
first, I moved the decleration of the btnClose to the top
public Button btnShowHint, btnCalculate, btnClose;
then in the design view, removed the link of the button Close onclick method refering to closeDialog.
Afterwards, removing the closeDialog method completely, and also moving some of that code to the _showHint method
it also makes logical sense, thanks to #Mike M. who commented on the post, helped me reason it out, since I say, THIS button must close the dialog but in the method of this button, I am assigning it to be used by itself, which doesn't make logical sense at all, here is the changed code and it works
CHANGED CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
btnClose = (Button) showHintDialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showHintDialog.dismiss();
}
});
}
We all make stupid and unnessasary mistakes at times, some worse than others, but if you find a solution to a problem you have had, maybe somewhere someone has the same issue, so post a solution to your problem, it might help that someone!!!
cheers

Related

Handling orientation change in android studio

I have been struggling with an issue in a note application i have been building with the help of a tutorial series. I just created a dialog allowing the user to change the category of a note but the new category is lost whenever the orientation is changed. as instructed by tutorial i override onSavedInstance to save information first but for some reason is not solved code below:
package com.workingprogess.notebook;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
public class NoteEditFragment extends Fragment {
private ImageButton noteCatButton;
private EditText title;
private EditText message;
private Button saveButton;
private Note.Category savedButtonCategory;
private AlertDialog categoryDialogObject;
private AlertDialog confirmDialogObject;
private static final String MODIFIED_CATEGORY="Modified Category";
public NoteEditFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(savedInstanceState!=null){
savedButtonCategory = (Note.Category) savedInstanceState.get(MODIFIED_CATEGORY);
}
//grab layout and assign to view so that we may access widgets
View fragmentLayout = inflater.inflate(R.layout.fragment_note_edit, container, false);
//grab widget references
title = (EditText) fragmentLayout.findViewById(R.id.editNoteTitle);
message = (EditText) fragmentLayout.findViewById(R.id.editMessage);
noteCatButton = (ImageButton) fragmentLayout.findViewById(R.id.editNoteButton);
saveButton = (Button) fragmentLayout.findViewById(R.id.saveNoteButton);
//populate with note data
Intent intent = getActivity().getIntent();
title.setText(intent.getExtras().getString(MainActivity.NOTE_TITLE_EXTRA));
message.setText(intent.getExtras().getString(MainActivity.NOTE_MESSAGE_EXTRA));
if(savedButtonCategory !=null){
Log.d("not null","the new image should be carried over");
noteCatButton.setImageResource(Note.categoryToDrawable(savedButtonCategory));
} else {
Note.Category noteCat = (Note.Category) intent.getSerializableExtra(MainActivity.NOTE_CATEGORY_EXTRA);
savedButtonCategory = noteCat;
noteCatButton.setImageResource(Note.categoryToDrawable(noteCat));
Log.e("null","pull from intent" );
}
//set onclick listeners
buildCategoryDialog();
noteCatButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
categoryDialogObject.show();
}
});
buildConfirmDialog();
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialogObject.show();
}
});
// Inflate the layout for this fragment
return fragmentLayout;
}
//save info before orientation change.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d("save","info is saved");
savedInstanceState.putSerializable(MODIFIED_CATEGORY, savedButtonCategory);
}
//build pop uo dialog to change note info
private void buildCategoryDialog(){
final String[] categories = new String[]{"Personal","Technical","Quote","Finance"};
final AlertDialog.Builder categoryBuilder = new AlertDialog.Builder(getActivity());
categoryBuilder.setTitle("Choose Note Type");
categoryBuilder.setSingleChoiceItems(categories, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int item) {
switch (item){
case 0:
savedButtonCategory= Note.Category.PERSONAL;
noteCatButton.setImageResource(R.drawable.p_icon);
break;
case 1:
savedButtonCategory=Note.Category.TECHNICAL;
noteCatButton.setImageResource(R.drawable.t_icon);
break;
case 2:
savedButtonCategory=Note.Category.QUOTE;
noteCatButton.setImageResource(R.drawable.q_icon);
break;
case 3:
savedButtonCategory=Note.Category.FINANCE;
noteCatButton.setImageResource(R.drawable.f_icon );
break;
}
categoryDialogObject.cancel();
}
});
categoryDialogObject=categoryBuilder.create();
}
private void buildConfirmDialog(){
final AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(getActivity());
confirmBuilder.setTitle("are you sure?");
confirmBuilder.setMessage("are you sure you want to save this note");
confirmBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("Save Note","Note title " + title.getText()+ "Note message "
+ message.getText()+" note category" + savedButtonCategory);
Intent intent = new Intent(getActivity(),MainActivity.class);
startActivity(intent);
}
});
confirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
savedButtonCategory=Note.Category.TECHNICAL;
}
});
confirmDialogObject = confirmBuilder.create();
}
}
Open your application Manifest file and for particular activity, add this code:
<activity
android:name=".MainActivity" //Activity where the problem is occuring
android:configChanges="screenLayout|orientation|screenSize">
Its better to add this "android:configChanges" to every activity to maintain data state even if orientation changes.
Have you checked if onSaveInstanceState is actually getting called? This callback will only be called if the Activity holding the fragment is getting destroyed. So, first check if your Activity is getting destroyed or not.

New layout doesn't pop up

I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.

Animation not showing after restarting Android Activity

I'll do my best to explain my issue without a video
I have a login activity where upon successful login, the EditText and Button fields fade out and a "logging in" TextView fades in (using Facebook Shimmer). This works great!! However, upon successfully login we are greeted by a blank activity (still fine). Now, I overwrote the back button so that when the back button is pressed, the user is forced to login again. My problem arises with the user hits the login button at this time. The Edit Text and Button elements fade out nicely but the "logging in" TextView never fades in.
Below are some picture examples. I will also post the source code for LoginActivity.class and if you want to download the project it is available at: git#github.com:fbgrecojr/Android-Application-Login-Activity-Template.git
If you download the project, username: testuser and password: testpass will work.
Images:
Initial Login (working)
Login Attempt after pressing the back button and then logging in again (which I overwrote to restart the intent)
LoginActivity.class
package com.projects.fbgrecojr.logintemplate.UI;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.projects.fbgrecojr.logintemplate.HTTPManager.HttpManager;
import com.projects.fbgrecojr.logintemplate.HTTPManager.RequestPackage;
import com.projects.fbgrecojr.logintemplate.Parser.JSONParser;
import com.projects.fbgrecojr.logintemplate.R;
import com.projects.fbgrecojr.logintemplate.Session.Session;
import com.projects.fbgrecojr.logintemplate.Structures.User;
import com.projects.fbgrecojr.logintemplate.Utility.UTILITY;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private EditText userName, password;
private Button login;
private RelativeLayout image;
private LinearLayout button, belowPic;
private Animation fadeInImage, fadeInButton, bottomUp, fadeOut;
private TextInputLayout inputLayoutName,inputLayoutPassword;
private ViewGroup hiddenPanel;
private ShimmerFrameLayout container, loggingIn;
private static final int SECOND = 1000;
private static final int HALF_SECOND = 500;
private static final int QUARTER_SECOND = 250;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//INITIALIZE ANIMATION ITEMS
fadeInImage = new AlphaAnimation(0, 1);
fadeInButton = new AlphaAnimation(0, 1);
fadeOut = new AlphaAnimation(1.0f,0.0f);
bottomUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bottom_up_animation);
fadeInImage.setInterpolator(new AccelerateInterpolator()); //and this
bottomUp.setInterpolator(new DecelerateInterpolator());
//GET UI ELEMENTS
userName = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
image = (RelativeLayout) findViewById(R.id.image);
button = (LinearLayout) findViewById(R.id.button);
container = (ShimmerFrameLayout) findViewById(R.id.shimmer);
belowPic = (LinearLayout) findViewById(R.id.below_picture);
loggingIn = (com.facebook.shimmer.ShimmerFrameLayout) findViewById(R.id.login_shimmer);
hiddenPanel = (ViewGroup)findViewById(R.id.input);
inputLayoutName = (TextInputLayout) findViewById(R.id.text_input_username);
inputLayoutPassword = (TextInputLayout) findViewById(R.id.text_input_password);
//SET UI PROPERTIES
loggingIn.setVisibility(View.INVISIBLE);
userName.setCursorVisible(false);
password.setCursorVisible(false);
password.setHint("Password");
userName.setHint("Username");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
userName.setCursorVisible(true);
password.setCursorVisible(true);
userName.requestFocus();
}
}, LoginActivity.SECOND * 3);
//ANIMATIONS
fadeInImage.setDuration(SECOND * 3);
fadeOut.setStartOffset(SECOND);
fadeOut.setDuration(SECOND);
image.setAnimation(fadeInImage);
fadeInButton.setStartOffset(SECOND + HALF_SECOND + QUARTER_SECOND);
fadeInButton.setDuration(SECOND * 2);
button.setAnimation(fadeInButton);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
container.setDuration(SECOND * 2 + QUARTER_SECOND);
container.setRepeatDelay(QUARTER_SECOND);
container.setIntensity((float) 0.15);
container.setBaseAlpha((float) 0.75);
container.setFadingEdgeLength(3);
container.setDropoff((float) 0.40);
container.startShimmerAnimation();
//ON CLICK LISTENERS
login.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
if(getUserName().getText().toString().equals("") || getUserName().getText().toString().equals(" ")) {
inputLayoutName.setError("enter username");
}else if(getPassword().getText().toString().equals("") || getPassword().getText().toString().equals(" ")){
inputLayoutPassword.setError("enter password");
}else{
//webservice
if (UTILITY.isOnline(getApplicationContext())) {
RequestPackage p = new RequestPackage();
p.setMethod("GET");
p.setUri(UTILITY.UBUNTU_SERVER_URL);
p.setParam("query", "user");
p.setParam("username", getUserName().getText().toString());
new WebserviceCallOne().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, p);
} else {
Toast.makeText(getApplicationContext(), "you are not connected to the internet", Toast.LENGTH_LONG).show();
}
}
break;
}
}
private void animateExit() {
//fade out annimation
belowPic.startAnimation(fadeOut);
belowPic.setVisibility(View.INVISIBLE);
fadeInImage.setStartOffset(SECOND * 2);
fadeInImage.setDuration(HALF_SECOND);
loggingIn.startAnimation(fadeInImage);
loggingIn.setVisibility(View.VISIBLE);
loggingIn.setDuration(SECOND);
loggingIn.startShimmerAnimation();
}
public EditText getPassword() {
return password;
}
public EditText getUserName() {
return userName;
}
private class WebserviceCallOne extends AsyncTask<RequestPackage, String, User> {
#Override
protected User doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return JSONParser.parseUserFeed(content);
}
#Override
protected void onPostExecute(User s) {
Session.setCurrentUser(s);
//if null, error stacktrace will print to the log. This is expected!!
if(Session.getCurrentUser() == null){ //username was incorrect
inputLayoutName.setError("username does not exist");
}else{ //check password
if(getPassword().getText().toString().equals(s.getPassword())){ //passwords match
animateExit();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
},LoginActivity.SECOND * 4);
}else{
inputLayoutPassword.setError("password incorrect");
}
}
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
#Override
public void onBackPressed() {
startActivity(new Intent(this, LoginActivity.class));
}
}
You have to call animateExit(); code in onResume methord
#Override
public void onResume() {
super.onResume();
animateExit();
}
override onResume() in your Activity.
try starting your animation in onresume.
override onPause() in your Activity
try stopping your animation in onPause.
Hope this Helps :)

Basic android debugging [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I seem to get at force close when i start the app on my Nexsus 4. Big possibility its just me that fools around but i can't find anything wrong with the code.
Android Studio gives no erros. The reset method that is commented out i supposed to reset the checkbox and the TextView.
Why can't i define items before onCreate ? And when i define them after i cannot use them in the "reset" method..
Could someone plese have a look ?
package com.example.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
final TextView txtTest = (TextView) findViewById(R.id.txtOut);
final CheckBox chkTest = (CheckBox) findViewById(R.id.chkTest);
final Button btnTest = (Button) findViewById(R.id.btnTest);
final EditText etTest = (EditText) findViewById(R.id.etTest);
String text = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chkTest.setChecked(true);
chkTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (chkTest.isChecked()) {
txtTest.setText("Checked :)");
} else txtTest.setText("Not Checked");
}
});
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//etTest.getText().toString(text);
text = etTest.toString();
// Reset(text);
}
});
/*void Reset(String text) {
chkTest.setChecked(false);
txtTest.setText(text);
}*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is the logcat error:
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{[...].MyActivity}: java.lang.NullPointerException
You can not initialize the item in this way! The layout is not inflated yet when is executed the code final TextView txtTest = (TextView) findViewById(R.id.txtOut); so you have a null pointer exception. Also, define the reset() method outside the onCreate().
See the codes below:
TextView txtTest = null;
CheckBox chkTest = null;
Button btnTest = null;
EditText etTest = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtTest = (TextView) findViewById(R.id.txtOut);
chkTest = (CheckBox) findViewById(R.id.chkTest);
btnTest = (Button) findViewById(R.id.btnTest);
etTest = (EditText) findViewById(R.id.etTest);
....
}
void reset(String text) {
chkTest.setChecked(false);
txtTest.setText(text);
}
You can't find a view when is not created yet, try this:
package com.example.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txtTest = null;
CheckBox chkTest = null;
Button btnTest = null;
EditText etTest = null;
String text = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtTest = (TextView) findViewById(R.id.txtOut);
chkTest = (CheckBox) findViewById(R.id.chkTest);
btnTest = (Button) findViewById(R.id.btnTest);
etTest = (EditText) findViewById(R.id.etTest);
chkTest.setChecked(true);
chkTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (chkTest.isChecked()) {
txtTest.setText("Checked :)");
} else txtTest.setText("Not Checked");
}
});
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//etTest.getText().toString(text);
text = etTest.toString();
// Reset(text);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void Reset(String text) {
chkTest.setChecked(false);
txtTest.setText(text);
}
}
You cant cause the items your are initializing is on the activity_main.xml and you set the content view after the initialization. Do the initialization in the onCreate().
Firstly you must define the Reset() function outside the onCreate(). Thats not the correct way.
Secondly, I observe you have just started out this so I would suggest to define the views in the xml and then act upon them. You can set the checkbox true initially in the xml and the later set to false in the code.

Splash Screen Causes MenuItems not to appear

I've built a splash screen that loads a (splash) activity and then starts another activity and it works fine. (I've attached it below - it's called SPLASH 1)
I created another splash screen to replace this one which is supposed to only run once - then after creating a SharedPreferences boolean it is supposed to load another activity. Everything seems fine with this but now when it loads the new activity, none of the menuitems appear. I have no idea what changed in SPLASH 2 - but something in there is causing the MenuItems not to appear after it loads the exact same activity SPLASH 1 does (NEWCORE.JAVA)
I'm really not sure what is going on here - any help is greatly appreciated!
(please let me know if any additional info is needed)
SPLASH 1. (WORKING)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import com.nfc.linkingmanager.R;
public class SplashScreen extends Activity {
private boolean mIsBackButtonPressed;
private static final int SPLASH_DURATION = 1000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
// make sure we close the splash screen so the user won't come back when it presses back key
finish();
if (!mIsBackButtonPressed) {
// start the home screen if the back button wasn't pressed already
Intent intent = new Intent(SplashScreen.this, NewCore.class);
SplashScreen.this.startActivity(intent);
}
}
}, SPLASH_DURATION); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
#Override
public void onBackPressed() {
// set the flag to true so the next activity won't start up
mIsBackButtonPressed = true;
super.onBackPressed();
}
}
SPLASH 2 (NOT WORKING - CAUSES MENUITEMS not to appear on the activity it loads)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import com.nfc.linkingmanager.R;
import android.content.SharedPreferences;
import java.lang.Object;
import android.preference.PreferenceManager;
public class SplashScreen extends Activity
{
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
Intent i = new Intent(SplashScreen.this, AppActivity.class);
SplashScreen.this.startActivity(i);
this.finish();
}
};
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("first_time", false))
{
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
Intent i = new Intent(SplashScreen.this, NewCore.class);
this.startActivity(i);
this.finish();
}
else
{
this.setContentView(R.layout.country_list);
handler.sendEmptyMessageDelayed(0, 2000);
}
}
}
NEWCORE.JAVA (Connected to by both Splash Screens - Only missing MenuItems when using SPLASH 2)
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class NewCore extends ListActivity {
public static final String ROW_ID = "row_id";
private ListView conListView;
private CursorAdapter conAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
// map each name to a TextView
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(NewCore.this, R.layout.country_list, null, from, to);
setListAdapter(conAdapter); // set adapter
}
#Override
protected void onResume()
{
super.onResume();
new GetContacts().execute((Object[]) null);
}
#Override
protected void onStop()
{
Cursor cursor = conAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
conAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(NewCore.this);
#Override
protected Cursor doInBackground(Object... params)
{
dbConnector.open();
return dbConnector.getAllContacts();
}
#Override
protected void onPostExecute(Cursor result)
{
conAdapter.changeCursor(result); // set the adapter's Cursor
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Intent addContact = new Intent(NewCore.this, NewCore.class);
startActivity(addContact);
return super.onOptionsItemSelected(item);
}
OnItemClickListener viewConListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent viewCon = new Intent(NewCore.this, NewCore.class);
viewCon.putExtra(ROW_ID, arg3);
startActivity(viewCon);
}
};
}
Create a new activity which extends the Android Activity class, and place your menu handling in there. Then, extend the new activity in your other activities - thus ensuring that the menu handling is consistent. For lists, you could create a second new activity which extends ListActivity, or grab the ListActivity code and just make that extend your previous activity with the menus.
In Splash 2 put
SetContentView(R.layout.country_list);
just below
super.onCreate(savedInstanceState);

Categories

Resources