将字符串数据从Activity发送到片段

时间:2016-09-29 12:28:29

标签: java android sqlite fragment android-sqlite

您好我想将一个字符串从Activity(MainActivity.java)发送到Fragment(Tozihat.java)并设置为TextView,但它会出错。 我已经检查了其他主题,但我无法找到问题的解决方案。

代码来自数据库Methode我写了id + 1,因为listView的第一个项目位置是0,但第一个id是1:

    public String Tozihat(int id) {
    int id2 = id + 1;
    String query = "SELECT Tozihat FROM tbl_mive WHERE ID ="+id2;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(query , null);
    String t;
    cursor.moveToFirst();
    t = cursor.getString(0);

    return t;
}
来自我的MainActivity.Java的

代码

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            Intent intent = new Intent(MainActivity.this , ClickActivity.class);

            String t = myDbHelper.Tozihat(position);
            Bundle bundle=new Bundle();
            Tozihat tozihat = new Tozihat();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.textViewTozihat , tozihat, null);
            bundle.putString("Tozihat", t );
            tozihat.setArguments(bundle);
            fragmentTransaction.commit();

            startActivity(intent);

        }
    });
来自我的Faragment(Tozihat.java)的代码

public class Tozihat extends Fragment{

TextView textViewTozihat;
DataBaseHelper myDbHelper;
String Tozihat;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.fragment_tozihat, container, false);



    myDbHelper = new DataBaseHelper(getActivity());

    textViewTozihat = (TextView) view.findViewById(R.id.textViewTozihat);

    Tozihat = getArguments().getString("Tozihat");

    textViewTozihat.setText(Tozihat);

    return view;

}

请帮助我!

1 个答案:

答案 0 :(得分:1)

在活动中的listview itemclick listner中添加以下代码:

 Tozihat gTozihat  = new Tozihat().newInstance("Data");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.textViewTozihat, gTozihat).commit();

在片段内:

 private static final String TYPE = "DATA_KEY";
public static  Tozihat newInstance(String type) {
         Tozihat fragment = new  Tozihat();
        Bundle args = new Bundle();
        args.putString(TYPE, type);

        fragment.setArguments(args);
        return fragment;
    }