How can I use interface from a for loop - java

I have two inner classes named CalculatorClass and UpdatePayment in MainActivity class.
In UpdatePayment class there is a for loop and I have a array of Buttons.
I want to add listener to each button in loop. Those buttons will initialize the CalculatorClass and get value of calculations.
Demo code is:
public static class MainActivity{
private interface UpdateEditText{
void onCallback(String s);
}
private class CalculatorClass extends Dialog{
UpdateEditText updateEditText;
public CalculatorInterface(#NonNull Context context, UpdateEditText updateEditText) {
super(context);
this.updateEditText = updateEditText;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
initialize();
}
initialize(){
.......................
s = "Some texts";
updateEditText.onCallback(s);
}
}
private class UpdatePayment extends Dialog{
private Button[] button = new Button[100];
private EditText[] editText = new EditText[100];
public CalculatorInterface(#NonNull Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
initialize();
}
initialize(){
.......................
for(int i = 0; i < MAXSize; i++){
button[i] = new Button(MainActivity.this);
editText[i] = new EditText(MainActivity.this);
//add buttons to view to layout
button[i].setOnclickListener(new View.OnClickListener(){
public void onClick(View v) {
CalculatorClass calculator = new
CalculatorClass(MainActivity.this,
new UpdateEditText() {
#Override
public void onCallback(String s) {
editText[i - 1].setText(s);
}
});
calculator.show();
}
);
}
}
}
}
Problem is the line editText[i].setText(s) work for the last editText what ever button I click, i.e, any button I click, it fills the editText[MaxSize -1]
What should I do?
How can I perform this action for all i?
Please help me, I tried a lot searching in internet, still I didn't get any solution.

Anonymous classes are very much treated like static variables in java.It's happenning because your i value after your activity is initialized is equal to 1 less than the length of the edit text array.
editText[indicies_of_button_clicke].setText(s)
How you will get the indicies of button clicked is by :
se the tag to button below this line "editText[i] = new EditText(MainActivity.this);", like this :
button[i].setTag(i)
to retreive the index of your actual button clicked inside button clicklisteners,
v.getTag()// this will give you an integer value which will be the indices of actual button clicked
//use this value to set your edit text value.

Solution:
After a whole night, I got answer, now I feel awwww, this was easy go!
I never came in this thought.
button[i].setId(i);
then call:
CalculatorClass calculator = new CalculatorClass(MainActivity.this, v.getId(),
new UpdateEditText() {
#Override
public void onUpdate(String s, int ID) {
Log.i("test", ID + "");
editText[ID].setText(s);
}
});
At the same time, #Rishabh Ritweek answered correctly.
Thanks to him.

Related

Deletion an element of an `ArrayList` and setting the info to a layout in `MainActivity` by the command of a custom `Dialog`

I am new working with this customized Dialog in android. I may not be able to clarify my problem properly by writing, So it humble request to understand what i want from given code.
In MainActivity i have Button to delete an element of an ArrayList and setting the info from the ArrayList to a Layout.
Code from CustomDialog:
public class PermissionToDelete extends Dialog implements View.OnClickListener {
public Button btnYes, btnNo;
public TextView txtPermToDelete;
public PermissionToDelete(Context context){
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.permission_delete);
initialize();
}
public void initialize(){
btnYes = findViewById(R.id.btnYes);
btnNo = findViewById(R.id.btnNo);
txtPermToDelete = findViewById(R.id.txtPermToDelete);
btnYes.setOnClickListener(this);
btnNo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnNo){
dismiss();
}
else if(v.getId() == R.id.btnYes){
MainActivity.deleteOrErase = "delete";
dismiss();
}
}
}
There is a static String variable in MainActivity named deleteOrErase.
From dialog it returns the string delete if Button Yes is clicked.
Code from MainActivity:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String text = tv.getText().toString();
PermissionToDelete permissionToDelete = new PermissionToDelete(MainActivity.this);
permissionToDelete.show();
if(deleteOrErase.equals("delete")){
String index = "";
for(int i = 1; text.charAt(i) != ')'; i++){
index += text.charAt(i);
}
tasksList.remove(Integer.parseInt(index) - 1);
File rootFile = new File(rootFolder);
if(rootFile.exists()){
String[]entries = rootFile.list();
for(String s: entries){
File currentFile = new File(rootFile.getPath(),s);
currentFile.delete();
}
rootFile.delete();
}
dailyTasksLayout.removeAllViews();
makePrimaryFileAndFolder();
saveDataToFile();
setTaskList();
deleteOrErase = "";
}
But the problem is before button from dialog is clicked, if(deleteOrErase.equals("delete")) is encountered when the value of deleteOrErase is still null.
Therefore data isn't deleted at the first click.
Its need second click to delete, because now the value of deleteOrErase is "delete".
How can i delete it from first click?
Or is there any other way???
thanks dear honorable members! <3
(I don't know either i could clarify my problem or not.
Even i can't understand from mty writings :P )

How to change the background color with a button?

How do I change the color of the background randomly with a button press in Android studio?
Here is my code:
public class partymodus extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partymodus);
final TextView aufgabe=(TextView)findViewById(R.id.txt_aufgabe);
final Button next = (Button)findViewById(R.id.btn_next);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String[] aufgaben = getResources().getStringArray(R.array.name);
Random rand = new Random();
int n = rand.nextInt(aufgaben.length - 0) + 0;
aufgabe.setText(aufgaben[n]);
}
});
}
You have to add an ActionListener to your button and override the method:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
And sorry for my english i'm beginner
As an un-profession to answer your question, you have to digging out what is jave graphic design pattern is before goes in official API,
Here is a link to search the JFrame or Java.awt.Graphic, [1]
it't where you start to build the components on the graphic,since you are building with a button component, I may suggest you looking the Inherit or father interface of JFrame, and another Containers
MyActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyActivity.setBackgroundColor(getResources().getColor(R.color.RED));
}
add view_name.setBackgroundColor(getResources().getColor(R.color.colorAccent));
line to set background color
this is my code:
mButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mHomeLl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
});

Using a button with the code inside of a different class

I am trying to make an app and I have the code for a button inside of a different class. When I start my app and click the first button it brings me to a different layout where the button is located. But when I click this button it doesn't do anything, just the little click down animation.
First Button Code:
public class TextAdd extends AppCompatActivity {
public static EditText Text;
public static Button Set;
public static String[] Checkagainst = new String[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Text_Checker);
Text = (EditText) findViewById(R.id.LPN);
Set = (Button) findViewById(R.id.Set);
Set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Text_Value = Text.getText().toString();
if (!Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.add);
for (int i = 0; i < Checkagainst.length; i++) {
if (Checkagainst[i] == null) {
Checkagainst[i] = Text_Value;
break;
}
}
} else if (Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.have);
}
}
});
}
}
Second Button Code:
public class Have extends AppCompatActivity {
private Button HaveBack;
private TextView Have;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.have);
HaveBack = (Button) findViewById(R.id.HaveBack);
Have= (TextView) findViewById(R.id.Have);
String Text_Value= TextAdd.License.getText().toString();
String Extra = Text_Value + " is already part of Your license plates";
Have.setText(Extra);
HaveBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.Text_Checker);
}
});
}
}
Does anyone know what is wrong? If so can you please help me.
You should use setContentView() only once in your onCreate() method. Calling it multiple times is not correct. If you want to show a small layout above your current layout, you should use a Dialog and if you want to show a completely different layout above everything, you have to use Intents to go to another activity and do the rest of the work in that one.
besides, use lowercase letters at start of your variables' and objects' names and start Class names with Uppercase letters. That's the standard for knowing what is a class and what is an object. e.g.
Button firstButton, secondButton;

How to take inputs in multiple textviews?

i am new to development. i am creating an android calculator app with advanced functionality.The thing is i am using text view for taking and displaying inputs/outputs. My question is, how can i take Multiple inputs in multiple Textviews.
For example i have 3 text views,when user will enter 1st input in first textview(by default) and when user press the specific button it moves automatically to next textview . In some cases i want to take 2 inputs and in some cases i want to take 3 ,
How can i achieve this
Note: I dont want to use edit text , coz all buttons of already available in my app.Using Edit text will make softkeyboard to appear, and then for hiding the softkeyboard, i need to use hiding code lines in every class
You can do something like following:
private TextView[] textViews;
private TextView tvCurrentEditing;
private Button btnNext;
private Button btnPrev;
private Button btnSetText;
private int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
textViews = new TextView[3];
//Initialize all your textviews like textViews[0] = findViewById(<textview-id1>);
//textViews[1] = findViewById(<textview-id2>);
//textViews[2] = findViewById(<textview-id3>);
tvCurrentEditing = textViews[index];// I am assuming this is your first
//initialzie btnSettext
btnSettext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCurrentEditing.setText("<what ever you want");
}
});
//initialize next buton
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index < textViews.length) {
index++;
}
tvCurrentEditing = textViews[index];
}
});
//Initialize previous button
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index > 0) {
index--;
}
tvCurrentEditing = textViews[index];
}
});
}
The names of the views could be different. The point is always use tvCurrentEditing whenever you want to change data of TextView. And update tvCurrentEditing whenever needed.

how to set different actions to dynamiclly created button on android (specifically - auto scroll to a textview using a dynamic button)

i created a layout containing multiple text views.
i saved the text view's ids in an ArrayList which is a class variable called _resultId.
now i want to create buttons which suppose to scroll to the correct text view
(the first button to the first text view etc)
the question is: how to pass the correct id to each of the buttons on press method?
i tried using a global variable _counter but when i run the program all the buttons scroll to the last text view
the code of the method:
private void addNavigationView(ViewGroup navigationLayout, ArrayList<Perek> mishnayot)
{
for (int i=0;i<mishnayot.size();i++)
{
_counter=i;
String currentOt=mishnayot.get(i).getOt();
Button button = new Button(getBaseContext());
button.setText(currentOt);
if (_resultId==null)
throw new IllegalAccessError("missing result id link cannot be created");
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) //make it scroll to correct textview
{
new Handler().post(new Runnable()
{
#Override
public void run()
{
View currentView=findViewById(_resultId.get(_counter));
ScrollView scrollView=(ScrollView) findViewById(R.id.resultScroll);
scrollView.scrollTo(0, currentView.getTop());
}
});
}
});
navigationLayout.addView(button);//add the button to panel
}
navigationLayout.setVisibility(View.VISIBLE);
}
after learning more on Runnable interface i Found an answer so for those who will struggle with something similar:
you need to create a new class altogether that implements both runnable and the OnClickListener.
this class will contain extra data and a constructor to match your needs.
when you set the onClick method of the button you create a new object of that class.
for instance in my case the new method looked like:
public class ButtonHandler implements OnClickListener,Runnable
{
private String _data;//data to be passed for the button
private ArrayList<Integer> _resultId;//the id's of the text views
private Activity _activity;
public ButtonHandler(String data,ArrayList<Integer> resultId,Activity activity)
{
_data=data;
_resultId=resultId;
_activity=activity;
}
#Override
public void run()
{
View currentView=_activity.findViewById(_resultId.get(Integer.valueOf(_data)));
ScrollView scrollView=(ScrollView) _activity.findViewById(R.id.resultScroll);
scrollView.scrollTo(0, currentView.getTop());
}
#Override
public void onClick(View v)
{
new Handler().post(this);
}
}
now to call it from the main activity i use:
private void addNavigationView(ViewGroup navigationLayout, ArrayList<Perek> mishnayot)
{
for (int i=0;i<mishnayot.size();i++)
{
_counter=i;
String currentOt=mishnayot.get(i).getOt();
Button button = new Button(getBaseContext());
button.setText(currentOt);
if (_resultId==null)
throw new IllegalAccessError("missing result id link cannot be created");
button.setOnClickListener(new ButtonHandler(i+"",_resultId,this));
navigationLayout.addView(button);//add the button to panel
}
navigationLayout.setVisibility(View.VISIBLE);
}

Categories