从Activity发送和接收数据到另一个扩展片段

时间:2017-10-16 10:07:54

标签: java android android-fragments

我无法从扩展AppCompatActivity并在扩展片段类的Activity中接收它的Activity发送数据。问题是我不能在接收类中扩展AppCompatActivity,因为我正在使用包含动画图表的java库,并且需要扩展该片段类,以便活动识别某些方法....我使用了调试器并且似乎数据已成功添加到捆绑包中,但捆绑包在接收端返回null。 (以下代码)

发送活动:

public class CreateLine extends AppCompatActivity {

    DatabaseHelper myDb;
    Button dateButton, nextButton;
    TextView quantity, duration;
    Date date = new Date();
    String PackageType20 = "648 Shippers";
    String PackageType30 = "605 Shippers";
    int timeadded;
    private Spinner spinner, spinner2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_line);
        myDb = new DatabaseHelper(this);

        quantity = (TextView) findViewById(R.id.editText3);
        duration = (TextView) findViewById(R.id.durationtextView);
        dateButton = (Button) findViewById(R.id.angry_btn);
        nextButton = (Button) findViewById(R.id.Confirm_button);

        spinner = (Spinner) findViewById(R.id.spinner);

        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(com.almac.tracker.CreateLine.this,
                R.layout.spinner_layout, getResources().getStringArray(R.array.LineTypes));
        myAdapter.setDropDownViewResource(R.layout.spinner_layout);
        spinner.setAdapter(myAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position2, long l) {


                switch ((int) position2) {
                    case 0:
                        quantity.setText("");
                        ;
                        break;
                    case 1:
                        quantity.setVisibility(View.INVISIBLE);
                        timeadded = 10;
                        duration.setText(timeadded + " Hours");
                        spinner2.setVisibility(View.INVISIBLE);
                        break;
                    case 2:
                        quantity.setVisibility(View.INVISIBLE);
                        timeadded = 10;
                        duration.setText(timeadded + " Hours");
                        spinner2.setVisibility(View.INVISIBLE);
                        break;
                    case 3:
                        quantity.setVisibility(View.INVISIBLE);
                        timeadded = 10;
                        duration.setText(timeadded + " Hours");
                        spinner2.setVisibility(View.INVISIBLE);
                        break;
                    case 4:
                        quantity.setVisibility(View.VISIBLE);
                        duration.setText(timeadded + " Hours");
                        spinner2.setVisibility(View.VISIBLE);
                        Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
                        break;
                    case 5:
                        quantity.setVisibility(View.VISIBLE);
                        duration.setText(timeadded + " Hours");
                        spinner2.setVisibility(View.VISIBLE);
                        break;
                    case 6:
                        quantity.setVisibility(View.VISIBLE);
                        duration.setText(timeadded + " Hours");
                        spinner2.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;

                }
            }


            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        spinner2 = (Spinner) findViewById(R.id.spinner2);

        ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(com.almac.tracker.CreateLine.this,
                R.layout.spinner_layout, getResources().getStringArray(R.array.PackageTypes));
        myAdapter2.setDropDownViewResource(R.layout.spinner_layout);
        spinner2.setAdapter(myAdapter2);

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {


                switch (position) {
                    case 0:
                        quantity.setText("");
                        ;
                        break;
                    case 1:
                        quantity.setText(PackageType20);
                        timeadded = 28;
                        duration.setText(timeadded + " Hours");


                        break;
                    case 2:
                        quantity.setText(PackageType30);
                        timeadded = 27;
                        duration.setText(timeadded + " Hours");

                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        dateButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                dateButton.setText(date.toString());

                // Creates an instance of current DateTime which represents the
                // current date time.
                DateTime dateTime = new DateTime();
                DateTimeFormatter fmt = DateTimeFormat.forPattern("E d MMM yyyy" + "\n" + " h:mm a ");
                String formattedtime = fmt.print(dateTime);
                dateButton.setText(formattedtime);

                // Plus some hours, minutes, and seconds to the original DateTime.
                DateTimeFormatter fmt2 = DateTimeFormat.forPattern("E d MMM yyyy" + "\n" + " h:mm a ");

                DateTime dateTime1 = dateTime.plusHours(timeadded);
                String endtimecalc = fmt2.print(dateTime1);
                TextView endtime = findViewById(endtimetextView);
                endtime.setText(endtimecalc);

                String spinnerSelection = String.valueOf(spinner.getSelectedItem());
                String spinnerSelection2 = String.valueOf(spinner2.getSelectedItem());
                String q = quantity.getText().toString();
                String d = duration.getText().toString();

                //INSERT DATA TO DATABASE
                boolean isInserted = myDb.insertData(
                        spinnerSelection,
                        spinnerSelection2,
                        q,
                        d,
                        formattedtime,
                        endtimecalc);

                if (isInserted == true)
                    Toast.makeText(CreateLine.this, "Data Inserted Successfully", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(CreateLine.this, "Data not Inserted", Toast.LENGTH_LONG).show();

            }
        });


        nextButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                    Cursor res = myDb.getAllData();

                    StringBuffer buffer0 = new StringBuffer();
                    StringBuffer buffer1 = new StringBuffer();
                    StringBuffer buffer2 = new StringBuffer();
                    StringBuffer buffer3 = new StringBuffer();
                    StringBuffer buffer4 = new StringBuffer();
                    StringBuffer buffer5 = new StringBuffer();
                    StringBuffer buffer6 = new StringBuffer();


                    if ( res != null && res.moveToFirst()) {
                        do {

                            buffer0.setLength(0);
                            buffer1.setLength(0);
                            buffer2.setLength(0);
                            buffer3.setLength(0);
                            buffer4.setLength(0);
                            buffer5.setLength(0);
                            buffer6.setLength(0);

                            String getid = res.getString(0);
                            String getlt = res.getString(1);
                            String getpt = res.getString(2);
                            String getqty = res.getString(3);
                            String getdur = res.getString(4);
                            String getst = res.getString(5);
                            String getet = res.getString(6);

                            buffer0.append(getid);
                            buffer1.append(getlt);
                            buffer2.append(getpt);
                            buffer3.append(getqty);
                            buffer4.append(getdur);
                            buffer5.append(getst);
                            buffer6.append(getet);
                        } while (res.moveToNext());
                    }


                Fragment fragment = new Fragment();
                Bundle extras = new Bundle();

                extras.putString("ID", buffer0.toString());
                extras.putString("LineType", buffer1.toString());
                extras.putString("PackageType", buffer2.toString());
                extras.putString("Quantity", buffer3.toString());
                extras.putString("Duration", buffer4.toString());
                extras.putString("Starttime",buffer5.toString());
                extras.putString("endtime", buffer6.toString());
                fragment.setArguments(extras);



                setContentView(R.layout.line_details);
                SamplerAdapter samplesAdapter = new SamplerAdapter(getSupportFragmentManager());
                ViewPager samplesPager = (ViewPager) findViewById(R.id.samplesPager);
                samplesPager.setAdapter(samplesAdapter);


            }
        });
    }
 }

接收活动:

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View myInflatedView = inflater.inflate(R.layout.line_details, container, false);

    Bundle extras = this.getArguments();
    if (extras != null) {

        String id = extras.getString("ID");
        String linetype = extras.getString("LineType");
        String packagetype = extras.getString("PackageType");
        String Quantity = extras.getString("Quantity");
        String Duration = extras.getString("Duration");
        String Starttime = extras.getString("Starttime");
        String endtime = extras.getString("endtime");

        TextView LT = (TextView) getView().findViewById(R.id.textViewLT);
        TextView PT = (TextView) getView().findViewById(R.id.textViewPT);
        TextView QTY = (TextView) getView().findViewById(R.id.textViewQTY);
        TextView DUR = (TextView) getView().findViewById(R.id.textViewDUR);
        TextView ST = (TextView) getView().findViewById(R.id.textViewST);
        TextView ET = (TextView) getView().findViewById(R.id.textViewET);

        LT.setText(linetype);
        PT.setText(packagetype);
        QTY.setText(Quantity);
        DUR.setText(Duration);
        ST.setText(Starttime);
        ET.setText(endtime);
    }

    return myInflatedView;
}

SAMPLERADAPTER CODE(使用getitem方法):

public class SamplerAdapter extends FragmentStatePagerAdapter {
private final int mCount = 10;
private Bundle extras;
Fragment fragment = new Fragment();

public SamplerAdapter(FragmentManager fm, Bundle extras) {
    super(fm);
    this.extras = extras;
}

@Override
public int getCount() {
    return mCount;
}

@Override
public Fragment getItem(int position) {
    fragment.setArguments(extras);
    return fragment;
}

@Override
public void finishUpdate(ViewGroup container) {
    super.finishUpdate(container);
}

}

任何人都可以附加我的代码,以便它接收数据并将其显示到我指定的文本框中。

任何帮助都会很棒,谢谢。

4 个答案:

答案 0 :(得分:1)

更改适配器构造函数以接收Bundle 将附加内容传递给构造函数,如

SamplerAdapter samplesAdapter = new SamplerAdapter(getSupportFragmentManager(), extras);

在SamplerAdapter类中为bundle

创建一个全局变量
private Bundle extras;

public SamplerAdapter(FragmentManager fm, Bundle extras){
   super(fm);
   this.extras = extras;
}

// Now set these arguments in getItem method
    @Override
    public Fragment getItem(int position) {
        // Create your fragment set arguments in that fragment
        Fragment fragment = new LineDetails();
        fragment.setArguments(bundle);
        return fragment;
    }

答案 1 :(得分:0)

首先,您无法在发送活动时创建片段。您必须在接收活动中创建它,以便实现所需的片段。

然后,要从发送活动到接收活动进行通信,您必须发送意图。 把你的包放在这个意图中。 在接收活动时,您可以调用getIntent()。getExtras()来获取您的包。 实现你的片段并像你一样给它捆绑。

另一件事,你的while循环是&#34;怪异的&#34;。如果您已经知道您将获得一行结果,请不要创建循环并且不要使用Stringbuilder。如果你可以有几行,不要在每个循环中重置StringBuilder的长度,因为它会覆盖每个新行的先前数据。

答案 2 :(得分:0)

从活动中您按意图发送数据:

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

并在Fragment onCreateView方法中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

答案 3 :(得分:0)

有时您可以在活动中收到Intent,并且需要将信息传递给您的工作片段。如果您需要启动片段,但如果它仍然有效,则给定答案是正常的,setArguments()不是很有用。如果传递的信息将导致与您的UI交互,则会出现另一个问题。在这种情况下,你不能调用类似myfragment.passData()的东西,因为android会很快告诉只有创建视图的线程才能与之交互。