I have some troubles trying to put an id to a dynamic edittext and texview in Android Studio, i want to use this id to get the id's in another functions.
Note: Im not setting any id in the onCreate function.
This is my code:
for (Map.Entry<String,String> entry : getMap(newContact).entrySet()) {
total++;
TextView ProgrammaticallyTextView = new TextView(this.getActivity());
EditText ProgrammaticallyEditText = new EditText(this.getActivity());
ProgrammaticallyTextView.setId(total);
ProgrammaticallyEditText.setId(total+1);
ProgrammaticallyTextView.setText(entry.getKey());
ProgrammaticallyEditText.setText(entry.getValue());
linearLayout.addView(ProgrammaticallyTextView);
linearLayout.addView(ProgrammaticallyEditText);
total++;
}
This is the function that i use the edittext and textview id's
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_create:
String test = "";
for(int i=0; i < (this.total); i+=2){
TextView tv = (TextView) v.findViewById(i++);
EditText et = (EditText) v.findViewById(i+2);
if ((i+2) >= this.total){
test += tv.getText()+"="+et.getText();
}else
{
test += tv.getText()+"="+et.getText()+",";
}
}
mContact = getMap(test);
newContactRequest();
break;
}
}
I appreciate any help!
You need to explicitly change the data type to string. Just writing i++ tries to assign that value as an integer.
I think if you change your lines to these it should work.
TextView tv = (TextView) v.findViewById(String.valueOf(i++));
EditText et = (EditText) v.findViewById(String.valueOf(i+2));
Related
I am completely lost and don't have enough knowledge on coding/android studio.
I have the EditTexts (FoodIncomeCounter, FoodCampX, and FoodUpgradeX) as inputs.
Then the TextView (FoodIncomeResult) as output.
The 1st button (IncomeSubmitButton) Works properly. The 2nd button (FoodCampSubmitButton) does not, I want it to take the input of the FoodCampXs and FoodUpgradeXs then do a calculation and put that into integer TotalFood, then output TotalFood to the FoodIncomeResult TextView.
How the heck do I do this? I feel like I am close but I don't know what is wrong.
Thank you for the help!!!
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText FoodIncomeCounter;
EditText FoodCamp1Counter, FoodCamp2Counter, FoodCamp3Counter, FoodUpgrade1Counter, FoodUpgrade2Counter, FoodUpgrade3Counter;
TextView FoodIncomeResult;
int FoodIncome;
int FoodCamp1, FoodCamp2, FoodCamp3, FoodUpgrade1, FoodUpgrade2, FoodUpgrade3;
int TotalFood;
Button IncomeSubmitButton, FoodCampSubmitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
FoodIncomeResult = (TextView) findViewById(R.id.FoodIncomeResult);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
//Submit button
IncomeSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to receive the inputted values
Food = Integer.parseInt(FoodIncomeCounter.getText().toString());
//to show the inputted values into the result fields
FoodIncomeResult.setText(FoodIncomeCounter.getText().toString());
}
});
//Submit button
FoodCampSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
FoodIncomeResult.setText(String.valueOf(TotalFood));
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.screenlocked);
//Retrieve stored ID
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
LoginID = unique.getString("identifier", "");
//Retrieve stored phone number
final String phoneNumber = unique.getString("PhoneNumber", "");
phoneView = (TextView) findViewById(R.id.phone);
phoneView.setText(phoneNumber.toString());
//Retrieve user input
input = (EditText) findViewById(R.id.editText1);
userInput = input.getText().toString();
//Set login button
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
compareID();
}
});
}
public void compareID(){
if (userInput.equals(LoginID)){
//phone screen unlocked
//continue
Toast.makeText(ScreenLockActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else{
count += 1;
input.setText("");
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
}
}
I am developing a login activity and I would like to record down how many times the user tried to login, so every time there is a login attempt the count will increment by one... but when i run the activity, this error appears in my logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1,
Can someone help me solve this problem?
Here is your mistake:
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
the makeText you are trying to invoke here, is the makeText that takes as second parameter a resId. See here for more info. Since you want to print the count value, you have to convert it in a String.
String value = String.valueOf(count);
Toast.makeText(ScreenLockActivity.this, value, Toast.LENGTH_SHORT).show();
This line should be inside onClick() or compareID():
userInput = input.getText().toString();
I am currently working on an app, but there is a bug in it. Whenever a user installs the app or clears data, it should get reset. But instead the app fills in standard data for the user, instead of showing the start screen where user can input himself.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
savedData();
}
public void savedData() {
showGoalTextView = (TextView) findViewById(R.id.textView3);
showBeamsTextView = (TextView) findViewById(R.id.textView2);
showGoalEditText = (EditText) findViewById(R.id.editText2);
checkBtnPressed = (ImageButton) findViewById(R.id.imageButton5);
showBeamsEditText = (EditText) findViewById(R.id.editText4);
beamsGoal = (EditText) findViewById(R.id.editText4);
//Fetch the stored data and display it upon starting.
String goalSave = showGoalTextView.getText().toString();
String beamsSave = showBeamsTextView.getText().toString();
preferences = getSharedPreferences("userData", MODE_PRIVATE);
goalSave = preferences.getString("goals", goalSave);
beamsSave = preferences.getString("beam", beamsSave);
showGoalTextView.setText(goalSave);
showBeamsTextView.setText(beamsSave);
//Hide all the first use stuff
showGoalEditText.setVisibility(View.GONE);
checkBtnPressed.setVisibility(View.GONE);
showBeamsEditText.setVisibility(View.GONE);
beamsGoal.setVisibility(View.GONE);
}
public void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
//Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
//Get saved version
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = preferences.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);
//Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
//No big deal
return;
} else if (savedVersionCode == DOESNT_EXIST) {
//TODO This is a new install
resetAll();
} else if (currentVersionCode > savedVersionCode) {
//TODO This is an upgrade
return;
}
//Update sharedPreferences with the current version code
preferences.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
public void resetAll() {
//For when resetting
TextView showGoalTextView =
(TextView) findViewById(R.id.textView3);
EditText showGoalEditText =
(EditText) findViewById(R.id.editText2);
ImageButton checkBtnPressed =
(ImageButton) findViewById(R.id.imageButton5);
EditText showBeamsEditText =
(EditText) findViewById(R.id.editText4);
EditText beamsGoal =
(EditText) findViewById(R.id.editText4);
//Clear editTexts
showGoalEditText.getText().clear();
showBeamsEditText.getText().clear();
//Show all editTexts
showGoalEditText.setVisibility(View.VISIBLE);
checkBtnPressed.setVisibility(View.VISIBLE);
showBeamsEditText.setVisibility(View.VISIBLE);
beamsGoal.setVisibility(View.VISIBLE);
//Get the text view
TextView showResetTextView =
(TextView) findViewById(R.id.textView2);
//Get the value of the text view
String resetString = showResetTextView.getText().toString();
//Convert value to a number and reset it
Integer reset = Integer.parseInt(resetString);
reset = 0;
//Display the new value in the text view.
showResetTextView.setText(reset.toString());
showGoalTextView.setText("BEAMS");
}
My question is mainly on the checkFirstRun method.
I want to input:
} else if (savedVersionCode == DOESNT_EXIST) {
//TODO This is a new install
resetAll();
Unfortunately, I can't get it to work. Can anyone point out the issue at hand?
SharedPreferences is not cleared with uninstall (at least, not since Marshmallow). This might help you solve it SharedPreferences are not being cleared when I uninstall
I am building an android application where I am creating dynamic EdittextView. I need to display the sum of integer enter in it by the user. Below is my code to create Dynamic EdittextView:
for (int i = 1; i < ZipRunApplication.ConfigLeg; i++){
LayoutInflater inflater = null;
inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = inflater.inflate(R.layout.drop_money, null);
TextView droxTextView = (TextView) mLinearView.findViewById(R.id.dropTextView);
final TextView position = (TextView) mLinearView.findViewById(R.id.position);
final TextView Amount = (TextView) mLinearView.findViewById(R.id.Amount);
final EditText dropEditTextView = (EditText) mLinearView.findViewById(R.id.dropEditext);
dropEditTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
Amount.setText(dropEditTextView.getText().toString()); //
}
});
droxTextView.setText("Amount to be pick From Drop " + String.valueOf(i));
position.setText(String.valueOf(i));
droxTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
container.addView(mLinearView);
}
Could any one help me getting the sum of the all the EdittextView created Dynamicly.
Answer for:
Could any one help me getting the sum of the all the EdittextView
created Dynamically.
You can maintain an ArrayList of EditText and then can iterate through them and get the text entered in each of them and find the sum.
As an example I have the following snippet:
LinearLayout layout;
List<EditText> concernedEditTexts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout)findViewById(R.id.base_layout); // Base layout defined in xml
concernedEditTexts = new ArrayList<EditText>();
// Creating five EditTexts
for(int i= 0; i< 5; i++){
EditText text = new EditText(getApplicationContext());
layout.addView(text);
concernedEditTexts.add(text); // Adding dynamically created EditText in the ArrayList
}
Button button = new Button(getApplicationContext());
button.setText("Get Sum");
layout.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sum = 0;
// Iterate through the List and find the sum
for(EditText editText : concernedEditTexts){
sum+= Integer.parseInt(editText.getText().toString());
}
Log.d("SUM","Sum is "+sum);
}
});
}
Note: This code is kind of raw and needs a lot more validations, but should be enough to explain the concept.
In your example you will need to store every dropEditTextView in the List and then iterate through the list as shown in my example will give you the desired result.
you can use
Integer.parseInt(dropEditTextView.getText().toString())
setTag() to each EditText as i variable and take an arrarylist of size ZipRunApplication. when you write in edittext then in textchnage listener get tag value and convert to int. This value will tell you for which position in arraylist you are writing . then in that position of arraylist set Integer.parseInt(editTextString).
Four tips:
1 - Here we get the childs by the parent:
for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
if (mLinearLayout.getChildAt(i) instanceof LinearLayout) {
LinearLayout ll = (LinearLayout) mLinearLayout.getChildAt(i);
for (int j = 0; j < ll.getChildCount(); j++) {
if (ll.getChildAt(j) instanceof EditText) {
ll.getChildAt(j).setOnFocusChangeListener(this);
}
}
}
}
2 - Don't forget to parse the data you try to receive:
Integer.parseInt(mFocusedEditText.getText().toString());
3 - note:
view.setTag() <-> View.getTag()
4 - And last but not least: In terms of readability, maintainability and performance you will get to a point soon, where a ListView- or RecyclerView will fit your needs MUCH better (so keep in mind: the above coding isn't a proper solution, even if it works).
ListView and
RecyclerView
Can anyone please guide me on how to setOnClickListener for the TextViews that are generated dynamically.
I have few buttons in my app.Now when a particular button is clicked than some specific text elements are retrieved from the database based on the the number of elements returned corresponding TextViews are generated in order to display the retrieved text elements.
Now the problem that i'm having is that i don't know how to set onClickListner for the dynamically generated TextViews.Following is the piece of code where i'm creating my TextViews.Please guide me on what should i do.thank you
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
catagory = "General";
IndependentDB genData = IndependentDB.getInstance();
genData.open(this);
ArrayList<TextHolder> genList = new ArrayList<TextHolder>();
genList = genData.getAllTextFromGenT();
genData.close();
x = genList.size();
String xstr = new StringBuilder().append(x).toString();
System.out.println(xstr);
mainText = new TextView[x];
textLayout = new LinearLayout[x];
llseperator = new LinearLayout[x];
textLayoutContainer
.setBackgroundResource(R.color.dark_navy_blue);
if (!genList.isEmpty()) {
for (int i = 0; i < x; i++) {
TextHolder firstOne = genList.get(i);
String text = firstOne.getText();
mainText[i] = new TextView(this);
mainText[i].setId(i);
mainText[i].setText("Text");
mainText[i].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mainText[i].setTextSize(25);
mainText[i].setGravity(Gravity.CENTER);
mainText[i].setText(text);
mainText[i].setTextColor(0xFFFFFFFF);
mainText[i].setClickable(true);
mainText[i].setOnClickListener(this);
llseperator[i] = new LinearLayout(this);
llseperator[i].setId(i);
llseperator[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
llseperator[i].setGravity(Gravity.CENTER);
llseperator[i]
.setBackgroundResource(R.drawable.tv_seperator);
textLayout[i] = new LinearLayout(this);
textLayout[i].setId(i);
textLayout[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
textLayout[i].setGravity(Gravity.CENTER);
textLayout[i].addView(mainText[i]);
textLayoutContainer.addView(textLayout[i]);
textLayoutContainer.addView(llseperator[i]);
}// End of for
}// End of If
break;}
You already have onClick() method in Activity class (implemented View.setOnClickListener) so I suggest you to create a new class which implements View.setOnClickListener interface to handle click of TextView.
Try,
class TextClick implements View.setOnClickListener {
#Override
public void onClick(View view) {
TextView tx=(TextView) view;
...
}
}
and set click listener,
TextClick click=new TextClick();
for (int i = 0; i < x; i++) {
TextHolder firstOne = genList.get(i);
String text = firstOne.getText();
mainText[i] = new TextView(this);
mainText[i].setOnClickListener(click);
...
}
It's the same setting on click listeners regardless of if the view was dynamically generated.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dosomething();
}
});
For example. you have a List tvs to store your TextView Objects created by the db result. What you should do is like this:
for(int i =0;i<tvs.count;i++){
tvs.get(i).setOnClickListener(new OnClickListener(){
...
})
}