How to add multiple edit text automatically on Android? - java

I am new to the Android and I am currently working on my android project.
I want to do this...
On the first Activity, the user will enter the number of strings he/she wants to input. For example, 3. (I am already done with this.)
And then, on the second activity, three edit text will appear for the entering the first, second and third string based on the user input in the first activity. If he/she enters 2, two edit text will appear on the second Java Activity. (How to do this one?)

In your Activity1, pass the user's entry to the next activity:
int userSelectedVal=somevalue;
Intent mIntent = new Intent(Activity1.this, Activity2.class);
mIntent.putExtra("userSelectedVal", userSelectedVal);
startActivity(mIntent);
In your Activity2, retrieve this value and programmatically add the Edittext's depending on this value:
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
int noOfEditTexts = extras.getInt("userSelectedVal");
LinearLayout mLinearlayout = new LinearLayout(this);
// specifying vertical orientation
mLinearlayout.setOrientation(LinearLayout.VERTICAL);
// creating LayoutParams
LayoutParams mLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// set LinearLayout as a root element of the screen
setContentView(mLinearlayout, mLayoutParam);
for (int i = 0; i < noOfEditTexts; i++) {
EditText mEditText = new EditText(context); // Pass it an Activity or Context
myEditText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mLinearlayout.addView(mEditText);
}
}

Related

Save data in ArrayList in activity

I am a new android programmer.
I have 4 activities: A B C D.
The order is A -> B -> C -> D -> A and A -> D using buttons.
I want to save data in ArrayList that is in activity D.
The problem is that when I move from D to A and come back to D, the data in the ArrayList didn't save.
Code for D activity here:
public class SchedulerActivity extends AppCompatActivity {
public String name = "";
public String number = "";
public String date = "";
public String hour = "";
public ArrayList<EventClass> scheduler = new ArrayList<>();
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scheduler);
Bundle extras = getIntent().getExtras();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SchedulerActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
if (extras != null) {
String sender = extras.getString("sender");
if(sender.compareTo("Hours") == 0) {
name = extras.getString("name");
number = extras.getString("number");
date = extras.getString("date");
hour = extras.getString("hour");
Date real_date = new Date();
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
try {
real_date = formatter1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
scheduler.add(new EventClass(real_date, name, number, "", hour));
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(t, params);
}
}
else{
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button btn = new Button(this);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(btn, params);
}
}
}
}
I want to change my ArrayList when C->D occurs and print it and when D->A occurs I just want to print it. I know that I can with SharedPreferences but for the first step, I want to do this with ArrayList.
What's the best way to do this?
Creating static objects is not a good approach. So you can use android activity stack in-place of using static Arraylist. Android activities are stored in the activity stack. Going back to a previous activity could mean two things.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application.
The scheduler is a non-static field in the SchedulerActivity which means that its existance is tied to the instance of the activity. When the activity instance is destroyed, and that might happen for example when the screen orientation is destroyed or you move to another activity, so are all its non-static fields. You can change that by adding a static keyword before your field:
public static ArrayList<EventClass> scheduler = new ArrayList<>();
Now, your field is tied to the class itself, not the instance, whitch means it wont be destroyed along with the instance. But it also means that it is shared between all instances and must be referenced with the class name outside of the class body:
EventClass event = SchedulerActivity.scheduler.get(0)
A good approach is saving your data in a local database, like Room. You need to save before go to new activity, and get it back on OnResume().

Add a text field on button click to second main activity

I need to add text field depends on the number the user added in the number text field to the second main activity. I already have a button that open onClick a new MainActivity but I need also to add text fields in the second MainActivity depends the number added.
I tried adding text fields on actionListeners but still not working.
public class MainActivity extends AppCompatActivity {
private Button submit_textfield;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit_textfield = (Button) findViewById(R.id.submit_textfield);
submit_textfield.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openActivity2();
}
});}
public void openActivity2() {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
The results must be: the user enters 5 and click submit the page redirect and creates 5 text fields. Thank You.
the user enters 5 and click submit the page redirect and creates 5
textfields
For this, you need to pass the text value into another class by using Intent.
Then you can receive the value by using getIntExtra in Main2Activity.
public void openActivity2() {
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("num",submit_textfield.getText());
startActivity(intent);
}
After get the num value, you can create the TextView dynamically based on the number.
Main2Activity
int num = getIntent().getIntExtra("num",0);
LinearLayout linearLayout = findViewById(R.id.myLinearLayout);
for (int i = 0; i < num; i++) {
final TextView rowTextView = new TextView(this);
rowTextView.setText("Value " + i);
myLinearLayout.addView(rowTextView);
}
Output
For achieving this you have to add a dynamic linear layout in which you will add textviews on run time nad firstly you have to pass that number into the intent by putExtra method.
public void openActivity2() {
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("number",submit_textfield.getText().toString());
startActivity(intent);
}
Now you just have to get this value in the next activity and start a for loop for this value and add runtime textviews in the linear layout.
int number =0;
if(getIntent().getExtras()!=null){
number = Integer.parseInt(getIntent().getStringExtra("number"));
}
LinearLayout ll= findViewById(R.id.ll_layout);
for (int i = 0; i < num; i++) {
final TextView tv_text= new TextView(this);
tv_text.setText("Value " + i);
ll.addView(tv_text);
}
if you want to set these textviews in vertical orientation then you just have to add the params to the linear layout as mentioned below:
ll.setOrientation(LinearLayout.VERTICAL);

Relative layout on click listener doesn't take the correct for-loop index

I have created a For-loop that create dinamycally some relative Layouts. I have an arrayList with some elements, called "photosPathList". The size of this arrayList is used to define the max number of loops.
This code that i'm writing is inside the onResume() method of an activity in Android. There is one thing that i'm not understanding.
If i log the i index inside the loop, it is increased correctly, and at each loop it take +1 value.
But if i click on the relative layout listener, the i index has always the last loop position. So if i create 4 relative layouts and i click on the first one, the log inside the relative layout show to me the the number 3. This isn't correctly because it should show the 0 number. Do you agree?
So what i'm doing wrong?
for (i=0; i<= photosPathList.size()-1; i++) {
//RELATIVE LAYOUT
RelativeLayout relativeLayout = new RelativeLayout(this); //create a new relative layout
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, //set main params about the width and height
RelativeLayout.LayoutParams.FILL_PARENT));
relativeLayout.setBackgroundColor(getResources().getColor(R.color.grayColor)); //set background color
LinearLayout.LayoutParams relativeParams = new LinearLayout.LayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
relativeParams.setMargins(20, 20, 20, 0);
relativeLayout.setLayoutParams(relativeParams); //set declared params about layout to the relativeLayout
relativeLayout.requestLayout();
Log.i("index",""+i);
Log.i("current path",""+photosPathList.get(i).toString());
relativeLayout.setOnClickListener(new View.OnClickListener(){ //create a listener about the layout. When a user press a point inside the relative layout a new activity should be created
#Override
public void onClick(View v){
Intent photoDetailsActivity = new Intent(
getApplicationContext(),
PhotoDetails.class //assign the class for create a new intent
);
Log.i("index2",""+i);
photoDetailsActivity.putExtra("photoDetailsImagePath", photosPathList.get(i).toString());
photoDetailsActivity.putStringArrayListExtra("photosPathList" , photosPathList);
photoDetailsActivity.putStringArrayListExtra("formatPhotoList", formatPhotoList);
photoDetailsActivity.putStringArrayListExtra("numberCopiesPhotoList", numberCopiesPhotoList);
photoDetailsActivity.putStringArrayListExtra("pricePhotoList", pricePhotoList);
startActivity(photoDetailsActivity); //let's start the new activity
}
});
}
Thanks
Your "i" variable isn't final.
Something you need to understand here:
When your onClick method invokes, it won't know what the value of "i" was during this loop. You need to find a way to pass "i" to the onClicklistener.
My suggestion, create a new class which implements OnClickListener and accepts an int variable.
Save this variable as a class member, and then use that in the OnClick method.
Hope this helps :)
You are using same variable i for every click event. You should use different counter variables.
// try this way
for (i=0; i<= photosPathList.size(); i++) {
//RELATIVE LAYOUT
RelativeLayout relativeLayout = new RelativeLayout(this); //create a new relative layout
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, //set main params about the width and height
RelativeLayout.LayoutParams.FILL_PARENT));
relativeLayout.setBackgroundColor(getResources().getColor(R.color.grayColor)); //set background color
LinearLayout.LayoutParams relativeParams = new LinearLayout.LayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
relativeParams.setMargins(20, 20, 20, 0);
relativeLayout.setLayoutParams(relativeParams); //set declared params about layout to the relativeLayout
relativeLayout.requestLayout();
relativeLayout.setTag(i);
relativeLayout.setOnClickListener(new View.OnClickListener(){ //create a listener about the layout. When a user press a point inside the relative layout a new activity should be created
#Override
public void onClick(View v){
Intent photoDetailsActivity = new Intent(
getApplicationContext(),
PhotoDetails.class //assign the class for create a new intent
);
int index = (Integer)v.getTag();
Log.i("index2",""+index);
photoDetailsActivity.putExtra("photoDetailsImagePath", photosPathList.get(index).toString());
photoDetailsActivity.putStringArrayListExtra("photosPathList" , photosPathList);
photoDetailsActivity.putStringArrayListExtra("formatPhotoList", formatPhotoList);
photoDetailsActivity.putStringArrayListExtra("numberCopiesPhotoList", numberCopiesPhotoList);
photoDetailsActivity.putStringArrayListExtra("pricePhotoList", pricePhotoList);
startActivity(photoDetailsActivity); //let's start the new activity
}
});
}

Transfer textview data between activities?

I'm currently making an app that has edittext and 2 buttons, everytime I write something in to edittext and then press button1, a new textview is added. This is the code:
public void novVnos (View v){
EditText eText = (EditText) findViewById(R.id.editText1);
LinearLayout mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mLayout.addView(createNewTextView(eText.getText().toString()));
}
private TextView createNewTextView (String text){
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView newTextView = new TextView(this);
newTextView.setLayoutParams(lparams);
newTextView.setText(text);
return newTextView;
}
Basically what I'm doing is adding new "players" and once I've added them all I want to press button2. Button2 opens a new activity and the new activity should read all the textviews that I've added in the previous activity.
What I would do is create a "Player" class and make a static ArrayList<String> players inside your Player.java class. Every time you call createNewTextView(textView) add whatever variable text is to the players ArrayList.
In your next Activity you just call Player.players.get(index) or whatever ArrayList function you need to do whatever work you want with it in the next class. You also could create this ArrayList in your current Activity and pass it as an extra in the Intent but I think creating a separate class for the players would be easiest.
Your ArrayList obviously doesn't need to hold Strings. It could hold whatever you want including a Player object.
ArrayList Docs
this is an example :
in the first activity :
Button search = (Button) findViewById(R.id.Button02);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, result.class);
Bundle b = new Bundle();
EditText searchtext = (EditText) findViewById(R.id.searchtext);
b.putString("searchtext", searchtext.getText().toString());
//Add the set of extended data to the intent and start it
intent.putExtras(b);
startActivityForResult(intent,RESULT_ACTIVITY);
}
});
and in the second activity at onCreat :
Bundle b = getIntent().getExtras();
String searchtext = b.getString("searchtext"); //here you get data then use it as you want
//here I use it to show data in another edittext
EditText etSearch = (EditText) findViewById(R.id.searchtext2);
etSearch.setText(searchtext);
Implementing a "Player" class will be a way to go. In that regard, you don't have to worry about transferring data between two activities. You can use Singleton method to make sure your class has been defined only once. You need to make sure it gets defined only once because let's say if you user closes application or kills app, then when he opens app again, it would create another class, so all of your data will be lost.

pass 2 values from one to another activity

i am very new to android.
i m trying to develop a login form for practise , and i m unable to pass and display 2 values
to another activity
Intent intent = new Intent(this, Success.class);
EditText edituser = (EditText) findViewById(R.id.userinput);
EditText editpass= (EditText) findViewById(R.id.passinput);
String username = edituser.getText().toString();
String password = editpass.getText().toString();
intent.putExtra(EXTRA_USER, username);
intent.putExtra(EXTRA_PASSWORD, password);
startActivity(intent);
and target activity is
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.EXTRA_USER);
String password = intent.getStringExtra(MainActivity.EXTRA_PASSWORD);
// Create the text view
TextView userView = new TextView(this);
TextView passView = new TextView(this);
userView.setTextSize(40);
userView.setText(username);
passView.setTextSize(40);
passView.setText(password);
// Set the text view as the activity layout
setContentView(userView);
setContentView(passView);
Your problem is that when you call setContentView() the second time, you remove the older view from the screen.
Try adding your Views to a ViewGroup like a LinearLayout and then adding that to the screen instead of individual Views.
Something like:
LinearLayout ll = new LinearLayout(this);
ll.addView(userView);
ll.addView(passView);
setContentView(ll);
You are getting the second value only, because you are setting your view twice..
the second one overrides the username..
You can use addContentView instead, or create an xml that contains 2 text views and use that..
use another layout and set intent values in the second layout....
setContentView(R.layout.anotherlayout);
TextView user = (TextView) findViewById(R.id.usertext);
TextView pass= (TextView) findViewById(R.id.passtext);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.EXTRA_USER);
String password = intent.getStringExtra(MainActivity.EXTRA_PASSWORD);
user.setText(username);
pass.setText(password);

Categories

Resources