How can I add custom data to textview in android? - java

I'm new to JAVA and Android. Previously, I was working on Javascript & Jquery.
As in HTML using Javascript (or Jquery) we can add custom data attribute to any element. for example-
$("#element").data("customdata", "customvalue");
And later I can get the value by doing-
var customvalue = $("#element").data("customdata");
Is there any method available in Android to achieve this type of thing?
Like, if I need to set multiple type of strings to a single TextView and later get them as needed.
Thank you all in advance.

You can get your textview from XML and set text on it . Something like this
TextView textView = findViewById(R.id.textview_id);
textView.setText("Your awesome text");
// Later fetch the text details back
String textDetails = textView.getText().toString();
This is a basic code sample of how to add and retrieve text from the text-view. Hope this help your case

You can use the View's setTag() and getTag() for that purpose.
However, most of the time there are cleaner ways like using ViewModel architecture etc. but that is a different story.

I saw your link. I think you can use AlertDialog.
this is my code.I think you would need it.
public class MainActivity extends AppCompatActivity {
EditText e1;
TextView t4;
Buttob btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t4=(TextView)findViewById(R.id.t4);
t4.setOnClickListener(t4click);
e1=(EditText)findViewById(R.id.e1);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(btnlogin);
}
private Button.OnClickListener btnlogin=new Button.OnClickListener(){
//click button
public void onClick(View v){
String account=e1.getText().toString();//get edittext value
String tmp="";
tmp=t4.getText().toString()+account; //get textview value and add
edittext string
t4.setText(tmp);//insert new value
}
}
};
private TextView.OnClickListener t4click=new TextView.OnClickListener(){
#Override
//if click textview it,would show dialog
//if your dialog value is from edittext ,you can reuse it.
public void onClick(View view) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("product")
.setMessage("item:pen"+"\nid=A001"+"\nprice:10 USD")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
};
}

Related

Saving Edittext and making it stay on EditText

I have an app where I take the Name of the user in an editText and I have it storing to firebase but when I get out of the activity and go back into it, the editText field does not show the Name of the user anymore. I want their name to stay in the editText field.
also how would I do the same thing but for an image in an ImageView that the user puts in. Please help.
IDEA:
You can use shared preference. When user launches his application first task will be load his user name and password from shared preference.
By doing this you can also manage a session manager for better user experience.
For example: After every successful authentication you can store the basic information of the user that is needed to update the screen everytime.
Benefit:
This will help you to show old data on screen if user launches your app without internet enabled. You can check the internet and if disabled then simply show the old data from preference.
You Can do something like this
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
text.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
prefs.edit().putString("autoSave", s.toString()).commit();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
//At here you can call some method to get the text from shared preferences and display it on EDitText
}
or You can save into DB at onTextChanged() method
Here is a little activity example which saves the username into SharedPreferences at stop of activity and restores the value to the EditText when activity is (re)started:
public class Test extends Activity {
EditText edtUser;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
edtUser = (EditText) findViewById(R.id.editTextUser);
edtUser.setText(preferences.getString("username", ""));
}
#Override
protected void onStop() {
super.onStop();
preferences.edit().putString("username", edtUser.getText().toString()).commit();
}
}
Set on click listener to edit text.
Inside on click enable edit text and write to firebase using setValue.
Set on click to parent layout or check is focus changed of edit text. Inside read from firebase using add value event listener.
In Oncreate disable edit text and read from firebase using add value event listener.
This will auto save and retrieve edit text data seamlessly.
In OnCreate create method of activity
//Initialize edittext
mEditText = (EditText) findViewById(R.id.edittext);
// Disable mEditText
mEditText.setEnabled(false);
//Read from firebase and set text to mEditText if mTextEdit is not in focus
if (!mEditText.isFocused()){
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String editTextData = (String) dataSnapshot.getValue();
mEditText.setText(editTextData);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
// Set onclick listener to mEditText
mEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mEditText.setEnabled(true);
editTextData = mEditText.getText().toString();
mFirebaseRef.setValue(editTextData);
}
});
This works for me and UI looks simple without any extra buttons to switch between edit and save.
Hope I understood your requirement correctly. Thanks

how to use java onclick shuffle array

I am learning how to use strings and onlclick in java. I have written a programme below which shuffle three names and then outputs them into three buttons.
When I click on Paul, I want the message to be displayed in message box. Since Paul will be in a button each time. I am puzzled on how to attach my message to Paul.
Paul moves around due to the use of array. I understand this is a tough question, but I also know, there are some very clever ppl out there who love a challenge.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void generate(View view) {
String [] names = new String[3];
names[0] = "Bob";
names[1] = "Paul";
names[2] = "Mike";
Button btn_a = (Button) findViewById(R.id.a);
Button btn_b = (Button) findViewById(R.id.b);
Button btn_c = (Button) findViewById(R.id.c);
TextView message = (TextView)findViewById(R.id.message);
Arrays.asList(names);
Collections.shuffle(Arrays.asList(names));
btn_a.setText(names[0]);
btn_b.setText(names[1]);
btn_c.setText(names[2]);
}
public void a1(View view) {
}
public void b1(View view) {
}
public void c1(View view) {
}
}
This is a trick practical implementation in Java where a single listener is used for multiple buttons, rather than one listener for each button, so that each button's content determines what happens, not each button's listener. Helps for dynamic button grids (i.e. an 8x8 chessboard) to not define 64 listeners and code them all.
I don't have an Android IDE on hand, so this is pseudo-code, but you should be able to get the gist from this.
//Create a Universal Listener for all our buttons
OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText().toString(); //get the button's name
if(text.equals("Paul")) {
//do anything for Paul ONLY in here
}
}
});
btn_a.setOnClickListener(listener); //give all the buttons the same listener, but only Paul's listener will do anything when you click on it
btn_b.setOnClickListener(listener);
btn_c.setOnClickListener(listener);
Using info from: http://developer.android.com/reference/android/widget/Button.html and https://stackoverflow.com/a/5620816/2958086

Android button with multiple click simple

i am new in android programming, and i am working on my first application, so i just want to know how every time when i click same button it does some action, for example if i have a button called ( next ) and i want to click on it and an image will appear, this one i did it, but i want to click on the same button and show another image view in the same activity.
i have tried some code but with no results
so please if anyone can post a code that explain how i can do it.
Here is a quick example of code...
Rather than show a random image, it will show a random String. All you need to do is just modify it to show images instead.
public class MainActivity extends Activity {
private String[] names = {"Joe", "Mark", "Amanda", "Kelly", "Michael", "Jenny"};
private Button button;
private TextView name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get our views
name = (TextView) findViewById(R.id.name);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
next(); // show random name
}
});
}
// Display random name on button click
private void next() {
name.setText(names[rand()]);
}
// Pick a random number from 0 to names.length
private int rand() {
return new Random().nextInt(names.length);
}
}

How to obtain Edittext values from dynamically created editttexts using a single button

I am splitting a string and putting the result in edittexts using a loop so that the user can edit the data.thereafter he can save all the data in
the edittexts by just pressing the final button.Problem is i don't know how to get each value from the edittext when he pressses the save button.this is my code:
EditText etstringone,etstringtwo;
Button btn_save;
btnsave=new Button(this);
String mystring="somevalue";
String del="\\|";
String[] splitResult = mystring.split(del);
for (String e : splitResult)
{
etstringone=new EditText(this);
etstringtwo=new EditText(this);
etstringone.setText(splitResult[0]);
etstringtwo.setText(splitResult[1]);
mylayout.addView(etstringone);
mylayout.addView(etstringtwo);
}
mylayout.addView(btnsave);
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// how to get each value from the edittexts and output each to logcat,,i'll do the saving and the rest
}
});
how do i go about this?thanks.
NB:emphasis on using a single button to get all the data,i managed to do a scenario for apppending a new save button each time the
loop runs but its not neat.
The edit texts are dynamically created, but you can still access the object. Either cache a reference to the edit texts or walk the child-views of your "mylayout".
EDIT
From your code, you declare
EditText etstringone,etstringtwo;
You instantiate them
etstringone=new EditText(this);
etstringtwo=new EditText(this);
Now I don't know the scope of this (are they local vars, class/member vars?) if class vars, you can reference them in the
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// how to get each value from the edittexts and output each to logcat,,i'll do the saving and the rest
}
});
body. eg
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String e1 = etstringone..getText().toString();
}
});

How to assign a numerical value to a check RadioButton and pass this onto the next activity (similar to a questionnaire app)

I am new to Android development and I am trying to design a simple questionnaire-type app. Each question has set answers within a RadioGroup. I would like to assign a numerical value to the checked RadioButton so I can then send this to the next activity where eventually it will be used to total the scores and produce a message.
I have been able to create a toast; for testing, to show which RadioButton is checked. But I am having trouble with assigning a value to each RadioButton once checked. I know that I will need to use a IF statement but not sure how. Can anyone help or send me a link to a good tutorial?
Here's some sample code within one of my .java file;
public class Diabetes_Question_1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diabetes_question_1);
Button btnBack = (Button) findViewById(R.id.btnBack1);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Diabetes_Question_1.this, Diabetes_Question_2.class));
}
});
final RadioGroup radioDQ1Group = (RadioGroup) findViewById(R.id.radioDQ1Group1);
Button btnNext = (Button) findViewById(R.id.btnNext1);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Diabetes_Question_1.this, Diabetes_Question_3.class));
int selectedId = radioDQ1Group.getCheckedRadioButtonId();
RadioButton rb1 = (RadioButton) findViewById(selectedId);
Toast.makeText(Diabetes_Question_1.this, rb1.getText(), Toast.LENGTH_SHORT).show();
}
});
}
};
Every view has a tag- an object that can hold whatever data you want. Use it to hold the integer value- you can do that via setTag() and getTag(). Then when you start the new activity, add it to the extras bundle of the intent you launch. The new activity should then read that value from the incoming intent.

Categories

Resources