1

I'm having an issue to where I'm trying to call a method in my main activity which saves my data to a database on a button click to my fragment. The issue is that I am unsure of what to put in the brackets of the method.

Here is my main activity class

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    NavigationView navigationView = null;
    Toolbar toolbar = null;
    DatabaseHelper myDB;
    EditText tNumber, tPoticullis, tChevalFrise, tMoat, tRamparts, tDrawbridge, tSallyPort, tRockWall, tRockTerrain, tLowBar;
    Context context = this;
    DatabaseHelper databaseHelper;
    SQLiteDatabase sqLiteDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Create database
        myDB = new DatabaseHelper(this);

        //Instantiate all editText objects
        tNumber = (EditText) findViewById(R.id.editNumber);
        tPoticullis = (EditText) findViewById(R.id.editPoticullis);
        tChevalFrise = (EditText) findViewById(R.id.editChevalFrise);
        tMoat = (EditText) findViewById(R.id.editMoat);
        tRamparts = (EditText) findViewById(R.id.editRamparts);
        tDrawbridge = (EditText) findViewById(R.id.editDrawbridge);
        tSallyPort = (EditText) findViewById(R.id.editSallyPort);
        tRockWall = (EditText) findViewById(R.id.editRockWall);
        tRockTerrain = (EditText) findViewById(R.id.editRockTerrain);
        tLowBar = (EditText) findViewById(R.id.editLowBar);

        //Set the fragment initially
        WelcomeFragment fragment = new WelcomeFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);

        //How to change elements in the header programatically
        View headerView = navigationView.getHeaderView(0);
        TextView emailText = (TextView) headerView.findViewById(R.id.description);
        emailText.setText("Scouting Application");

        navigationView.setNavigationItemSelectedListener(this);
    } //End of onCreate

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        } //End of if statement
    } //End of onBackPressed

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    } //End of onCreateOptionsMenu

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        } //End of if statement

        return super.onOptionsItemSelected(item);
    } //End of onOptionsItemSelected

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_welcome) {
            //Set the fragment initially
            WelcomeFragment fragment = new WelcomeFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
            // Handle the camera action
        }
        else if (id == R.id.nav_facebook) {
            FacebookFragment fragment = new FacebookFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
        else if (id == R.id.nav_members) {
            //Set the fragment initially
            MembersFragment fragment = new MembersFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
        else if (id == R.id.nav_robot) {

        }
        else if (id == R.id.nav_scout) {
            //Set the fragment initially
            ScoutFragment fragment = new ScoutFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
        else if (id == R.id.nav_match) {
            //Set the fragment initially
            MatchFragment fragment = new MatchFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        } //End of if statement

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    } //End of onNavigationItemSelected

    public void addScoutInfo(View view){
        //Converts all editText values into strings
        String sNumber = tNumber.getText().toString();
        String sPoticullis = tPoticullis.getText().toString();
        String sChevalFrise = tChevalFrise.getText().toString();
        String sMoat = tMoat.getText().toString();
        String sRamparts = tRamparts.getText().toString();
        String sDrawbridge = tDrawbridge.getText().toString();
        String sSallyPort = tSallyPort.getText().toString();
        String sRockWall = tRockWall.getText().toString();
        String sRockTerrain = tRockTerrain.getText().toString();
        String sLowBar = tLowBar.getText().toString();

        //Saves data
        databaseHelper = new DatabaseHelper(context);
        sqLiteDatabase = databaseHelper.getWritableDatabase();
        databaseHelper.addInformation(sNumber, sPoticullis, sChevalFrise, sMoat, sRamparts, sDrawbridge, sSallyPort, sRockWall,
                sRockTerrain, sLowBar, sqLiteDatabase);
        Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
        databaseHelper.close();
    } //End of addScoutInfo
} //End of class

Here is my Fragment class

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A simple {@link Fragment} subclass.
 */
public class AddScoutDataFragment extends Fragment {

    Button cancelButton;
    Button addDataButton;

    public AddScoutDataFragment() {
        // Required empty public constructor
    } //End of AddScoutDataFragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_add_scout_data, container, false);
        view.setBackgroundColor(Color.WHITE);

        //Adds data to ScoutFragment
        addDataButton = (Button) view.findViewById(R.id.buttonDataAdd);
        addDataButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //Saves data to database
                MainActivity mainActivity = ((MainActivity)getActivity()).addScoutInfo();
                //Returns to ScoutFragment
                ScoutFragment fragment = new ScoutFragment();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.commit();
            } //End of onClick
        }); //End of setOnClickListener

        //Returns to ScoutFragment without adding any data
        cancelButton = (Button) view.findViewById(R.id.buttonCancel);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Returns to ScoutFragment
                ScoutFragment fragment = new ScoutFragment();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.commit();
            } //End of onClick
        }); //End of setOnClickListener
        // Inflates the layout for this fragment
        return view;
    } //End of onCreateView
} //End of class

The issue happens in the fragment class in the onCreateView method MainActivity mainActivity = ((MainActivity)getActivity()).addScoutInfo(Need to insert something here);

Samer Alabi
  • 117
  • 1
  • 10
  • 1
    Is this your code? I look at `public void addScoutInfo(View view)`, the `view` is not being used in the function at all. You could pass in anything as it does nothing with it. – Elye Mar 16 '16 at 01:05
  • let me clarify, you have a button in **your fragment**, when you click that button data will be saved to db, right? – hehe Mar 16 '16 at 01:29
  • If I'm correct it is a problem of activity and fragment communication and you better refer to this :http://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices – hehe Mar 16 '16 at 01:36
  • @Elye That parameter is needed by `android:onClick` in the layout XML – OneCricketeer Mar 16 '16 at 02:27

3 Answers3

1

addScoutInfo function parameter is not used in that function, so you can just pass null or remove the parameter. That will make your code work BUT it is generally a bad idea to cast the result of getActivity() to a specific type. The fragment can be reused by other activity in future and that cast will no longer work.

Here are a few suggestions that can improve your code:

  1. Make the fragment manage its own views,
  2. Move the DB saving logic into the fragment,
  3. Communicate from fragment to activity using either local Broadcast Receivers , some kind of Event bus or by passing a callback to the fragment.
arsent
  • 6,975
  • 3
  • 32
  • 31
  • If I do that, how to do I use `Context context = this;` and `getBaseContext()` in the fragment? – Samer Alabi Mar 16 '16 at 02:25
  • You can do this: `databaseHelper = new DatabaseHelper(getContext());` if you are using support library 22+ or `databaseHelper = new DatabaseHelper(getActivity());` otherwise – arsent Mar 16 '16 at 02:27
  • Getting another error, this time my database crashed when I enter data – Samer Alabi Mar 16 '16 at 04:18
0

In the fragment, on the onbind() method, add the listener and implement it in the Main Activity class, this way you can call this method from the fragment to the activity. More information here:

http://developer.android.com/training/basics/fragments/communicating.html

Isaac Urbina
  • 1,295
  • 11
  • 21
-1

If in case you are NOT using android:onClick="addScoutInfo" method in widget in XML, you can just remove the parameters on your addScoutInfo method. Else, you must pass the view that has been triggered, say for example your btn_add_scout_info button.

shibapoo
  • 1,909
  • 3
  • 16
  • 22