Search code examples
androidandroid-intentwhile-loopfinal

Passing int value, .putExtra, loop


I need to pass int value i to other class, because it's the id from a database, but it doesn't allow me to pass the int value using .putExtra, because the value needs to be int, but if I declare that value as final then it can't change anymore for the loop.. Help, thanks.

final int x = DataBaseHelper.getLastId();
        int i = 0;

        final TextView[] textViews = new TextView[x];

        while (i < x) {
            TextView newTextView = new TextView(this);
            newTextView.setText(DataBaseHelper.getTitleNow(i + 1) + " \n");
            newTextView.setInputType(newTextView.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
            newTextView.setLayoutParams(new LayoutParams((LayoutParams.WRAP_CONTENT), ViewGroup.LayoutParams.WRAP_CONTENT));
            newTextView.setClickable(true);
            newTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(HistoryActivity.this, MainActivity.class);
                    intent.putExtra("ID", i);
                    startActivity(intent);
                    finish();
                }
            });
            ll.addView(newTextView, layoutParams); 
            textViews[i] = newTextView;
            i++;
        }

Solution

  • Declare i as a member variable and you can use it in your onClick()

    public class HistoryActivity extends Activity
    {
        int i;
    
        public void onCreate(...)
    {
       ...
    }
    
    final int x = DataBaseHelper.getLastId();  //not sure where all of this code is but take off the int type here
        i = 0;
    
        final TextView[] textViews = new TextView[x];
    
        while (i < x) {
    

    Just declare it outside of a function (usually right after the class definition) then it is available everywhere within the Activity

    You also could use another variable within the loop to assign to i as a final variable

     while (i < x) {
            final int j = i;  // use new variable here 
            TextView newTextView = new TextView(this);
           ...
            newTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(HistoryActivity.this, MainActivity.class);
                    intent.putExtra("ID", j);  // use newly defined variable
                    startActivity(intent);