3

I am created two fragments name are Frag_A and Frag_B. In Frag_A I display all data in listview. and also having update button. In Frag_B having Edit text and save button. Firstly when user select one item from list view and then click upadate. when click on update Frag_A is replace by Frag_B and Display the selected item from selected List View in edit text and user make changes and save.How to achive this demo? Thanks in advance.

My DatabaseAdapter file is DBAdapter.java file

package com.dlcpl.insert_view;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {

    public static final String KEY_TEXT="text";
    public static final String TAG="DBAdapter";

    public static final String DATABASE_NAME="taskmanager.db";
    public static final String DATABAS_TABLE="text_table";
    public static final int DATABASE_VERSION=1;

    public static final String DATABASE_CREATE="create table "+DATABAS_TABLE+"("+KEY_TEXT+" varchar(500) not null);";
    public final Context context;
    public DatabaseHelper DBHelper;
    public SQLiteDatabase db;

    public DBAdapter(Context ctx)
    {
        this.context=ctx;
        DBHelper=new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        public DatabaseHelper(Context context)
        {
            super(context,DATABASE_NAME,null,DATABASE_VERSION );
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            try
            {
                db.execSQL(DATABASE_CREATE);
            }
            catch(SQLException e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG,"Upgrading database from version"+oldVersion+"to"+newVersion+",which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS text_table");
            onCreate(db);
        }
    }

    //---opens the database---
    public DBAdapter open() throws SQLException
    {
        db=DBHelper.getWritableDatabase();
        return this;
    }

    //---close the database---
    public void close()
    {
        DBHelper.close();
    }

    //---insert a text into the database---
    public long insertText(String text)
    {
        ContentValues initialValues=new ContentValues();
        initialValues.put(KEY_TEXT, text);
        return db.insert(DATABAS_TABLE, null, initialValues);
    }

    //---delete a particular contact---
    public boolean deleteContact(String text)
    {
        return db.delete(DATABAS_TABLE, KEY_TEXT + "=" + text, null) > 0;
    }

    //---retrieves all the text
    /*public Cursor getAlltext()
    {
        return db.query(DATABAS_TABLE, new String[] {KEY_TEXT}, null, null, null, null, null);
    }*/

    public List<String[]> getAlltext()
    {

        List<String[]> list = new ArrayList<String[]>();
        Cursor cursor = db.query(DATABAS_TABLE, new String[] {KEY_TEXT}, null, null, null, null, null); 

        int x=0;
        if (cursor.moveToFirst()) {
            do {
                String[] b1=new String[]{cursor.getString(0)};

                list.add(b1);

                x=x+1;
            } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        } 
        cursor.close();

        return list;
    }

    //---retrieves a particular contact---
    public Cursor gettext(String string) throws SQLException
    {
        Cursor mCursor= db.query(true, DATABAS_TABLE, new String[] {KEY_TEXT}, KEY_TEXT + "=" + string, null, null, null, null, null);      

        if(mCursor !=null)
        {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //---updates a text_table---
    public boolean updateContact(String text)
    {
        ContentValues args=new ContentValues();
        args.put(KEY_TEXT, text);
        return db.update(DATABAS_TABLE, args, KEY_TEXT + "=" + text, null) > 0;
    }

}

my Frag_A File is View_Data.java

package com.dlcpl.insert_view;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
//import android.widget.Toast;
import android.app.ListFragment;
import android.graphics.Color;
public class View_Data extends ListFragment
{
     public static final String ROW_ID = "row_id";
     ListView listView;
    TextView selection;
    TextView label1;
    public int idToModify; 
    List<String[]> list = new ArrayList<String[]>();
    List<String[]> names2 =null ;
    String[] stg1;  
    EditText A_input;
    @Override
    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState) {

         return inflater.inflate(R.layout.view_data, container, false);
    }   

    @Override
    public void onStart()
    {
        super.onStart();
    DBAdapter dbAdapter =new DBAdapter(getActivity());
        dbAdapter.open();       
         names2 = dbAdapter.getAlltext();
         stg1=new String[names2.size()];
         int x=0;
            String stg;

            for (String[] name : names2) {
                stg = name[0];

                stg1[x]=stg;
                x++;
            }
         setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, stg1));


         Button btnLoad = (Button) getActivity().findViewById(R.id.updata);


            btnLoad.setOnClickListener( new View.OnClickListener() {             
                 public void onClick(View v) {  

                     android.app.FragmentManager fragmentManager = getFragmentManager();                
                     android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();                
                     Update_data updatedata = new Update_data(); 
                      fragmentTransaction.replace(R.id.fragment,updatedata);                         


                      fragmentTransaction.commit();           
                     }        
                 }); 

        dbAdapter.close();

    }
     public void onListItemClick(ListView parent, View v, int position, long id) 
        {       

            for(int a = 0; a < parent.getChildCount(); a++) 
            { 
                parent.getChildAt(a).setBackgroundColor(Color.WHITE);

            } 
            TextView label1=(TextView)getActivity().findViewById(R.id.textdisplay);
           v.setBackgroundColor(Color.LTGRAY);   
           label1.setText(stg1[position]);
        }   
}

and Frag_B file is Update_data.java

package com.dlcpl.insert_view;

import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
//import android.widget.ListView;
import android.widget.TextView;
//import android.support.v4.app.Fragment;
import android.widget.Toast;

public class Update_data  extends Fragment
{
    //String Text;
    EditText A_input;
     TextView label1;


    @Override
    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState) 
    {       
         return inflater.inflate(R.layout.update, container, false);        
    }   

    @Override
    public void onStart()
    {
        super.onStart();
        Button btnLoad = (Button) getActivity().findViewById(R.id.save_btn);
         A_input = (EditText)getActivity().findViewById(R.id.udate_text);

            btnLoad.setOnClickListener( new View.OnClickListener() {             
                DBAdapter Adapter =new DBAdapter(getActivity());

                public void onClick(View v) {                                

                    Adapter.open(); 
                     Cursor c = Adapter.gettext("text");
                        if (c.moveToFirst())
                        {
                        DisplayContact(c);
                        }
                        else
                        {
                        Toast.makeText(getActivity(), "No contact found", Toast.LENGTH_LONG).show();

                        }
                        Adapter.close();

                     }        
                 });  


    }
    public void DisplayContact(Cursor c)
    {  
        A_input.setText(c.getString(0));

    }

} 

and my Main Activity file is Home.java

package com.dlcpl.insert_view;

import android.app.Activity;
import android.os.Bundle;
//import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;


public class Home extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);        

   Button insertData = (Button) findViewById(R.id.button1);
        insertData.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Insert_Data insertdata = new Insert_Data();               
                 android.app.FragmentManager fragmentManager = getFragmentManager();                
                 android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();                
                 fragmentTransaction.replace(R.id.fragment,insertdata);                
                 fragmentTransaction.commit();              
            }

        });

      Button viewData = (Button) findViewById(R.id.button2);
        viewData.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                View_Data viewdata = new View_Data();               
                 android.app.FragmentManager fragmentManager = getFragmentManager();                
                 android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();                
                 fragmentTransaction.replace(R.id.fragment,viewdata);                
                 fragmentTransaction.commit();              
            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_home, menu);
        return true;
    }
}
sandip chandak
  • 93
  • 2
  • 2
  • 8

4 Answers4

6

Try with Bundle,

I can't remember now the code, but when one friend of mine used fragment he used Bundle, I think he used like the last parameter in some calling method.

UPDATE:

Send:

 Fragment fragment = new Fragment();
 Bundle bundle = new Bundle();
 bundle.putInt(key, value);
 fragment.setArguments(bundle);

Retrieve:

 Bundle bundle = this.getArguments();
 int myInt = bundle.getInt(key, defaultValue);

I found the code above in this link: How to transfer some data to another Fragment?

Community
  • 1
  • 1
William Da Silva
  • 703
  • 8
  • 19
1

As both of your fragments share the same activity "Home" you can use this to share information between the two fragments. View_Data could call:

((Home) getActivity()).shareData("example string");

Which could correspond to the method shareData() in Home:

public void shareData(String string){
    android.app.FragmentManager fragmentManager = getFragmentManager();                
    Update_data fragment = (Update_data) fragmentManager.findFragmentByTag( "your_tag" );
    fragment.update(string);
}

You will need to set the id of your second fragment so that the fragment manager is able to find the fragment and also create the public method "update" in your second fragment.

Edit: To set the tag of a fragment, change your fragment add code to include the tag "your_tag".

View_Data viewdata = new View_Data();               
android.app.FragmentManager fragmentManager = getFragmentManager();                
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();                
fragmentTransaction.replace(R.id.fragment,viewdata,"your_tag");                
fragmentTransaction.commit();              
Ljdawson
  • 12,091
  • 11
  • 45
  • 60
  • I want to transfer selected item in listview from fragment first to other frgment and set to edittext. Please give me full example with explanation. Thanks in advance. – sandip chandak Sep 14 '12 at 12:29
  • I've modified my example to reflect sharing a string from one fragment to another. – Ljdawson Sep 14 '12 at 14:15
  • I have created dynamically fragment. Please tell me how to set id for Update_data fragment for this code Update_data fragment = (Update_data) fragmentManager.findFragmentById( id_of_fragment); – sandip chandak Sep 14 '12 at 15:10
  • I've modified the example to show how to set the tag of a fragment, you can then call findFragmentByTag. – Ljdawson Sep 16 '12 at 12:52
0
  • Option 1: Using Intent, you can setIntent() and getIntet() puting all the data you wish on your intent,
  • Option 2: Both of your fragments leave in the same activity. You can get activity reference by calling() getActivity()

In both cases your data will be stored in the activity level, and this is good because your fragments live in the same activity so both the options can do the job very well.

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
0

you can use setArgument and getArgument method to pass the data

ft.replace(R.id.menuContent, Fragment.instantiate(getApplicationContext(), name, bundle));

you can get this bundle in in FragmentB class by getArguments() methods where name is the name of class e.g. fragmentB.class.getName()

Nixit Patel
  • 4,435
  • 5
  • 30
  • 57