Java Android-将方法从MainActivity调用为片段

Java Android-将方法从MainActivity调用为片段,java,android,database,android-fragments,android-activity,Java,Android,Database,Android Fragments,Android Activity,我遇到了一个问题,我试图在我的主要活动中调用一个方法,该方法通过单击我的片段的按钮将我的数据保存到数据库中。问题是,我不确定该将什么放在方法的括号中 这是我的主要活动课 import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.support.design.widg

我遇到了一个问题,我试图在我的主要活动中调用一个方法,该方法通过单击我的片段的按钮将我的数据保存到数据库中。问题是,我不确定该将什么放在方法的括号中

这是我的主要活动课

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
这是我的片段类

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

这个问题发生在onCreateView方法
MainActivity MainActivity=((MainActivity)getActivity())的fragment类中

如果您没有在XML小部件中使用android:onClick=“addScoutInfo”方法,您可以删除addScoutInfo方法上的参数。否则,您必须传递已触发的视图,例如您的btn\u add\u scout\u info按钮。

如果您没有在XML小部件中使用android:onClick=“addScoutInfo”方法,您可以删除addScoutInfo方法上的参数。否则,您必须传递已触发的视图,例如您的btn_添加_scout_信息按钮。

addScoutInfo
函数参数未在该函数中使用,因此您可以传递null或删除该参数。这将使您的代码正常工作,但是将
getActivity()
的结果强制转换为特定类型通常是一个不好的想法。该片段可以在将来被其他活动重用,该转换将不再工作

以下是一些可以改进代码的建议:

  • 让片段管理自己的视图
  • 将DB保存逻辑移到片段中
  • 使用本地的、某种类型的或通过向片段传递

  • addScoutInfo
    函数参数未在该函数中使用,因此您可以传递null或删除该参数。这将使您的代码正常工作,但是将
    getActivity()
    的结果强制转换为特定类型通常是一个不好的想法。该片段可以在将来被其他活动重用,该转换将不再工作

    以下是一些可以改进代码的建议:

  • 让片段管理自己的视图
  • 将DB保存逻辑移到片段中
  • 使用本地的、某种类型的或通过向片段传递

  • 在片段中的onbind()方法上,添加侦听器并在主活动类中实现它,这样您就可以从片段调用此方法到活动。更多信息请点击此处:


    在片段中的onbind()方法上,添加侦听器并在主活动类中实现它,这样您就可以从片段调用此方法到活动。更多信息请点击此处:


    这是您的代码吗?我查看了
    public void addScoutInfo(视图视图)
    ,函数中根本没有使用
    视图。你可以传递任何东西,因为它对它没有任何作用。让我澄清一下,你的片段中有一个按钮,当你点击该按钮时,数据将保存到db,对吗?如果我是正确的,这是一个活动和片段通信的问题,您最好参考以下内容:@Elye布局中的
    android:onClick
    需要该参数,这是您的代码吗?我查看了
    public void addScoutInfo(视图视图)
    ,函数中根本没有使用
    视图。你可以传递任何东西,因为它对它没有任何作用。让我澄清一下,你的片段中有一个按钮,当你点击该按钮时,数据将保存到db,对吗?如果我是正确的,这是一个活动和片段通信的问题,您最好参考以下内容:@Elye该参数是布局xml中的
    android:onClick
    所需的。如果我这样做,我如何使用
    Context=this
    getBaseContext()
    在片段中?您可以这样做:
    databaseHelper=newdatabasehelper(getContext())如果您使用的是支持库22+或
    databaseHelper=newdatabasehelper(getActivity())
    otherwise获取另一个错误,这次当我输入数据时,我的数据库崩溃了如果我这样做,我如何使用
    Context=this
    getBaseContext()
    在片段中?您可以这样做:
    databaseHelper=newdatabasehelper(getContext())如果您使用的是支持库22+或
    databaseHelper=newdatabasehelper(getActivity())
    otherwise获取另一个错误,这一次,如果此方法是通过XML
    android:onClick设置的,则当我输入数据时,我的数据库崩溃。如果此方法是通过XML
    android:onClick
    设置的,则需要该参数。这个参数是必需的