Android Pass value to another activity - java

I have a MainActivity with 30 buttons (Ids: imageButton1,imageButton2...). On the click event, I'm starting a new activity called KlikNaDugme:
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
buttons = new ImageButton[30];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}
}
I'm trying to pass vr to the KlikNaDugme activity, which is declared as a public int.
KlikNaDugme Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klik_na_dugme);
int x = getIntent().getExtras().getInt("vrijednost");
System.out.println(x);
}
The problem is that it always gets a value of 29. How can I pass the id correctly?

Store the value of i in the button's tag:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(getResources().getIdentifier("imageButton" + (i + 1), "id", this.getPackageName()));
buttons[i].setTag(i);
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class)
myIntent.putExtra("vrijednost", Integer.parseInt(view.getTag().toString()));
startActivity(myIntent);
}
});
}
}

The problem lies here:
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
What you are doing is that you're creating an invalid resource reference and then finding your view upon that reference, which is obviously wrong. Remember findViewById() needs a resource id which is generated by Android Studio itself.
The solution is to save all of your 20-30 views references in an array and then use a loop to set click listeners on them

Add the vr value as tag to button and then use getTag() method to get the vr value inside onclicklistener
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setTag(vr); // This will se the vr value as tag
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int vr = (int)view.getTag() // this will get the vr value from view
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}

R.id.what_ever will give you an integer value that generated by android studio in R class not the what_ever string. You should use getResources().getIdentifier() to get correct id of resource and pass it to findViewById().
Please try this code. It will get you the correct id of ImageButtons:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
String buttonID = "imageButton" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = (ImageButton) findViewById(resID);
buttons[i].setTag(i);
//vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View args0) {
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", (int)args0.getTag());
startActivity(myIntent);
}
});
}
Enjoy it.

Related

Looping through an array of edittexts and getting the texts of each

I have an autogenerated list of edittexts gotten from the user input. What i want to do is shuffle the edittexts when the shuffle button is clicked or get the texts and set them to different edittexts. What i tried doing is to get the texts of each edittext adding it to an arraylist and shuffling it and then recreating the layout with the shuffled list. But that in itself is giving me errors. When the shuffle button is clicked it gives me this error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
Thanks For the help
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnForCreate = (Button) findViewById(R.id.btnCreateTxt);
editTextForInputToCreate = (EditText) findViewById(R.id.textForInputToCreate);
listLayout = (LinearLayout) findViewById(R.id.listLayout);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnShuffleTxt = (Button) findViewById(R.id.btnShuffleTxt);
editTextForInputToCreate.animate().translationX(-1000f);
btnForCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bringTextInputBackOnScreen();
}
});
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextForInputToCreate.getText().toString().length() >= 0) {
try {
listLayout.removeAllViews();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
length = Integer.parseInt(editTextForInputToCreate.getText().toString());
for (i = 0; i < length; i++) {
editTextCollection = new EditText[length];
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
}
});
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
}
});
}
private void bringTextInputBackOnScreen()
{
editTextForInputToCreate.animate().translationXBy(1000f).setDuration(2000);
}
`
Please make some corrections in your EditTextCollection.
editTextCollection = new EditText[length];// initialization outside the loop
for (i = 0; i < length; i++) {
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
for (EditText gottenEditText:editTextCollection)
{
gottenEditText.setText(list.get(editTextCollection.indexOf(gottenEditText)));
}
}
});

Calculate total checkboxes ticked and perform calculation (Android Java)

I have checkboxes created dynamically using shared preferences. The label for each checkbox is stored in array.xml. How can I calculate the total number of checkboxes that are ticked and store the total in a variable and further use it for another calculation -- (total/totalCheckboxes)*100?
Here's a snippet of the Java class:-
public class CheckBoxSharedPreferences extends Activity {
ListView myList;
Button getChoice, clearAll, button1;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice";
ArrayList<String> selectedItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView) findViewById(R.id.list);
getChoice = (Button) findViewById(R.id.getchoice);
clearAll = (Button) findViewById(R.id.clearall);
button1 = (Button) findViewById(R.id.button1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
// code snippet to retrieve array values in ArrayAdapter
getResources().getStringArray(R.array.Questionnaire));
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(MyPREFERENCES)) {
LoadSelections();
}
getChoice.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = myList.getCount();
SparseBooleanArray sparseBooleanArray = myList
.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString()
+ "\n";
System.out.println("Checking list while adding:"
+ myList.getItemAtPosition(i).toString());
SaveSelections();
}
}
Toast.makeText(CheckBoxSharedPreferences.this, selected,
Toast.LENGTH_LONG).show();
}
});
//listener for clear all button
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClearSelections();
}
});
//listener for button1 (that transfers the activity to another intent
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(CheckBoxSharedPreferences.this,
result.class);
startActivity(intent);
}
});
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the
// user
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.myList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.myList.getItemAtPosition(i);
} else {
savedItems += this.myList.getItemAtPosition(i);
}
}
}
return savedItems;
}
private void LoadSelections() {
// if the selections were previously saved load them
if (sharedpreferences.contains(MyPREFERENCES.toString())) {
String savedItems = sharedpreferences.getString(
MyPREFERENCES.toString(), "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter().getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
Toast.makeText(getApplicationContext(),
"Current Item: " + currentItem, Toast.LENGTH_LONG)
.show();
} else {
myList.setItemChecked(i, false);
}
}
}
}
and the array.xml:-
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="Questionnaire">
<item>abc</item>
<item>jkm</item>
<item>xyz</item>
<item>abc2</item>
<item>jkm2</item>
<item>xyz2</item>
<item>abc3</item>
<item>jkm3</item>
<item>xyz3</item>
</resources>
Thanks in advance!
Use this code where you want to get the total number of checked items and perform the calculation
int checkedCount = myList.getCheckedItemCount();
int totalCount = myList.getAdapter().getCount();
int calculatedValue = (totalCount/checkedCount) * 100;

Android - Dynamically set intent Extras

I'm trying to pass an ID to my new activity on creation.
The obvious solution seems to be to use "Intent.putExtra(name, value);".
But as the intent is only created on click, all of my buttons have the same Intent extras (useally null).
Is there any way i can initialize these from a loop?
for ( int i = 0; i< IDList.size() ; i++)
{
//Get Information from ID
btnDetails.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(),DetailActivity.class);
intent.putExtra("", IDList.get(i));
startActivity(intent);
}
});
//Add To Screen
}
In the code snippit IDList.get(i) is out of scope and a new Final Int isn't checked until the button is clicked, also going out of scope.
Is there any other was i can send the variable on click?
You can a inner class that implements OnClickListener and takes as parameter the id. For instance
private class MyOnClickListener implements OnClickListener {
private final int mId;
public MyOnClickListener(int id) {
mId = id;
}
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("", mId);
startActivity(intent);
}
}
for ( int i = 0; i< IDList.size() ; i++) {
btnDetails.setOnClickListener(new MyOnClickListener(IDList.get(i)));
}

cannot be resolved or is not a field with some EditTexts

Ok so i have the following situation : I create some Editexts dynamically and i want to add another row of Editexts when one of the EditTexts from the last row is clicked.
I tried doing it the following way :
When the last row of EditTexts is created,i assign each of them an id
et.setId(997);
et.setId(998);
et.setId(999);
I declared each of them ;
public EditText camp1;
public EditText camp2;
public EditText camp3;
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
And when i try to do this
case R.id.camp1:
inside a switch i get "camp1 cannot be resolved or is not a field"
What am i doing wrong ?
Is there a better way to detect when the last Edittext is clicked and create a new one ?
EDIT:
public class MainActivity extends Activity implements OnClickListener,
TextWatcher {
public Button paginanoua;
// public Button calculeaza;
public Button produsnou;
public EditText camp1;
public EditText camp2;
public EditText camp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
produsnou();
paginanoua = (Button) findViewById(R.id.paginanoua);
// calculeaza = (Button) findViewById(R.id.calculeaza);
produsnou = (Button) findViewById(R.id.produsnou);
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
paginanoua.setOnClickListener(this);
// calculeaza.setOnClickListener(this);
produsnou.setOnClickListener(this);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
}
public void onClick(View view) {
switch(view.getId())
{
case R.id.paginanoua:
ShowDialog();
case R.id.produsnou:
produsnou();
case R.id.997:///error
produsnou();
}
}
private void ShowDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Pagina noua..");
dialogBuilder.setMessage("Sigur doriti o pagina noua?");
dialogBuilder.setPositiveButton("Da",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Am inceput o lista noua", Toast.LENGTH_SHORT)
.show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
dialogBuilder.setNegativeButton("Nu",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Ramanem la lista curenta", Toast.LENGTH_SHORT)
.show();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
List<EditText> allpret = new ArrayList<EditText>();
List<EditText> allcant = new ArrayList<EditText>();
List<Float> alltotal = new ArrayList<Float>();
float totaltest = 0;
public void produsnou() {
LinearLayout l1 = (LinearLayout) findViewById(R.id.layout1);
EditText et = new EditText(this);
et.setHint("Produs");
l1.addView(et);
et.addTextChangedListener(this);
et.setId(997);
LinearLayout l2 = (LinearLayout) findViewById(R.id.layout2);
EditText et2 = new EditText(this);
et2.setHint("Cantitate");
et2.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
et2.setId(998);
allcant.add(et2);
l2.addView(et2);
et2.addTextChangedListener(this);
LinearLayout l3 = (LinearLayout) findViewById(R.id.layout3);
EditText et3 = new EditText(this);
et3.setHint("Pret");
et3.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l3.addView(et3);
et3.setId(999);
allpret.add(et3);
et3.addTextChangedListener(this);
}
float temp = 0;
public void calculeaza() {
totaltest = 0;
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
}
String[] pret = new String[allcant.size()];
for (int k = 0; k < allpret.size(); k++) {
pret[k] = allpret.get(k).getText().toString();
if (pret[k].matches("")) {
Toast.makeText(this,
"Ati omis pretul de pe pozitia " + (k + 1),
Toast.LENGTH_SHORT).show();
pret[k] = Float.toString(0);
}
}
for (int l = 0; l < allpret.size(); l++) {
Float temp = Float.parseFloat(cant[l]) * Float.parseFloat(pret[l]);
alltotal.add(temp);
totaltest = totaltest + temp;
// totaluri[l] = temp ; }
TextView totalf = (TextView) findViewById(R.id.total);
totalf.setText(String.format("Total: %.2f", totaltest));
}
}
// Float[] totaluri = new Float[allcant.size()];
public void reload(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
calculeaza();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
calculeaza();
}
}
All you care about is the last editText, right? Just give the last editText an onClickListener that creates another editText. Then give the new editText the onClickListener and remove it from the the previous "last one".
like this:
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(new myListener());
...
//put this private class in the same activity as the stuff above
private class myListener implements View.OnClickListener {
#Override
public void onClick(View view) {
EditText editText = new EditText(YourActivityName.this);
editText.setOnClickListener(new myListener());
//TODO put it in your viewGroup
//Give the old EditText your standard onClickListener
view.setOnClickListener(YourActivityName.this);
//To change body of implemented methods use File | Settings | File Templates.
}
}
setId() does not add any variables to the R.id class because setId() executes at run-time, but R is generated at compile-time. Since you are creating dynamic views, you need to rethink your onClick() method. You might want to consider using a ListView to help you. You can also set up the three TextViews using a separate XML file, such as row.xml.

Way of setting of onClickListener()

I created a ImageView object(img) and pass some resources through the same object(img) to a Linear Layout with a for-loop. On each Iteration of the loop I invoke a setOnClickListener() on img(img.setOnClickListener()) to show a Toast that reflects the value of the loop controller variable (i). The code segment i tried is below:
for (i = 1; i <= 6; i++)
{
img = new ImageView(this);
img.setImageResource(R.drawable.thambu);
body.addView(img);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(Details.this, Integer.toString(i) , Toast.LENGTH_LONG).show();
}
});
}
The thing is whenever i click on the Images that is generated, i have a Toast displaying 7.
I know why its displaying 7. but i want to display the index of the image that is being clicked.
(body is the id of a linear layout on which i pass an ImageView)
How can i do that on android. Thanks in advance.
for (i = 1; i <= 6; i++)
{
img = new ImageView(this);
img.setImageResource(R.drawable.thambu);
body.addView(img);
img.setTag(i);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int tagInt = (int) v.getTag();
Toast.makeText(Details.this, Integer.toString(tagInt) , Toast.LENGTH_LONG).show();
}
});
}
try this, i have used tags..
Actually, it's rather a general Java question.
You should do something like the following:
for (int i = 1; i <= 6; i++) {
img = new ImageView(this);
img.setImageResource(R.drawable.thambu);
body.addView(img);
final int j = i;
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(Details.this, Integer.toString(j) , Toast.LENGTH_LONG).show();
}
});
}

Categories