java - How to send data from DialogFragment to a Fragment?

java - How to send data from DialogFragment to a Fragment?

Mandlenkosi Shantelle Author: Mandlenkosi Shantelle Date: 2022-08-20
java - How to send data from DialogFragment to a Fragment?

All you need to know about java - How to send data from DialogFragment to a Fragment? , in addintion to android - How to send data from an activity to its parent fragment? , java - How to send data from Arduino-uno using Bluetooth module HC-05 and read it in Android? , android - How to get data from DialogFragment to a Fragment? , java - How to do Socket connection and send data to server from Android Wear

  1. java - How to send data from DialogFragment to a Fragment?
  2. Question:

    I have a fragment that opens a Dialogfragment to get user input (a string, and an integer). How do I send these two things back to the fragment?

    Here is my DialogFragment:

    public class DatePickerFragment extends DialogFragment {
        String Month;
        int Year;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            getDialog().setTitle(getString(R.string.Date_Picker));
            View v = inflater.inflate(R.layout.date_picker_dialog, container, false);
    
            Spinner months = (Spinner) v.findViewById(R.id.months_spinner);
            ArrayAdapter<CharSequence> monthadapter = ArrayAdapter.createFromResource(getActivity(),
                    R.array.Months, R.layout.picker_row);
                  months.setAdapter(monthadapter);
                  months.setOnItemSelectedListener(new OnItemSelectedListener(){
                      @Override
                      public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int monthplace, long id) {
                          Month = Integer.toString(monthplace);
                      }
                      public void onNothingSelected(AdapterView<?> parent) {
                        }
                  });
    
            Spinner years = (Spinner) v.findViewById(R.id.years_spinner);
            ArrayAdapter<CharSequence> yearadapter = ArrayAdapter.createFromResource(getActivity(),
                 R.array.Years, R.layout.picker_row);
            years.setAdapter(yearadapter);
            years.setOnItemSelectedListener(new OnItemSelectedListener(){
              @Override
              public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int yearplace, long id) {
                  if (yearplace == 0){
                      Year = 2012;
                  }if (yearplace == 1){
                      Year = 2013;
                  }if (yearplace == 2){
                      Year = 2014;
                  }
              }
              public void onNothingSelected(AdapterView<?> parent) {}
            });
    
            Button button = (Button) v.findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v) {
                   getDialog().dismiss();
                }
            });
    
            return v;
        }
    }
    

    I need to send the data after the button click and before getDialog().dismiss()

    Here is the fragment that data needs to be sent to:

    public class CalendarFragment extends Fragment {
    int Year;
    String Month;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        int position = getArguments().getInt("position");
        String[] categories = getResources().getStringArray(R.array.categories);
        getActivity().getActionBar().setTitle(categories[position]);
        View v = inflater.inflate(R.layout.calendar_fragment_layout, container, false);    
    
        final Calendar c = Calendar.getInstance();
        SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
        Month = month_date.format(c.getTime());
        Year = c.get(Calendar.YEAR);
    
        Button button = (Button) v.findViewById(R.id.button);
        button.setText(Month + " "+ Year);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               new DatePickerFragment().show(getFragmentManager(), "MyProgressDialog");
            }
        });
       return v;
      }
    }
    

    so once the user selects a date in the Dialogfragment, it must return the month and year.

    Then, the text on the button should change to the month and year specified by user.


    Solution 1:

    NOTE: aside from one or two Android Fragment specific calls, this is a generic recipe for implementation of data exchange between loosely coupled components. You can safely use this approach to exchange data between literally anything, be it Fragments, Activities, Dialogs or any other elements of your application.


    Here's the recipe:

    1. Create interface (i.e. named MyContract) containing a signature of method for passing the data, i.e. methodToPassMyData(... data);.
    2. Ensure your DialogFragment fullfils that contract (which usually means implementing the interface): class MyFragment extends Fragment implements MyContract {....}
    3. On creation of DialogFragment set your invoking Fragment as its target fragment by calling myDialogFragment.setTargetFragment(this, 0);. This is the object you will be talking to later.
    4. In your DialogFragment, get that invoking fragment by calling getTargetFragment(); and cast returned object to the contract interface you created in step 1, by doing: MyContract mHost = (MyContract)getTargetFragment();. Casting lets us ensure the target object implements the contract needed and we can expect methodToPassData() to be there. If not, then you will get regular ClassCastException. This usually should not happen, unless you are doing too much copy-paste coding :) If your project uses external code, libraries or plugins etc and in such case you should rather catch the exception and tell the user i.e. plugin is not compatible instead of letting the app crash.
    5. When time to send data back comes, call methodToPassMyData() on the object you obtained previously: ((MyContract)getTargetFragment()).methodToPassMyData(data);. If your onAttach() already casts and assigns target fragment to a class variable (i.e. mHost), then this code would be just mHost.methodToPassMyData(data);.
    6. Voilà. You just successfully passed your data from dialog back to invoking fragment.

    Solution 2:

    Here's another recipe without using any Interface. Just making use of the setTargetFragment and Bundle to pass data between DialogFragment and Fragment.

    public static final int DATEPICKER_FRAGMENT = 1; // class variable
    

    1. Call the DialogFragment as shown below:

    // create dialog fragment
    DatePickerFragment dialog = new DatePickerFragment();
    
    // optionally pass arguments to the dialog fragment
    Bundle args = new Bundle();
    args.putString("pickerStyle", "fancy");
    dialog.setArguments(args);
    
    // setup link back to use and display
    dialog.setTargetFragment(this, DATEPICKER_FRAGMENT);
    dialog.show(getFragmentManager().beginTransaction(), "MyProgressDialog")
    

    2. Use the extra Bundle in an Intent in the DialogFragment to pass whatever info back to the target fragment. The below code in Button#onClick() event of DatePickerFragment passes a String and Integer.

    Intent i = new Intent()
            .putExtra("month", getMonthString())
            .putExtra("year", getYearInt());
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
    dismiss();
    

    3. Use CalendarFragment's onActivityResult() method to read the values:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case DATEPICKER_FRAGMENT:
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String mMonth = bundle.getString("month", Month);
                    int mYear = bundle.getInt("year");
                    Log.i("PICKER", "Got year=" + year + " and month=" + month + ", yay!");
                } else if (resultCode == Activity.RESULT_CANCELED) {
                    ...
                }
                break;
        }
    }
    

    Solution 3:

    Here's an approach that illustrates Marcin's answer implemented in kotlin.

    1.Create an interface that have a method for passing data in your dialogFragment class.

    interface OnCurrencySelected{
        fun selectedCurrency(currency: Currency)
    }
    

    2.Add your interface in your dialogFragment constructor.

    class CurrencyDialogFragment(val onCurrencySelected :OnCurrencySelected)    :DialogFragment() {}
    

    3.Now make your Fragment implement the interface you just created

    class MyFragment : Fragment(), CurrencyDialogFragment.OnCurrencySelected {
    
    override fun selectedCurrency(currency: Currency) {
    //this method is called when you pass data back to the fragment
    }}
    

    4.Then to show your dialogFragment your just call CurrencyDialogFragment(this).show(fragmentManager,"dialog"). this is the interface object you will be talking to, to pass data back to your Fragment.

    5.When you want to sent data back to your Fragment you just call the method to pass data on the interface object your passed in dialogFragment constructor.

    onCurrencySelected.selectedCurrency(Currency.USD)
    dialog.dismiss()
    

  3. android - How to send data from an activity to its parent fragment?
  4. Question:

    I have a main activity, inside which there is a fragment with an image view. When this image view is clicked, a new activity starts which contains a list view. I want to return the position(index) the user clicks on this list view, back to the fragment.

    Fragment Code

    package com.example.kedee.testgradle;
    
    
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    
    /**
     * A simple {@link Fragment} subclass.
     */
    public class ASKFragment extends Fragment implements View.OnClickListener{
        private Context context;
        private View rootView;
        private int pos;
    
        public ASKFragment() {
            // Required empty public constructor
        }
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            rootView= inflater.inflate(R.layout.fragment_ask, container, false);
            context=inflater.getContext();
            setListeners();
            return  rootView;
        }
    
        void setListeners(){
            ImageView catIcon=(ImageView)rootView.findViewById(R.id.cat_icon);
            catIcon.setOnClickListener(this);
    
    
    
        }
    
        @Override
        public void onClick(View v) {
            int vID=v.getId();
            if(vID==R.id.cat_icon){
                Intent intent=new Intent(getActivity(),ASK.class);
                getActivity().startActivity(intent);
            }
    
        }
    }    
    

    Code of Activity which is getting called from this fragment. (ASK activity)

    package com.example.kedee.testgradle;
    
    import android.app.Fragment;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;
    
    public class ASK extends AppCompatActivity {
        private int index;
        private String[] catNames= {"Acad","Emer","Tech","Exam","Station","Finance","Medical","Place","Sports" ,
                "Others" };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_ask);
            ListView listView=(ListView)findViewById(R.id.ask_cat_listView);
            listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,catNames));
            listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                public void onItemClick(AdapterView<?> listView, View v, int pos, long id){
                    index=pos;
                    //code to return back this index to the parent fragment?
                }
            });
        }
    
    
    }
    


    Solution 1:

    use startActivityForResult

    1. in ASKFragment

    Intent intent=new Intent(getActivity(),ASK.class);
    getActivity().startActivityForResult(intent, 22 /* any other request code you want */);
    

    2. Pass position with intent.

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                public void onItemClick(AdapterView<?> listView, View v, int pos, long id){
                    index=pos;
                    Intent i = new Intent();
                    i.putExtra("position", index);
                    setResult(RESULT_OK, i);
                    finish();
                }
            });
    

    3. The activity from where you are adding or replacing fragment.

    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 22 && resultCode == RESULT_OK) {
                // get the position from intent
                if(data.getExtras()!=null && data.hasExtra("position")){
                   int position = data.getExtras().getInt("position");
                   // pass this position to fragment.
                }
            }
        }
    

    EDIT
    Send the value from Activity to fragment.
    1) create function in fragment

    public void getPositionOfList(int position){
       // here is the position
    }
    

    2) from Activity calling the fragment method.

    if (requestCode == 22 && resultCode == RESULT_OK) {
                    // get the position from intent
                    if(data.getExtras()!=null && data.hasExtra("position")){
                       int position = data.getExtras().getInt("position");
                       // pass this position to fragment.
                       ((ASKFragment)fragmentManager.findFragmentById(/*id of your container*/)).getPositionOfList(position);
                    }
                }
    

    Solution 2:

    You can achieve this by calling/starting new activity having listview

    by replacing startActivity to startActivityForResult

    and further send any data back to calling activity accordingly. Then, handle it with onActivityResult.

    Solution 3:

    you have to Use OnActivityResult like below

    In Main Activity In which you have Fragments you have to write like this

      @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.viewpager);
        fragment.onActivityResult(requestCode, resultCode, data);
    }
    

    Then in your Fragment in which you want result you have to write like below

     @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
        if(resultCode == getActivity().RESULT_OK) {
    
            switch(requestCode) {
    
                case REQUEST_PICK_FILE:
    
                    if(data.hasExtra(FilePicker.EXTRA_FILE_PATH)) {
    
                        selectedFile = new File
                                (data.getStringExtra(FilePicker.EXTRA_FILE_PATH));
                        tvFile.setText(selectedFile.getPath());
    
                    }
                    break;
            }
        }
    }
    

    And you have to put this code on which click you want to open Activity

            Intent intent = new Intent(getActivity(), FilePicker.class);
        startActivityForResult(intent, REQUEST_PICK_FILE);
    

  5. java - How to send data from Arduino-uno using Bluetooth module HC-05 and read it in Android?
  6. Question:

    I am able to send data from my Android phone to my Arduino Uno using the HC-05 module. I also want to send data from the Arduino to my Android phone and I'm unable to do that.

    Question: I will send a number from 0-9 using my android app to my Arduino Uno, the Arduino will send back the same number to my app, in words. For now, I am able to send numbers/letters to my Arduino from my app. I want help with the second part of the problem.

    This is, in fact, a perfect duplicate of this question Android - receive bluetooth data from Arduino, but, unfortunately, this remains unanswered.


    Solution 1:

    for receiving data from the arduino

    UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { 
         //Defining a Callback which triggers whenever data is read.
            @Override
            public void onReceivedData(byte[] arg0) {
                String data = null;
                try {
                    data = new String(arg0, "UTF-8");
                    data.concat("/n");
                    tvAppend(textView, data);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        };
    

    and to send data from the arduino

    serialPort.write(string.getBytes()); 
    

    check the full tutorial

    Solution 2:

    You can achieve this by calling/starting new activity having listview

    by replacing startActivity to startActivityForResult

    and further send any data back to calling activity accordingly. Then, handle it with onActivityResult.

  7. android - How to get data from DialogFragment to a Fragment?
  8. Question:

    Imagine, I have FragmentA from which I startDialogFragment (there are EditText in box). How to can I get back the value from the EditText to FragmentA? I try to make something like this, and this but I was not successful.


    Solution 1:

    The Fragment.onActivityResult() method is useful in this situation. It takes getTargetRequestCode(), which is a code you set up between fragments so they can be identified. In addition, it takes a request code, normally just 0 if the code worked well, and then an Intent, which you can attach a string too, like so

    Intent intent = new Intent();
    intent.putExtra("STRING_RESULT", str);
    

    Also, the setTargetFragment(Fragment, requestCode) should be used in the fragment that the result is being sent from to identify it. Overall, you would have code in the requesting fragment that looks like this:

    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialogFragment = new DialogFragment();
    dialogFragment.setTargetFragment(this, REQUEST_CODE);
    dialogFragment.show();
    

    The class to send data (the DialogFragment) would use this Fragment we just defined to send the data:

    private void sendResult(int REQUEST_CODE) {
        Intent intent = new Intent();
        intent.putStringExtra(EDIT_TEXT_BUNDLE_KEY, editTextString);
        getTargetFragment().onActivityResult(
            getTargetRequestCode(), REQUEST_CODE, intent);
    }
    

    To receive the data, we use this type of class in the Fragment which initially started the DialogFragment:

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Make sure fragment codes match up 
        if (requestCode == DialogFragment.REQUEST_CODE) {
            String editTextString = data.getStringExtra(
                DialogFragment.EDIT_TEXT_BUNDLE_KEY);
    

    At this point, you have the string from your EditText from the DialogFragment in the parent fragment. Just use the sendResult(int) method in your TextChangeListener() anonymous class so that the text is sent when you need it.

    Solution 2:

    Assume a situation that you are uploading some file to server , on clicking of upload button a dialog should open,prompting for title and optional tag.And the dialog itself containing 2 buttons say cancel and continue.

    make the UI as you wish by using layout xml file.

    then create one class that extending DialogFragment. inflate the layout and initialize views inside onCreateView() method.

    Inside that class create one interface

     public interface uploadDialogInterface
    
       {
           public void senddata(String title, String tag);
       }
    
        uploadDialogInterface interfaceObj;
        String title="";
        String tag=" ";
    

    And the important thing is you need to override onAttach() method

     @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
        interfaceObj= (uploadDialogInterface) getTargetFragment();
    }
    

    And in the on Button click call the interface method like

         @Override
    public void onClick(View v) {
        int id=v.getId();
        if(id== R.id.vB_fud_cancel)
        {
            dismiss();
        }
        else if(id== R.id.vB_fud_upload)
        {
            title=mVideotitle.getText().toString();
            tag=mOptionaltag.getText().toString();
            if(mVideotitle.getText().toString().isEmpty()) {
                Snackbar.make(mVideotitle,"Please enter the video title", Snackbar.LENGTH_SHORT).show();
           }else
            {
                interfaceObj.senddata(title,tag);
                dismiss();
    
            }
        }
    }
    

    And inside the Fragment or activity from which you are launching the dialog should contain setTargetFragment attribute.

    private void callUploadDialog()
    {
        UploadDialogFragment fragment = new UploadDialogFragment();
        fragment.setTargetFragment(this, 0);
        FragmentManager manager = getFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();
        ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_in);
        fragment.show(ft, "UploadDialogFragment");
        fragment.setCancelable(false);
    }
    

    And finally you should implement the interface (that was declared inside the dialog fragment) and override the method

    @Override
    public void senddata(String title,String optionaltag) {
        this.videoTitle=title;
        this.optionalTag=optionaltag;
    
    }
    

    I think this post will be helpful for those who are using dialog fragment for the first time . I was struggled to find the solution . And hopefully this will solve someone's problem in the future. (Sorry for the language)

    Solution 3:

    One of the better and simpler ways to do this is using Android ViewModel.

    This helps in easier sharing of data, without the need of sending any data across fragments. You could do this not only for DialogFragments, but also for normal Fragments.

    Source: https://developer.android.com/topic/libraries/architecture/viewmodel

    Here is what I did

    My ViewModel looks as below

    import android.arch.lifecycle.LiveData;
    import android.arch.lifecycle.MutableLiveData;
    import android.arch.lifecycle.ViewModel;
    
    public class PlayerViewModel extends ViewModel {
        private final MutableLiveData<Player> selectedPlayer = new MutableLiveData<>();
    
        public LiveData<Player> getSelectedPlayer() {
            return selectedPlayer;
        }
    
        public void selectPlayer(Player player) {
            selectedPlayer.setValue(player);
        }
    }
    

    In the Fragment where I select a Player, I use the following code in the onCreate method to bind the ViewModel

    playerViewModel = ViewModelProviders.of(getActivity()).get(PlayerViewModel.class);
    

    When a specific Player is selected, use the following (You can use an ArrayAdapter, DialogFragment's selector or anything you want to display list of players)

    playerViewModel = ViewModelProviders.of(getActivity()).get(PlayerViewModel.class);
    

    And finally, in the fragment where you need to show the Player information, do the following in the onCreate method

    PlayerViewModel model = ViewModelProviders.of(getActivity()).get(PlayerViewModel.class);
    model.getSelectedPlayer().observe(this, new Observer<Player>() {
        @Override
        public void onChanged(@Nullable Player selPlayer) {
            if (selPlayer != null)
                player = selPlayer;
                populateData();
            }
        });
    

  9. java - How to do Socket connection and send data to server from Android Wear
  10. Question:

    This program is to send Gyroscope and Accelerometer information (6 digits ) to server using Socket programing.

    My Question is How to do Socket connection and send data to server from Android Wear (using Socket Connection)

    Here is complete program ::

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    import com.example.helloandroid.R;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Context;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class HelloAndroid extends Activity implements SensorEventListener,Runnable {
        private SensorManager sensorManager;
    
        TextView x1; // declare X axis object
        TextView y1; // declare Y axis object
        TextView z1; // declare Z axis object
    
        TextView x2; // declare X axis object
        TextView y2; // declare Y axis object
        TextView z2; // declare Z axis object
    
        String x1Str,y1Str,z1Str,x2Str,y2Str,z2Str ;
        String oldX1,oldY1,oldZ1,oldX2,oldY2,oldZ2;
    
        Button sendAtATime,startContinous,dataChanged;
        private boolean startStop = false ,valueChanged = true;
    
        Context context ;
    
        public HelloAndroid(){}
    
        public HelloAndroid(String x1Str, String y1Str, String z1Str, String x2Str,
                String y2Str, String z2Str) {
            super();
            this.x1Str = x1Str;
            this.y1Str = y1Str;
            this.z1Str = z1Str;
            this.x2Str = x2Str;
            this.y2Str = y2Str;
            this.z2Str = z2Str;
        }
    
        @SuppressLint("NewApi") @Override
        public void onCreate(Bundle savedInstanceState){
             context = getApplicationContext();
             StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()   // or .detectAll() for all detectable problems
                .penaltyLog()
                .build());
              StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build()); 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            x1=(TextView)findViewById(R.id.x1); // create X axis object
            y1=(TextView)findViewById(R.id.y1); // create Y axis object
            z1=(TextView)findViewById(R.id.z1); // create Z axis object
    
            x2=(TextView)findViewById(R.id.x2); // create X axis object
            y2=(TextView)findViewById(R.id.y2); // create Y axis object
            z2=(TextView)findViewById(R.id.z2); // create Z axis object
    
            sendAtATime =  (Button)findViewById(R.id.sendAtATime);
            startContinous =  (Button)findViewById(R.id.startContinuous);
    
            sendAtATime.setOnClickListener(buttonSendOnClickListener);
            startContinous.setOnClickListener(buttonContinuousClickListener);
    
            sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
            // add listener. The listener will be HelloAndroid (this) class
            sensorManager.registerListener(this,
                    sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_NORMAL);
    
            sensorManager.registerListener(this,
                    sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    
        public void onAccuracyChanged(Sensor sensor,int accuracy){
        }
    
        public void onSensorChanged(SensorEvent event)
        {
            // check sensor type
            if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER)
            {
                oldX1 = x1.getText().toString();
                oldY1 = y1.getText().toString();
                oldZ1 = z1.getText().toString();
    
                // assign directions/
                float x=event.values[0];
                float y=event.values[1];
                float z=event.values[2];
    
                x1.setText("X1: "+x);
                y1.setText("Y1: "+y);
                z1.setText("Z1: "+z);
    
            }
            if(event.sensor.getType()==Sensor.TYPE_ORIENTATION)
            {
                oldX2 = x2.getText().toString();
                oldY2 = y2.getText().toString();
                oldZ2 = z2.getText().toString();
    
                // assign directions/
                float x=event.values[0];
                float y=event.values[1];
                float z=event.values[2];
    
                x2.setText("X2: "+x);
                y2.setText("Y2: "+y);
                z2.setText("Z2: "+z);
            }
    
            if(x1.getText().toString().equals(oldX1) && y1.getText().toString().equals(oldY1) 
            && z1.getText().toString().equals(oldZ1) && x2.getText().toString().equals(oldX2)
            && y2.getText().toString().equals(oldY2) && z2.getText().toString().equals(oldZ2) )
            {
                valueChanged = false;
            }
            else
            {
                valueChanged = true;
            }
            if(startStop && valueChanged)
            {
    
                Thread aThread = new Thread(new HelloAndroid(x1.getText().toString()
                                                            ,y1.getText().toString()
                                                            ,z1.getText().toString()
                                                            ,x2.getText().toString()
                                                            ,y2.getText().toString()
                                                            ,z2.getText().toString()));
                aThread.run();
            }
        }
    
        Button.OnClickListener buttonContinuousClickListener = new Button.OnClickListener()
        {
            public void onClick(View arg0) 
            {
                if(startStop)
                {
                    startStop = false;
                    startContinous.setText("Send Continous");
                    return;
                }
                startStop = true;
                startContinous.setText("StopContinous");
            }
         };
         Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener()
         {
            public void onClick(View arg0) 
            {
                Thread aThread = new Thread(new HelloAndroid(x1.getText().toString()
                                                            ,y1.getText().toString()
                                                            ,z1.getText().toString()
                                                            ,x2.getText().toString()
                                                            ,y2.getText().toString()
                                                            ,z2.getText().toString()));
                aThread.run();
            }
         };
        public void run() 
        {
            Socket socket = null;
             DataOutputStream dataOutputStream = null;
             DataInputStream dataInputStream = null;
    
             try 
             {
                  socket = new Socket("192.168.1.107", 5000);
                  dataOutputStream = new DataOutputStream(socket.getOutputStream());
                  dataInputStream = new DataInputStream(socket.getInputStream());
                  dataOutputStream.writeUTF("\nAcceleration Values :\n"
                                            +x1Str+"\n"
                                            +y1Str+"\n"
                                            +z1Str+"\n"
                                            +"Orientation Values :\n"
                                            +x2Str+"\n"
                                            +y2Str+"\n"
                                            +z2Str+"\n");
             } 
             catch (UnknownHostException e) 
             {
                 e.printStackTrace();
             } 
             catch (IOException e) 
             {
                 e.printStackTrace();
             }
             finally
             {
                    if (socket != null)
                    {
                         try 
                         {
                             socket.close();
                         } 
                         catch (IOException e) 
                         {
                             e.printStackTrace();
                         }
                    }
                    if (dataOutputStream != null)
                    {
                          try 
                          {
                            dataOutputStream.close();
                          } 
                          catch (IOException e) 
                          {
                               e.printStackTrace();
                          }
                    }
                    if (dataInputStream != null)
                    {
                         try 
                         {
                              dataInputStream.close();
                         } 
                         catch (IOException e) 
                         {
                              e.printStackTrace();
                         }
                    }
                }   
        }    
    }
    

    This way i was able to send Sensor data to server using Mobile phone. But while i am using same program with Android Wear but its not connecting to socket and because of NO INTERNET connection (Because its not connected to WIFI) obvious !!

    I read few related topics on stackoverflow but i am still not sure how to do this ??

    Related question : Android wear doesn't start thread

    I also read http://developer.android.com/training/wearables/data-layer/index.html but still trying best way to send data over internet (NOT BLUETOOTH SOCKET - since person can go out side range)

    Can anyone help me with this question.


    Solution 1:

    This is not possible, unfortunately, because Android Wear devices have no direct access to the Internet (and hence cannot use sockets, HttpURLConnection, or any of the like). See for example:

    • Does Android Wear support HttpURLConnection - getting EOFException
    • Direct internet connection on Android Wear?

    The only supported way of getting data "out" of the Wearable device is using the Data or Message APis as described in the article you mention (Data Layer).

    Solution 2:

    Hi to do this i had to create and use Wearable.MessageApi using GoogleApiClient

    I have complete code posted on Git repo : --> https://github.com/mvyas85/Fall-Alarm-Wearable

    Since Wearable can only make bluetooth connection with Phone, main method to send msg is using following class which is a thread and which uses Wearable.MessageApi to send msg from my Android wearable to my phone. and then phone has Socket which on Wifi connects to Server.

    /**
     * WearableMessageSender is responsible for sending messages
     * between apps and wearable devices. It manages this work
     * on its own thread.
     */
    public class WearableMessageSender extends Thread {
    
        private static final String TAG = "WearableMessageSender";
    
        private String mPath;
        private DeviceData mMessage;
        private GoogleApiClient mGoogleApiClient;
        /**
         * Constructor to send a message to the data layer
         * @param path Message path
         * @param msg Message contents
         * @param googleApiClient GoogleApiClient object
         */
        public WearableMessageSender(String path, DeviceData msg, GoogleApiClient googleApiClient) {
    a
            Log.i(TAG,"Google Api is connected");
            if (null == path || null == msg || null == googleApiClient) {
                Log.e(TAG, "Invalid parameter(s) passed to WearableMessageSender");
                throw new IllegalArgumentException("Invalid parameter(s) passed to WearableMessageSender");
            }
            mPath = path;
            mMessage = msg;
            mGoogleApiClient = googleApiClient;
        }
    
        public void run() {
            // Broadcast message to call connected nodes
            NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
            for (Node node : nodes.getNodes()) {
                MessageApi.SendMessageResult result = null;
                try {
                    result = Wearable.MessageApi.sendMessage(
                            mGoogleApiClient,
                            node.getId(),
                            mPath,
                            DeviceData.serialize(mMessage)
                    ).await();
                    Log.i(TAG,"Trying to send byte arr::"+DeviceData.serialize(mMessage));
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                if (result.getStatus().isSuccess()) {
                    Log.d(TAG, "Message: {" + mMessage + "} successfully sent to: " + node.getDisplayName());
                } else {
                    Log.e(TAG, "Failed to send message to device");
                }
            }
        }
    }