0

My program requires me to send data from a database in the phone over to android wear of the same program when a Button is clicked. I have been trying to send it by converting the database to JSON and then taking those datas from the JSON recieved and entering them in the database with the same name (but has an extra record). Sending the JSON data to the watch works perfectly fine but when it comes to receiving the data on the watch, the watch never receives it. I have tried several methods to try and see if the watch receives anything but so far nothing. I haven't implemented a DataMap for it like some of Google's tutorial does but I am not sure how to do so. My code below shows exactly what I have done so far:

Phone - MainPhoneApp.java's onCreate method:

final Button updateWearDatabaseButton = (Button) findViewById(R.id.updateWearDatabaseButton);
        updateWearDatabaseButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                DatabaseToJSON dbJSON = new DatabaseToJSON(MainPhoneApp.this);
                try {
                    JSONArray json = dbJSON.getJSON();
                    new SendToDataLayerThread(DatabaseHelper.DB_DIRECTORY, json.toString()).start();
                    Toast.makeText(getApplicationContext(), "Wear Database Updated", Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

Phone - DatabaseToJSON.java:

package com.jawad.wifihotspotfinder;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DatabaseToJSON {
    DatabaseHelper dbhandler;

    public DatabaseToJSON(Context context) {
        dbhandler = new DatabaseHelper(context);
    }

    public JSONArray getJSON() throws JSONException {
        String myPath = DatabaseHelper.DB_DIRECTORY; // Set path to your database
        String myTable = DatabaseHelper.DB_TABLE; // Set name of your table

        SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        String searchQuery = "SELECT  * FROM " + myTable;
        Cursor cursor = myDataBase.rawQuery(searchQuery, null );

        JSONArray resultSet = new JSONArray();

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {

            int totalColumn = cursor.getColumnCount();
            JSONObject rowObject = new JSONObject();
            for( int i=0 ;  i< totalColumn ; i++ ) {
                if( cursor.getColumnName(i) != null ) {
                    try {
                        if( cursor.getString(i) != null )
                        {
                            Log.d("TAG_NAME", cursor.getString(i));
                            rowObject.put(cursor.getColumnName(i) ,  cursor.getString(i) );
                        }
                        else
                        {
                            rowObject.put( cursor.getColumnName(i) ,  "" );
                        }
                    } catch( Exception e ) {
                        Log.d("TAG_NAME", e.getMessage()  );
                    }
                }
            }
            resultSet.put(rowObject);
            cursor.moveToNext();
        }
        cursor.close();
        Log.d("TAG_NAME", resultSet.toString());
        return resultSet;
    }
}

Wear - DataLayerListenerService.java:

package com.jawad.wifihotspotfinder;

import android.content.ContentValues;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class DataLayerListenerService extends WearableListenerService {

    public final String TAG = "NodeListener";

    @Override
    public void onPeerConnected(Node peer) {
        super.onPeerConnected(peer);

        String id = peer.getId();
        String name = peer.getDisplayName();

        Log.d(TAG, "Connected peer name & ID: " + name + "|" + id);
    }

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
        ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
        if(!connectionResult.isSuccess()) {
            Log.e("Error", "Failed to connect to Google API Client");
            return;
        }

        if (messageEvent.getPath().equals(DatabaseHelperWear.DB_DIRECTORY)) {
            final String message = new String(messageEvent.getData());
            Log.v("myTag", "Message path received on watch is: " + messageEvent.getPath());
            Log.v("myTag", "Message received on watch is: " + message);

            try {
                DatabaseHelperWear myDbHelper;
                myDbHelper = new DatabaseHelperWear(this);

                try {
                    myDbHelper.createDataBase();
                } catch (IOException io) {
                    throw new Error("Unable to create database");
                }

                try {
                    myDbHelper.openDataBase();
                } catch (SQLException sqle) {
                    throw new Error("Unable to open database");
                }

                SQLiteDatabase db = myDbHelper.getWritableDatabase();

                try {
                    JSONArray jArray = new JSONArray(message);
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json_data = jArray.getJSONObject(i);
                        ContentValues initialValues = new ContentValues();
                        initialValues.put("_id", json_data.getString("_id"));
                        initialValues.put("Type", json_data.getString("Type"));
                        initialValues.put("Postcode", json_data.getString("Postcode"));
                        initialValues.put("Latitude", json_data.getString("Latitude"));
                        initialValues.put("Longitude", json_data.getString("Longitude"));

                        String where = "_id = ?";
                        String[] whereArgs = new String[] {String.valueOf(i)};
                        db.update(DatabaseHelperWear.DB_TABLE, initialValues, where, whereArgs);
                    }
                } catch (JSONException e) {
                    Log.e("log_tag", "Error parsing data " + e.toString());
                }
                myDbHelper.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            Toast.makeText(getApplicationContext(), "Database updated", Toast.LENGTH_SHORT).show();
        }
        else {
            super.onMessageReceived(messageEvent);
        }
    }
}

UPDATE

I forgot to add the AndroidManifest.xml part.

<service android:name=".NodeListenerService">
    <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
    </intent-filter>
</service>

1 Answers1

0

If you're extending WearableListenerService you don't need to make a connection to GoogleApiClient; that's all done behind the scenes. So all you really need is to process the data from the message:

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    if (messageEvent.getPath().equals(DatabaseHelperWear.DB_DIRECTORY)) {
        // process data
    }
}
Sterling
  • 6,365
  • 2
  • 32
  • 40
  • It still doesn't work. This is what my phone is saying: `02-19 00:30:49.850 14609-16699/com.jawad.wifihotspotfinder V/myTag: Message: {[{"_id":"1","Type":"Work","Postcode":"N1 9NR","Latitude":"51.531","Longitude":"-0.121539"},{"_id":"2","Type":"Home","Postcode":"WC2B 6UN","Latitude":"51.5137","Longitude":"-0.118486"}]} sent to: LG Urbane FC48` but nothing is being received in the watch. – Jawad Adnan Feb 19 '16 at 00:37
  • Crap! Just realised my `AndroidManifest.xml` had the wrong name for the Listener Class. – Jawad Adnan Feb 19 '16 at 00:50