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.
Related
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().
Hello I want to have an Add function that allows me to input items to my GridView
For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.
My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently
Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList<WordFolder> word){
super(context, 0, word);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//Getting the current word
WordFolder currentWord = getItem(position);
//making the 2 text view to match our word_folder.xml
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(currentWord.getTitle());
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
desc.setText(currentWord.getTitleDesc());
return listItemView;
}
}
Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
//goes back to the MainActivity
Intent intent = new Intent(NewFolder.this, MainActivity.class);
startActivity(intent);
}
});
}
In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.
Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you
To pass data between Activities to need to do a few things:
First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.
This method takes an intent and an int.
Use the same intent you used in startActivity.
The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:
private static final int ADD_RESULT_CODE = 123;
Now, your button's click listener should looks something like this:
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this, NewFolder.class);
startActivityForResult(intent, ADD_RESULT_CODE);
}
});
Now for returning the result.
First, you shouldn't go back to your main activity by starting another intent.
Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.
And to return some data, too, you can use this code:
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
where title and desc are the variables you want to pass.
in your case it should look something like this:
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
//goes back to the MainActivity
finish();
}
});
}
You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:
setResult(Activity.RESULT_CANCELLED);
finish();
In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind
Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).
To do this you need to override a method called onActivityResult inside ActivityMain:
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check the result code to know where the result came from
//and check that the result code is OK
if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )
{
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
//... now, do whatever you want with these variables in ActivityMain.
}
}
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);
}
}
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);
I'm creating an EditText in onOptionsItemSelected() and trying to get it's information in onClick(). Here's the offending code:
onOptionItemSelected(MenuItem item){
...
EditText mealCalories = new EditText(context);
mealCalories.setId(MealCalId) //in this example it's just an integer 1.
...
}
onclick(View v){
EditText mealCaloriesInBox = (EditText)findViewById(mealCalId);
}
When I haven't selected an item from the menu (and thus haven't called onOptionItemSelected();) it doesn't crash when I click the button. However, when I actually have created the EditText and I click the button it crashes as it's trying to create the instance, giving me the aforementioned error. Any ideas on why it could be doing that?
EDIT
Here's more of my code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
switch(item.getItemId()) {
case R.id.addMeal:
trackMealItems++;
mealCalId++;
mealFatId++;
mealCarbId++;
mealProteinId++;
//the base layout
LinearLayout root = (LinearLayout)findViewById(R.id.linearLayout1);
//make the layout that holds the meal item and add it to the base layout
LinearLayout mealItem = new LinearLayout(context);
mealItem.setId(trackMealItems);
mealItem.setOrientation(LinearLayout.VERTICAL);
mealItem.setLayoutParams(mealItemParams);
root.addView(mealItem);
//make the TextView that holds the name of the meal and add it to the mealItem layout
EditText mealName = new EditText(context);
mealName.setLayoutParams(mealNameParams);
mealItem.addView(mealName);
//make the TextViews that hold the information about the meal and stick them in a
//horizontal LinearLayout
LinearLayout mealStats = new LinearLayout(context);
mealStats.setOrientation(LinearLayout.HORIZONTAL);
mealStats.setLayoutParams(mealStatParams);
mealItem.addView(mealStats);
EditText mealCalories = new EditText(context);
mealCalories.setId(mealCalId);
mealCalories.setLayoutParams(mealStatParams);
mealStats.addView(mealCalories);
EditText mealFat = new EditText(context);
mealFat.setId(mealFatId);
mealFat.setLayoutParams(mealStatParams);
mealStats.addView(mealFat);
EditText mealCarbs = new EditText(context);
mealCarbs.setId(mealCarbId);
mealCarbs.setLayoutParams(mealStatParams);
mealStats.addView(mealCarbs);
EditText mealProtein = new EditText(context);
mealProtein.setId(mealProteinId);
mealProtein.setLayoutParams(mealStatParams);
mealStats.addView(mealProtein);
return true;
case R.id.removeMeal:
LinearLayout removeMe = (LinearLayout)findViewById(trackMealItems);
removeMe.setVisibility(View.GONE);
trackMealItems--;
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v){
EditText mealCaloriesInTextBox = (EditText)findViewById(mealCalId);
}
You seem to be using two different values: MealCalId when you create your EditText and mealCalId when you call findViewById. That's one possible problem. The other is that if you have more than one view with the same id, findViewById will not necessarily return the one you want.
EDIT
At first glance, your code looks like it should work. I don't know what's going wrong, but I have a suggestion for a work-around. When you create the view, instead of assigning it an ID, assign it a tag:
mealCalories.setTag(mealCalId);
(The int value will be autoboxed to an Integer.) Then in your onClick handler, retrieve it by tag:
EditText mealCaloriesInTextBox =
(EditText) getContentView().findViewWithTag(mealCalId);
If there's any kind of funny interaction with view IDs, this technique will avoid them.
If that doesn't work (or if you prefer anyway) you can also try diagnosing the ID-based retrieval using the Hierarchy Viewer.
For those who are having this error for the same reason I did....
Just try cleaning your project and re-building.
Solved it for me.
i tried to run your code and what i found is that
when menu item is not clicked and button is clicked, the edit text is null.
So if you will call any method on this object, it will crash with NULLPointerException
When menu item is clicked and then button is clicked, the edit text is not null so you call any method on this object.