Reza4000 Reza4000 - 2 months ago 5
Android Question

send string data from Activity to fragment

Hello i want to send a string from Activity (MainActivity.java) to the to the Fragment (Tozihat.java) and set to the a TextView but it gives an error.
i have checked other topics but i can't find solution of my problem.

code From Database Methode i write id + 1 because the first item position from listView is 0 but the first id is 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;
}


code from my 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);

}
});


code from my 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;

}


please help me!

Answer

Add below code inside listview itemclick listner in activity:

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

Inside your Fragment :

 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;
    }
Comments