I am new to android and am trying to make an app where the user inputs an array in a text box with inputType = textMultiLine. The problem is that I want to make it so that whenever user hits enter, the app takes input of the next array element and not treat the entire text in the textbox as one element. The code is as below :
EditText input = findViewById(R.id.inputtext);
Button show = findViewById(R.id.button);
TextView output = findViewById(R.id.output);
String [] name = new String[3];
for (int i = 0 ; i < 3 ; i++)
{
name[i] = input.getText().toString();
output.setText(name[i]);
}
But whenever i try to take name[1] after hitting enter the app doesnt treat the next line as name[2] but instead treats it as name[1]. For example if type the names john,steve and frank, then i should get an array that is like this :
name[0] = john
name[1] = steve
name[2] = frank
but instead whenever I typejohn,press enter,type steve, press enter and type frank the app treats it as :
name[0] = john
steve
frank
also if i set the output to something like this :
output.setText(name[i] + i)
instead of getting an oupt like this :
john 0
steve 1
frank 2
I get an output like this :
john
steve
frank2
Any and all help would be much appreciated.
Thanks
======================================================================================================================================================
EDIT 1
I tried this code but didn't work:
String name[] = input .getText().toString().split("\\r?\\n");
for (int i = 0 ; i < name.length; i++)
{
output.setText(name[i]);
}
Still get only frank when I input john,steve and frank
If you want to put each line to different array item :
String [] name = input.getText().toString().split("\n");
input.getText().toString() gives you string containing whole EditText content with lines separated by new line - "\n". You need to split this string to get each line.
try below code
String name[] = input .getText().toString().split("\\r?\\n");
String disp="";
for (int i = 0 ; i < name.length; i++)
{
disp += name[i] +"\n";
}
output.setText(disp);
Maybe the following example will be useful:
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/edit_text"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginBottom="100dp"
android:inputType="textMultiLine"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show"/>
<TextView
android:id="#+id/text_view"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"/>
</LinearLayout>
Java Code
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
final String newLine = System.getProperty("line.separator");
final String[] inputText = inputString.split(newLine);
String outputText = "";
for (int i = 0; i < inputText.length; i++) {
outputText += inputText[i];
if (i != inputText.length - 1) {
outputText += newLine;
}
}
output.setText(outputText);
}
}
});
}
You can download de APK here or here the complete source code
(another way:simple!) In the following code it is not necessary to make a split on the input text.
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
output.setText(inputString);
}
}
});
Note that, your code is wrong, because in for each loop, you override the text was setted in the previous loop.
Related
I want to thumbnail initials with two word for my image view like "Peter Parker" but am able to get only one word "P"while running code how can get second word after space my code is.
holder.imgName?.text=teamData[position].userImage.substring(0,1)
You can do it functional way:
val peterParker = "Peter Parker"
val initials = peterParker
.split(' ')
.mapNotNull { it.firstOrNull()?.toString() }
.reduce { acc, s -> acc + s }
println(initials) //PP
This would cover cases when a person's name consists of more than 2 words.
I have done some Trick & implemented this avatar with a Button lol ;p
create profile_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#color/colorWhite"/>
<corners
android:radius="500dp"/>
</shape>
then main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4300313A"
tools:context=".MainActivity">
<Button
android:onClick="clicked"
android:id="#+id/avatar"
android:clickable="false"
android:focusable="false"
android:textColor="#color/colorPrimary"
android:textSize="65sp"
android:focusableInTouchMode="false"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/profile_bg"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
<EditText
android:id="#+id/edtname"
android:layout_below="#+id/avatar"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:textSize="18sp"
android:hint="Enter your name"/>
<Button
android:onClick="clicked"
android:textColor="#color/colorBackground"
android:text="Submit Name"
android:textStyle="bold"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/edtname"
android:layout_marginTop="50dp"/>
</RelativeLayout>
then in MainActivity.java (to split the string and get the first letter of each word ~ name in if condition with stringbuilder)
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edtname);
button = (Button) findViewById(R.id.avatar);
}
public void clicked(View view) {
String str = editText.getText().toString();
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
//First name
if (strArray.length > 0){
builder.append(strArray[0], 0, 1);
}
//Middle name
if (strArray.length > 1){
builder.append(strArray[1], 0, 1);
}
//Surname
if (strArray.length > 2){
builder.append(strArray[2], 0, 1);
}
button.setText(builder.toString());
}
}
Hi you can using following way
String str = "FirstWord SecondWOrd";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
if (strArray.length > 0)
builder.append(strArray[0], 0, 1);
if (strArray.length > 1)
builder.append(strArray[1], 0, 1);
Log.d("New Text" , builder.toString());
it look's like your using substring to only grab the letters from position 0 to position 1, This is P in Petter
holder.imgName?.text=teamData[position].userImage
.substring(0,1)
If you'd like to grab the words Petter Parker, you have a few options.
• IndexOf & Substring - find the position of a string and get the subtext after.
• Substring - Subtext of string based on parameters
If you plan to change the text length at any stage, you'll need to find the start of the word ( int start = yourString.indexOf("Petter"));
and end of the word ( int end = yourString.indexOf(" "))
IndexOf will return the position of the first letter in your query - Your case it's P in Petter --- So start+"petter".length()
Here's an example of a barcode price checker app I'm working on
// STRING FORMAT 00000899999:0.99
String currentLine = "00000899999:0.99";
int breakPoint = currentLine.indexOf(":");
int end = currentLine.length();
int start = breakPoint + 1;
String Price = currentLine.substring(start,end);
Price will be starting after (:) With +1 or include (:) with no + 1 and end at the lines length.
I wrote an extension function in Kotlin to get initials for a name. You can use a custom view and use draw text and clip shape you want for avatar view.
val initials = "Vikas Patidar".asInitials()
fun String.asInitials(limit: Int = 2): String {
val buffer = StringBuffer()
trim().split(" ").filter {
it.isNotEmpty()
}.joinTo(
buffer = buffer,
limit = limit,
separator = "",
truncated = "",
) { s ->
s.first().uppercase()
}
return buffer.toString()
}
Not asked a question in a while so it's been long overdue!
I am creating an app where job items can be created onClick, with each new row containing a Description(EditText), a Price(EditText) and a button to delete the current row, but I am having trouble when getting the values from the EditText fields when there is more than one row - it just returns the values of the newest row.
Aside from the 'Job List Container', the views are created dynamically so pardon the lack of XML, but the structure of what I am trying to achieve is as follows, where clicking the Add button adds a row (this can be multiple rows) and clicking the submit button takes all of the Description and Price values and processes them (adds the prices and adds the job to the DB):
...and this is the code I've written for it called from the addNewJobRow onClick listener (all together for simplicity):
private void addJobItem() {
//Create a new row container
final LinearLayout jobRowContainer = new LinearLayout(this);
//Create a new EditText for the Description
final EditText description = new EditText(this);
description.setHint("Description...");
description.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
1.0f
));
//Create an EditText for the Price
final EditText price = new EditText(this);
price.setHint("00.00");
//Create a new button to delete the row
Button delete = new Button(this);
delete.setBackgroundColor(Color.RED);
delete.setText("X");
//Add Description, Price and Delete to the row container
jobRowContainer.addView(description);
jobRowContainer.addView(price);
jobRowContainer.addView(delete);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
for(int j = 0; j < jobRowContainer.getChildCount(); j++) {
if (jobRowContainer.getChildAt(i) instanceof EditText){
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
System.out.println("z! " + descriptionString + " # " + priceString);
}
}
}
}
});
}
I have tried a couple of iterations of this with and without the nested FOR loops and with and without the use of instanceof, but all it does is print out the newest row.
So, if I have multiple job rows, how can I get all of the values as required?
Thanks for your time and all that nice stuff xxx
The basic problem is that you're using only the last instance of description and price instead of each rows instance. (This may be what Dmitry is saying as well). To fix it, you need to get the input for each row. Here's one way.
Set an ID for description & price. (You can't just use '1' or '2', it needs to be a resource type ID so it is guaranteed to be unique). I made a dummy layout file of a row & assigned IDs in that to the 2 EditTexts. There may be a better way to do it. So anyway, add these 2 lines in your declarations
descripton.setId(R.id.description); and price.setId(R.id.price);
Now this is your onClick()
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
EDIT: I didn't want to change this answer since it had already been accepted so I've put a more concise solution in another answer.
Of cause, your last setOnClickListener takes strings
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
Where description and price - is fields in the function (last edittexts).
The good way to do that is to use RecyclerView/ListView, in "onTextChangeListner" of ViewHolder save new text to model of this object and print all text from your models, not directly from views.
I normally try to answer only question that was asked rather than change code that's not necessary. However, in this case, since I had created a dummy layout just to get Resource IDs, I wonder if that layout file could be put to use. I had started to change my answer but original one was accepted before I could make the changes. I've put a different version of the solution here. I didn't want to modify an answer that had already been accepted.
private void addJobItem() {
//Create a new row container
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout jobRowContainer = (LinearLayout)inflater.inflate(R.layout.row_layout, null);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
});
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/single_row">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Description..."
android:id="#+id/description"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="00.00"
android:id="#+id/price"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/holo_red_dark"
android:text="X"
android:id="#+id/clear_button"
/>
</LinearLayout>
I want to get the product of the inputted values in two editTexts.
For example I will input [1,2,3,4,5] in xValues then I will input also [6,7,8,9,10] in freqValues then it will multiply (1*6),(2*7),(3*8),(4*9),(5*10). How will i do that? Please help me. Thank you in advance:)
final AutoCompleteTextView xValues = (AutoCompleteTextView) findViewById(R.id.x_Values);
final AutoCompleteTextView freqValues = (AutoCompleteTextView) findViewById(R.id.frequency_Values);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int[]convertedx=new int[x.length];
int[]convertedfreq=new int[freq.length];
}
});
You'll have to do some error catching to make sure only numbers are inputted but once you get that figured out, do something like this:
...
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int product = 0;
for(int i = 0; i < x.length(); i++) {
int tempX = Integer.parseInt(x[i]);
int tempFreq = Integer.parseInt(freq[i]);
product += (tempX * tempFreq);
}
Assuming that the arrays are split correctly and only contain integers, this loop will grab the first int from X[] and Freq[] and then multiply them together, and add it to product, then grab the 2nd int from these arrays, parse the string into an int, and then multiply those and loop through until the end of the array.
Is there any way to set Button text to capital letter for the first character and all text is cap?
Layout:
<Button
android:id="#+id/q1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13sp"
android:textColor="#ffffff"
android:background="#drawable/ic_btn_q_normal" />
Activity:
final Button q1 = (Button) findViewById(R.id.q1);
q1.setText(answers[numbers.get(0)]);
q1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
q1.setBackgroundResource(R.drawable.ic_btn_q_right);
}
});
answers[numbers.get(0)] is the text that I get from array list.
I have tried with q1.setAllCaps(true); but it's doesn't work for me.
Thanks.
You can use: WordUtils
method:
capitalize(String str):
Capitalizes all the whitespace separated words in a String.
or: capitalizeFully(String str)
Converts all the whitespace separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.
final Button q1 = (Button) findViewById(R.id.q1);
String label = answers[numbers.get(0)];
StringBuilder sb = new StringBuilder();
sb.append( label .substring(0,1) );
sb.append( label .substring(1).toLowerCase() );
label = sb.toString();
q1.setText(label);
q1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
q1.setBackgroundResource(R.drawable.ic_btn_q_right);
}
});
Code for string conversion taken from: What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
I'm new to Android development. I tried to make a Textview display a text or number and it crashes. Please Help.
This is the button in activity_main.xml:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentBottom="true"
android:text="#string/Change"
android:onClick="change"/>
and this is the Main Activity:
public void change(){
TextView tv = new TextView(this);
tv.setText("" + 4);
}
the application crashes when i start it. I wanted to create a basic calculator with two text boxes and a button which when pressed adds the value in two text boxes and display it. can anybody tell me where I am going wrong with the code?
public void change()
{
TextView tv = new TextView(this);
tv.setText("4");
}
and if it is any kind of integer variable, then
public void change()
{
TextView tv = new TextView(this);
tv.setText("" + integer_variable);
}
and also, check if the textView is plumbed with the code
TextView tv = (TextView) findViewById(R.Id.textView1);
should have worked fine, I hope.. :)
If it crashes again, then the information in the question may be incomplete.
Happy Coding..!
public void change(){
TextView tv =(TextView)findViewById(R.id.textView1);
tv.setText(Integer.toString(4));
}
layout_contact.xml:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="#string/number1" />
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="number1">0091010</string>
</resources>
ContactFragment.java:
String num = "0091010";
textView8.setText(someContactNum);
Output:
0091010
You have to give id of the text view properly in the xml like
<TextView
....
android:id="#+id/tvID"/>
Check it you gave it properly or not..
Otherwise here share your textview code from your xml file..
And also checkit, you import the Textview in your code or not like this:
import android.widget.TextView;
Here is the answer for how to display the dynamic numbers in a single text view
StringBuilder stringBuilder = new StringBuilder();
for (int j = fromNumber; j <= toNumber; j++) {
for (int i = 2; i <= j / 2; i++) {
if (j % i == 0) {
isPrimeNumber = false;
break;
} else {
isPrimeNumber = true;
}
}
if (isPrimeNumber) {
stringBuilder.append(j);
stringBuilder.append(",");
} else {
}
}
tvResult.setText(stringBuilder.toString());