Pass various objects to a Class

I'm programming a layout in Android and it is quite dynamic. Since I'm also working with databases, I decided to split it into various classes, meaning that I have several "set up" classes. This, though, leads me to pass almost all layout elements to the classes when calling them. What I want to know is if there's a way to wrap them up in a single Bundle-like argument, so the code doesn't get too messy. An example of the coding:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_materialtab);
    final Spinner spnMaterial = (Spinner) findViewById(R.id.mat_spn_material);
    final EditText nome = (EditText) findViewById(R.id.mat_frm_nome);
    final EditText modE = (EditText) findViewById(R.id.mat_frm_elasticidade);
    final EditText dVol = (EditText) findViewById(R.id.mat_frm_densidade);
    final ImageButton atMaterial = (ImageButton) findViewById(R.id.mat_btm_atualizar);
    final ImageButton addMaterial = (ImageButton) findViewById(R.id.mat_btm_add);
    final ImageButton excMaterial = (ImageButton) findViewById(R.id.mat_btm_exc);
    createSpinner(nome, modE, dVol, spnMaterial, atMaterial, excMaterial, 0);
    createAddMaterial(nome, modE, dVol, spnMaterial, addMaterial, atMaterial, excMaterial);
    createAtMaterial(nome, modE, dVol, spnMaterial, atMaterial, excMaterial);
    createExcMaterial(nome, modE, dVol, spnMaterial, atMaterial, excMaterial);

}

public void createSpinner(final EditText nome, final EditText modE, final EditText dVol, final Spinner spnMaterial, final ImageButton atMaterial, final ImageButton excMaterial, final int position) {

    final SQLiteDatabase Estrutura = openOrCreateDatabase("Estrutura.db", getBaseContext().MODE_PRIVATE, null);
    final Cursor linha = Estrutura.rawQuery("SELECT * FROM MATERIAIS", null);
    String[] from = {"_id","nome","modE","dVol"};
    int[] to = {R.id.mat_lay_txvid,R.id.mat_lay_txvnome,R.id.mat_lay_txvmodE,R.id.mat_lay_txvdVol};
    SimpleCursorAdapter adp = new SimpleCursorAdapter(getBaseContext(), R.layout.sp_material, linha, from, to, 0);
    spnMaterial.setAdapter(adp);
    spnMaterial.setSelection(position);
    spnMaterial.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            linha.moveToPosition(position);
            nome.setText(linha.getString(1));
            modE.setText(String.valueOf(linha.getDouble(2)));
            dVol.setText(String.valueOf(linha.getDouble(3)));
            if(position == 0) {isEnabled(false, nome, modE, dVol, atMaterial, excMaterial);} else
                              {isEnabled(true, nome, modE, dVol, atMaterial, excMaterial);}
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {}
    });
}

public void createAddMaterial(final EditText nome, final EditText modE, final EditText dVol, final Spinner spnMaterial,final ImageButton addMaterial, final ImageButton atMaterial, final ImageButton excMaterial) {
    final SQLiteDatabase Estrutura = openOrCreateDatabase("Estrutura.db", getBaseContext().MODE_PRIVATE, null);

    addMaterial.setOnClickListener(new OnClickListener() {  
        @Override
        public void onClick(View v) {
            String sql = "INSERT INTO MATERIAIS(nome,modE,dVol) VALUES('Nome',0,0)";
            Estrutura.execSQL(sql);
            createSpinner(nome, modE, dVol, spnMaterial, atMaterial, excMaterial, spnMaterial.getAdapter().getCount());
        }
    });
}

public void createAtMaterial(final EditText nome, final EditText modE, final EditText dVol, final Spinner spnMaterial, final ImageButton atMaterial, final ImageButton excMaterial) {
    final SQLiteDatabase Estrutura = openOrCreateDatabase("Estrutura.db", getBaseContext().MODE_PRIVATE, null);

    atMaterial.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            StringBuilder sql = new StringBuilder();
            sql.append("UPDATE MATERIAIS SET ");
            sql.append("nome = '"+nome.getText().toString()+"', ");
            sql.append("modE = "+modE.getText().toString()+" , ");
            sql.append("dVol = "+dVol.getText().toString()+" ");
            sql.append("WHERE _id = "+spnMaterial.getSelectedItemId());
            Estrutura.execSQL(sql.toString());
            createSpinner(nome, modE, dVol, spnMaterial, atMaterial, excMaterial, spnMaterial.getSelectedItemPosition());
        }
    });
}

public void createExcMaterial(final EditText nome, final EditText modE, final EditText dVol, final Spinner spnMaterial, final ImageButton atMaterial, final ImageButton excMaterial) {
    final SQLiteDatabase Estrutura = openOrCreateDatabase("Estrutura.db", getBaseContext().MODE_PRIVATE, null);

    excMaterial.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String sql = "DELETE FROM MATERIAIS WHERE _id = "+spnMaterial.getSelectedItemId();
            Estrutura.execSQL(sql);
            if(spnMaterial.getSelectedItemPosition() == spnMaterial.getAdapter().getCount()-1) {
                createSpinner(nome, modE, dVol, spnMaterial, atMaterial, excMaterial, spnMaterial.getSelectedItemPosition()-1);} else {
                createSpinner(nome, modE, dVol, spnMaterial, atMaterial, excMaterial, spnMaterial.getSelectedItemPosition());   }
        }
    });
}

public void isEnabled(boolean is, EditText nome, EditText modE, EditText dVol, ImageButton atMaterial, ImageButton excMaterial) {
    nome.setEnabled(is);
    modE.setEnabled(is);
    dVol.setEnabled(is);
    atMaterial.setEnabled(is);
    excMaterial.setEnabled(is);
}

}

As you can see, the classes receive quite a lot of arguments, and I wanted to make it look better. Since they have different types, Im not sure if arrays would be the best way to do this.

Upvotes: 0

Views: 59

Answers (1)

Caleb
Caleb

Reputation: 1706

Short answer: No. You cannot put Views directly in a bundle and I don't recommend it. You can only pass Serializable or Parcelable objects via bundles. Trying to serialize a View and then retrieve it later will cause issues if the view's context has been destroyed or corrupted since the time you put in the bundle. You don't want to find yourself with random crashes due to the Garbage Collector cleaning up your views without your consent. If you are trying to edit the same View object from two different Contexts, you'll face difficulty.

I have several "set up" classes

Are these setup classes just plain POJO's that you can obtain references to? Then just pass it like a normal parameter.(as it looks like you are doing in your example)

Manipulator manipulator = new ();
manipulator.createAddMaterial(customView1, customView2, material1, ...)

What I want to know is if there's a way to wrap them up in a single Bundle-like argument

If you really need to pass a view to another Activity (essentially another context), your best bet will be to extract the relevant data from the view and pass only that.

MyViewData myViewData = new MyViewData();
myViewData.setText(view.getText());
myViewData.setMaterial(view.getMaterial());
Intent i = new Intent(this, NextActivity.class);
intent.putExtra(MY_VIEW_DATA, myViewData);
startActivity(intent);

Then you can receive it in the other activity and you'll have the relevant data you need.

What I want to know is if there's a way to wrap them up in a single Bundle-like argument, so the code doesn't get too messy.

If you want to keep it clean, then create an 'overlord' object that would hold all of the relevant data about your views. It could function similar to a Map so you could retrieve information about a specific view. In this case, the "value" of the map would be a MyViewData object. This overlord object could be bundled into the Intent cleanly.

eg.

MyViewOverlord mvo = new MyViewOverlord();
mvo.saveDataForView("key1", myViewData1);
mvo.saveDataforView("key2" myViewData2);
intent.putExtra("ViewOverlord", mvo);

(You can see the answers to a similar question here: How can i pass image view between activities in android)

Upvotes: 1

Related Questions