So I have a situation where I populate TextView from Intent extras and then allow users to edit it. When user taps on edit Button, EditText appears with text shown in TextView.
Then user can input new value.
And finally when the save Button is pressed, new value isn't saving, instead the old value is still shown.
Here's my code:
Bundle extras = getIntent().getExtras();
if (extras != null){
textViewNazivTodoaDetails.setText(extras.getString("naslov"));
textViewDatumTodoaDetails.setText(extras.getString("datum"));
final int id = extras.getInt("id");
String oldText = extras.getString("naslov");
editTextDetaljnoIspravljanje.setText(oldText);
}
final String newText = editTextDetaljnoIspravljanje.getText().toString();
buttonDetaljnoIspravljanjeDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewNazivTodoaDetails.setText(newText);
}
});
}
What am I doing wrong?
You are clearly setting the text back to old text inside your onClick with the following line.
textViewNazivTodoaDetails.setText(newText);
You don't need this line inside onClick. Instead of this you should have the code to save the new value to where ever you want to save it.
The line of code where you initialized newText was called before you edited it and contains the same value as oldText. Hence you see the old text again.
Your text view already has the newly entered text.
Related
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 trying to add the text written in a textfield everytime and add it into an ArrayList. For eg- if the text "abcdef" is written in the textfield, then it should get added into the list. Again if the text "ghijkl" is written in the textfield, than that should get added.
My code for adding the text into the listview:
final ArrayList<String> mylist = new ArrayList<String>(5);
String s3=text1.getText().toString();
if(s3!=null)
g++;
else g--;
if(g>0) {
for(int i=0;i<mylist.size();i++) {
mylist.add(s3);
Toast.makeText(getApplicationContext(), mylist.get(i), Toast.LENGTH_LONG).show();
}
}
Is this the right way to do this? Also I am trying to get the list item for testing purpose, but I don't get any toast.
I assume you like to add the Content of your EditText field into the list after pressing a button, so you could do it like this:
// Member to store your Texts in list
private ArrayList<String> _list = new ArrayList<>()
// Method to call to add an entry to your list
// Either by pressing a button, removing focus of your edit text or something else
private void addTextToList()
{
String text = text1.getText().toString();
if (text != null)
{
_list.add(text);
}
}
private void showToast()
{
for(String text: _list)
{
Toast.makeText(this, mylist.get(i), Toast.LENGTH_LONG).show();
}
}
The toast is not shown because you need to pass your current activity.
Assuming your Code is in your activity, I passed this in the example above.
you have to make a button to handle this action every click i make editTex ,textView and Button
this is the action of button it every click take the value of editText and stor it in ArrayList and increse String by this value
public void getText(View v){
if(ed.getText().toString().length()!=0){
s+="\n"+ed.getText().toString();
arr.add(ed.getText().toString());
}
tv.setText(s);
}
I have an edittext in first activity (apples.java). User can write anything using edittext which is passed as a string to second activity (Bacon.java) on clicking a button. Second activity has a textview written Bacon. When a string is passed from first activity, Bacon is replaced with the passed string/text.
What is happening : When nothing is written using editText and button is clicked to go to second activity, Bacon disappears.
My requirment is that if nothing is passed using EditText and only button is clicked, Bacon should not get replaced.If something is passed, it should replace Bacon.
apples.java:
Intent i = new Intent(apples.this,Bacon.class);
final EditText applesInput = (EditText) findViewById(R.id.applesInput);
String userMessage = applesInput.getText().toString();
i.putExtra("applesMessage",userMessage);
startActivity(i);
Bacon.java
final TextView baconText = (TextView) findViewById(R.id.baconText);
Bundle applesData = getIntent().getExtras();
if(applesData==null){
Toast.makeText(Bacon.this, "Love u", Toast.LENGTH_SHORT).show();
return;
}
String applesMessage = applesData.getString("applesMessage");
baconText.setText(applesMessage);
This is first activity
This is second activity
Do this:
if (!TextUtils.isEmpty(applesMessage))
baconText.setText(applesMessage);
In apples.java write if(applesInput.getText().toString().equals(""); { i.putExtra("applesMessage",userMessage);} just add this..
your problem is that Bundle is not null, so the condition is never satisfied.no string is set does not mean that your bundle is Null
change it to
final TextView baconText = (TextView) findViewById(R.id.baconText);
Bundle applesData = getIntent().getExtras();
if(applesData!=null){
String applesMessage =applesData.getStrng("applesMessage")
if(applesMessage ==null ||applesMessage .trim().equals("")){ //trim to delete spaces
Toast.makeText(Bacon.this, "Love u", Toast.LENGTH_SHORT)
.show();
return;
}
baconText.setText(applesMessage);
}
}
I have an EditText field that represents an ID number. That field can either be filled programmatically, using IDField.setText(String) based on the results of a card swipe, or it can be filled manually using the keyboard.
Once the text is filled both methods (auto login--based on swipe, or manual--based on button click) both run the same sign in script. However when I go to grab the contents of the EditText field, if I edited the text manually I get an empty string returned. If the text was set programmatically then it works perfectly.
This doesn't make any sense to me. Is there a reason that editText.getText().toString() would not return the content that is visibly shown in the textbox?
XML:
<Button
android:id="#+id/btn_swipeCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/signInID"
android:layout_toLeftOf="#+id/textView1"
android:onClick="SignInStudent"
android:text="Swipe ID" />
Button Initialization:
IDField = (EditText) layout.findViewById (R.id.signInID);
LoginButton = (Button) findViewById(R.id.button1);
LoginButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { SignInStudent(); } } );
Card Swipe:
// displays data from card swiping
private Runnable doUpdateTVS = new Runnable()
{
public void run()
{
try
{
//Grab ID Number
String[] splitMSG = strMsrData.split("=");
//txtIDNumber.setText(splitMSG[2]);
IDField.setText(splitMSG[2]);
StringBuffer hexString = new StringBuffer();
hexString.append("<");
String fix = null;
for (int i = 0; i < msrData.length; i++) {
fix = Integer.toHexString(0xFF & msrData[i]);
if(fix.length()==1)
fix = "0"+fix;
hexString.append(fix);
if((i+1)%4==0&&i!=(msrData.length-1))
hexString.append(' ');
}
hexString.append(">");
myUniMagReader.WriteLogIntoFile(hexString.toString());
SignInStudent();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};
Sign In Logic:
public void SignInStudent()
{
String temp = "http://wwww.tempUrl.com/signIn?ID="+ IDField.getText().toString() + "&DeviceId="+KEY;
webView.loadUrl(temp);
}
The layout is only updated during the onCreate phase of the loop. This is fired when an onResume event is called as well which explains why the fields update after you lock and unlock the device. There are a few workarounds for this such as doing more background processing and then creating a new view with correct values, or using a surfaceView that allows drawing to occur while the program is in its normal execute cycle.
For my application I either do background processing and then move to a new view, or have a view that just keeps calling itself to get the onCreate events to fire again. The solution depends on the application, but that's why the problem occurs.
I have an activity with a TextView that needs to be updated from a second activity.
I can pass the Text view data to the 2nd activity ok, but when I try to update that TextView
within the 2nd activity it crashes. My code:
1st Activity (where the TextView is defined in my xml):
Intent intent = new Intent(1stactivity.this, 2ndactivity.class);
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
startActivity(intent);
// code snippet
Then in my 2nd activity:
Bundle bundle = getIntent().getExtras();
hometext = bundle.getString("homescore_value"); // this works and displays the correct String from 1st activity,
but it crashes when I try to pull in as a TextView:
// other code snipped
int homescore = 0;
String Home_nickname = "HOME ";
TextView homestext = (TextView) bundle.get("homescore_value");
hometext.setText(Home_nickname +": "+homescore );
Please help.
You are trying to get a String as a TextView (you are setting a String in the intent from the first Activity).
You trying to cast String to TextView. The code that crashes is equivalent of:
String text = bundle.get("homescore_value"); //this is ok
TextView textView = (TextView)text; //this is bad
You should do instead:
String text = bundle.get("homescore_value");
TextView textView = (TextView)findViewById(R.id.yourTextViewId);
textView.setText(text);
This line here:
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
is attaching a String along with the intent, not a TextView.
You must inflate a new TextView within the 2nd activity, by either declaring it in the layout.xml, or programmatically placing it within the layout.
Something that solved part of this problem for me was setting the receiving String variables to null like this:
public String param1new = null;
public String param2new= null;
My issue with this is I'm trying to set background colors on several TextViews and only the first one is being set at this time.