My problem is I have a button and that button is doing create new textview but that textviews removing when i click back button. How I saved textviews in activity?
My java sourcecodes here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notlar);
Button btnNotEkle = (Button) findViewById(R.id.btnNotEkle);
final EditText etNot = new EditText(NotEkle.this);
final LinearLayout layoutNotlar = (LinearLayout) findViewById(R.id.layoutNotlar);
final TextView tv1 = (TextView) findViewById(R.id.tvnotOrtalama);
etNot.setInputType(InputType.TYPE_CLASS_NUMBER);
AlertDialog.Builder notEkle = new AlertDialog.Builder(NotEkle.this);
notEkle.setTitle("Notunuz");
notEkle.setView(etNot);
//Positive button
notEkle.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvNot = new TextView(NotEkle.this);//girelen not burdaki textview e yazdırılacak.
girilenNot = etNot.getText().toString();//Girilen notu alıyoruz
tvNot.setText(girilenNot);//girilen notu textviewa veriyoruz
notTopla += Integer.parseInt(girilenNot);//Notları topluyoruz
layoutNotlar.addView(tvNot);
count = layoutNotlar.getChildCount();
dersOrtalamaYazdir=String.valueOf(dersOrtalama());
tv1.setText("Ders Ortalamanız : "+dersOrtalamaYazdir);
dialog.cancel();
}
});
final AlertDialog notEkleCreate = notEkle.create();
btnNotEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
notEkleCreate.show();
}
});
}
}
Try giving your TextView objects ids.
You need to know that when you click back button - by default your activity is destroyed so all views are removed.
When you are adding new TextView you should add information about this TextView (like the text itself) to some list declared as field in your activity.
Then you can save this list when activity is recreated see: onSaveInstanceState/nRestoreInstanceState
You can also pass this list back or to new activity so that they can take actions based on this list.
Following my understanding your TextView had been created inside Dialog and after you press back button the dialog dismisses and all views you created inside will be removed and you can't access it from your Activity.
You may try to create TextView in onCreate, pass and in Dialog just call setText. I hope this is the answer you're looking for.
Cheers.
Related
I have in my program a scroll view with a linearlayout inside of it. I add dynamically TextView's to the linearlayout and I have no way to know how much TextView's I'll end up with. When a certain TextView is clicked I need to get it's text. Any idea what is the best way to do it?
Thanks in advance.
I've tried to add a listener to the text view but I am not sure how to get the text. I saw in some posts that you can do a listener to the LinearLayour/ScrollView though I am not sure what is the best option.
This happenes every time a message is added:
TextView messageText = new TextView(RecordedMessagesScreen.this);
messageText.setText(content);
messageText.setClickable(true);
messageText.setOnClickListener(RecordedMessagesScreen.this.textViewListener);
RecordedMessagesScreen.this.messagesLayout.addView(messageText);
this is the listener:
this.textViewListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("message", ***NEED TO GET THE TEXT***)
}
};
At the class level declare a String variable:
private String text = "";
and a View.OnClickListener variable:
private View.OnClickListener listener;
Initialize the listener in onCreate() of your activity like this:
listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v;
text = tv.getText().toString();
}
};
and every time you create a new TextView set the listener:
textView.setOnClickListener(listener);
This way the variable text each time you click a TextView will get the clicked TextView's text.
You can customize the code inside onClick() yo suit your needs.
I know that was already asked but it is outdated:
I have 2 buttons that represent 2 choices and if one is selected the background color gets changed to yellow. But if i want to change the choice i need to somehow reset the button:
I already try to set it back but some old design comes out. Can you provide me the id of the modern button style? And show me how to implement it?
int myChoice;
if (view == findViewById(R.id.choice1)){
myChoice = 1;
choice1.setBackgroundColor(getResources().getColor(R.color.highlightButton));
choice2.setBackgroundResource(android.R.drawable.btn_default);
}
else if (view == findViewById(R.id.choice2)){
myChoice = 2;
choice2.setBackgroundColor(getResources().getColor(R.color.highlightButton));
choice1.setBackgroundResource(android.R.drawable.btn_default);
}
}
Use Tags with getBackground(). This will assure you are always setting back to original.
Add following in beginning of function
if (v.getTag() == null)
v.setTag(v.getBackground());
Then instead of setBackgroundResource, use
v.setBackground(v.getTag());
Starting from here, you can store the default color of the button into a Drawable and grab the selection color (Yellow in your case) into anther Drawable, then toggle background colors of buttons with these Drawable variables
please check below demo
public class MainActivity extends AppCompatActivity {
private Drawable mDefaultButtonColor;
private Drawable mSelectedButtonColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn1 = findViewById(R.id.btn1);
final Button btn2 = findViewById(R.id.btn2);
mDefaultButtonColor = (btn1.getBackground());
mSelectedButtonColor = ContextCompat.getDrawable(this, R.color.buttonSelected);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleButton(btn1, true);
toggleButton(btn2, false);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleButton(btn1, false);
toggleButton(btn2, true);
}
});
}
private void toggleButton(Button button, boolean isSelected) {
button.setBackground(isSelected ? mSelectedButtonColor : mDefaultButtonColor);
}
}
Can't seem to find a post/video on the net that explains adding new EditText fields with a button. I need to use the edittexts later. Can someone please explain to me how to create this system? Or link a video/post that explains this. I've been searching for a long time but I still haven't found a good explanation. Thanks.
Button mButton = (Button) findViewById(R.id.my_button);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText t = new EditText(myContext);
t.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
root.addView(t);
}
});
root: is the root layout where you want to add the EditText.
use below code
Add this Java File..
LinearLayout linearLayout = findViewById(R.id.editTextContainer);
Button btnShow = findViewById(R.id.btnShow);
if (btnShow != null) {
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create EditText
final EditText editText = new EditText(this);
editText.setHint(R.string.enter_something);
editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setPadding(20, 20, 20, 20);
// Add EditText to LinearLayout
if (linearLayout != null) {
linearLayout.addView(editText);
}
}
});
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a function which creates a button, which has an onClick event to bring up a custom dialog which just shows some information from the functions parameters. The dialog has two buttons on it as well, one to close the dialog, and one to add information to a file.
When I try to set onClick events for those buttons, the app crashes, and the error I get is a NullPointerException which says that I am trying to invoke a virtual method on a null object reference.
If I comment out the part where I set the onClickEventListener code for both buttons, then the dialog appears as normal, with the buttons on it.
Note: context is a variable declared in the class. It is simply Context context = this
Code is below:
public void addButton(String text, int id, String areas, String details, String notes) {
Button button = new Button(this);
final String title = "Add "+text;
final String dName = text;
final String dAreas = areas;
final String dDetails = details;
final String dNotes = notes;
button.setText(text);
button.setTextColor(ContextCompat.getColor(context, R.color.buttonText));
button.setTextSize(32);
button.setId(id);
if (isEven(id+1)) {
button.setBackgroundResource(R.drawable.buttonshapeother);
} else {
button.setBackgroundResource(R.drawable.buttonshape);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Make custom dialog
final Dialog dialog = new Dialog(context);
Button add = (Button) dialog.findViewById(R.id.btnAddExer);
Button cancel = (Button) dialog.findViewById(R.id.btnCancel);
dialog.setContentView(R.layout.popup_exercise);
dialog.setTitle(title);
// Set the custom components now
TextView tName = (TextView) dialog.findViewById(R.id.lblNameData);
TextView tAreas = (TextView) dialog.findViewById(R.id.lblAreaData);
TextView tDetails = (TextView) dialog.findViewById(R.id.lblDetailsData);
TextView tNotes = (TextView) dialog.findViewById(R.id.lblNotesData);
tName.setText(dName);
tAreas.setText(dAreas);
tDetails.setText(dDetails);
tNotes.setText(dNotes);
// Add functions to buttons
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (addExercise(dName, dAreas, dDetails, dNotes)) { // Add exercise to user's workout
Toast.makeText(context, "Exercise was added to your workout", Toast.LENGTH_LONG).show();
dialog.dismiss(); // Close dialog
} else {
Toast.makeText(context, "There was an error adding your exercise", Toast.LENGTH_LONG).show();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss(); // Close dialog
}
});
dialog.show(); // Actually show the dialog
}
});
LinearLayout lay = (LinearLayout) findViewById(R.id.innerLay);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lay.addView(button, params);
}
public boolean isEven(int num) {
if ((num&1) == 0) {
return true;
} else {
return false;
}
}
Because you are trying to find button view before setting the layout to it. So try like this:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.popup_exercise);
dialog.setTitle(title);
Button add = (Button) dialog.findViewById(R.id.btnAddExer);
Button cancel = (Button) dialog.findViewById(R.id.btnCancel);
I have just started Android Studio and am also a little new to java, so please excuse the inefficient code.
Anyway, when I click on the button on the main activity on my app to take the user to the activity that I want to display the images, my app stops working and it throws an OutOfMemoryError.
Here is MainActivty.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button presidentQuizButton = (Button) findViewById(R.id.presidentQuizButton);
Button reviewPresidentsButton = (Button) findViewById(R.id.reviewPresidentsButton);
presidentQuizButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
//when button is clicked, do something
}
});
reviewPresidentsButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
//when button is clicked, do something
startActivity(new Intent(MainActivity.this, presidentReviewActivity.class));
}
});
}
Here is presidentReviewActivity.java:
ImageView imageView;
public int presidentNumber = 0;
private Drawable drawable;
private Drawable [] drawables = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_president_review);
Button menuButton = (Button) findViewById(R.id.menuButton);
Button nextButton = (Button) findViewById(R.id.nextButton);
Button backButton = (Button) findViewById(R.id.backButton);
drawables = new Drawable[]{
getResources().getDrawable(R.drawable.president1),
getResources().getDrawable(R.drawable.president2),
getResources().getDrawable(R.drawable.president3),
getResources().getDrawable(R.drawable.president4),
getResources().getDrawable(R.drawable.president5),
getResources().getDrawable(R.drawable.president6),
getResources().getDrawable(R.drawable.president7),
getResources().getDrawable(R.drawable.president8),
getResources().getDrawable(R.drawable.president9),
getResources().getDrawable(R.drawable.president10),
getResources().getDrawable(R.drawable.president11),
getResources().getDrawable(R.drawable.president12),
getResources().getDrawable(R.drawable.president13),
getResources().getDrawable(R.drawable.president14),
getResources().getDrawable(R.drawable.president15),
getResources().getDrawable(R.drawable.president16),
getResources().getDrawable(R.drawable.president17),
getResources().getDrawable(R.drawable.president18),
getResources().getDrawable(R.drawable.president19),
getResources().getDrawable(R.drawable.president20),
getResources().getDrawable(R.drawable.president21),
getResources().getDrawable(R.drawable.president22),
getResources().getDrawable(R.drawable.president23),
getResources().getDrawable(R.drawable.president24),
getResources().getDrawable(R.drawable.president25),
getResources().getDrawable(R.drawable.president26),
getResources().getDrawable(R.drawable.president27),
getResources().getDrawable(R.drawable.president28),
getResources().getDrawable(R.drawable.president29),
getResources().getDrawable(R.drawable.president30),
getResources().getDrawable(R.drawable.president31),
getResources().getDrawable(R.drawable.president32),
getResources().getDrawable(R.drawable.president33),
getResources().getDrawable(R.drawable.president34),
getResources().getDrawable(R.drawable.president35),
getResources().getDrawable(R.drawable.president36),
getResources().getDrawable(R.drawable.president37),
getResources().getDrawable(R.drawable.president38),
getResources().getDrawable(R.drawable.president39),
getResources().getDrawable(R.drawable.president40),
getResources().getDrawable(R.drawable.president41),
getResources().getDrawable(R.drawable.president42),
getResources().getDrawable(R.drawable.president43),
getResources().getDrawable(R.drawable.president44),
};
menuButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presidentNumber++;
drawable = drawables[presidentNumber];
imageView.setImageDrawable(drawable);
}
});
And here is most of the error log:
http://imgur.com/xzFfPrq
Instead of store all the drawable content in an array. You can actually just store the resource id in a array.
replace private Drawable [] drawables = null; with private int[] drawableids
replace drawables = new Drawable[]{...} to drawableids = new int[]{...}
replace
drawable = drawables[presidentNumber];
imageView.setImageDrawable(drawable);
to
drawable = getResource().getDrawable(drawableids[presidentNumber]);
imageView.setImageDrawable(drawable);
Try to change as above steps and try again.
The nullpointerexception may be caused by you did not init the drawableids array or you are still using the drawables array instead of drawableids.
you are trying to load large size images directly into memory which causes out of memory exceptions,this issue is discussed in details and a nice solution is given in developers site