Gear Fit SDK IllegalStateException - android

I recently downloaded the Gear Fit-SDK from XDA-Developers-forum and tried the example in the pdf file.
The app is starting and I can click on the ListViewItem to start the ExampleDialog on my Gear Fit. But then I get the following error:
04-01 15:00:52.748 29498-29498/de.chrosey.gearfitone E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.chrosey.gearfitone, PID: 29498
java.lang.IllegalStateException: Scup is not initialized
at com.samsung.android.sdk.cup.ScupDialog.<init>(Unknown Source)
at de.chrosey.gearfitone.cup.HelloCupDialog.<init>(HelloCupDialog.java:15)
at de.chrosey.gearfitone.MainActivity$1.onItemClick(MainActivity.java:39)
...
Here are my files:
MainActivity.java
public class MainActivity extends ActionBarActivity {
String[] NAMES = {"Hello Cup"};
private HelloCupDialog mHelloCupDialog = null;
private static final int Hello_Cup = 0;
private ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, NAMES);
mListView = (ListView) findViewById(R.id.demo_list);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == Hello_Cup) {
if (mHelloCupDialog == null) {
mHelloCupDialog = new HelloCupDialog(
getApplicationContext());
} else {
mHelloCupDialog.finish();
mHelloCupDialog = null;
}
}
}
});
}[...]}
HelloCupDialog.java
public class HelloCupDialog extends ScupDialog {
public HelloCupDialog(Context context) {
super(context); //<-- this is where the error appears
}
#Override
protected void onCreate(){
super.onCreate();
setBackEnabled(true);
ScupLabel helloLabel = new ScupLabel(this);
[...]
setBackPressedListener(new BackPressedListener() {
#Override
public void onBackPressed(ScupDialog scupDialog) {
finish();
}
});
}}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.chrosey.gearfitone">
<uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY" />
<uses-permission android:name="com.samsung.android.sdk.permission.SAMSUNG_CUP_SERVICE"/>
<application
[...]
<activity
[...]
<intent-filter>
<action android:name="com.samsung.android.sdk.cup"/>
</intent-filter>
</activity>
<meta-data
android:name="SAMSUNG_CUP_APP"
android:value="app_name;ic_launcher;true" />
</application>
I am testing on Samsung S4, Lollipop StockRom. IDE is Android Studio 1.1.
Has anybody an idea why it isn't working as other cups-enabled apps from PlayStore do?

You need to initialize Scup in your MainActivity before creating instance of ScupDialog. Add the following code after the setContentView.
Scup scup = new Scup();
try {
scup.initialize(this);
}catch (Exception e){}
Hope this is clear!

Related

Problems with NullPointer [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I need to go to the second activity, but when I click the button, it will write to me:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.application/com.example.application.Firebase}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2367)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$800(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1343)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
a
at android.app.Activity.performCreate(Activity.java:5350)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
This is Firebase activity:
public class Firebase extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlistView = (ListView) findViewById(R.id.listView);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://example.firebase/Users");
FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(
this,
String.class,
android.R.layout.simple_list_item_1,
databaseReference
) {
#Override
protected void populateView(View v, String model, int position) {
TextView textView = (TextView) v.findViewById(android.R.id.text1);
textView.setText(model);
}
};
mlistView.setAdapter(firebaseListAdapter);
}
}
This is the first activity:
public class DashBoard extends AppCompatActivity implements View.OnClickListener {
private TextView txtWelcome;
private EditText input_new_password;
private Button btnChangePass,btnLogout;
private RelativeLayout activity_dashboard;
private FirebaseAuth auth;
private Button mbtnIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_board);
//View
txtWelcome = (TextView)findViewById(R.id.dashboard_welcome);
input_new_password = (EditText)findViewById(R.id.dashboard_new_password);
btnChangePass = (Button)findViewById(R.id.dashboard_btn_change_pass);
btnLogout = (Button)findViewById(R.id.dashboard_btn_logout);
activity_dashboard = (RelativeLayout)findViewById(R.id.activity_dash_board);
mbtnIntent = (Button) findViewById(R.id.btnIntent);
btnChangePass.setOnClickListener(this);
btnLogout.setOnClickListener(this);
//Init Firebase
auth = FirebaseAuth.getInstance();
//Session check
if(auth.getCurrentUser() != null)
txtWelcome.setText("Welcome , "+auth.getCurrentUser().getEmail());
mbtnIntent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DashBoard.this), Firebase.class);
startActivity(intent);
}
});
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.dashboard_btn_change_pass)
changePassword(input_new_password.getText().toString());
else if(view.getId() == R.id.dashboard_btn_logout)
logoutUser();
}
private void logoutUser() {
auth.signOut();
if(auth.getCurrentUser() == null)
{
startActivity(new Intent(DashBoard.this,MainActivity.class));
finish();
}
}
private void changePassword(String newPassword) {
FirebaseUser user = auth.getCurrentUser();
user.updatePassword(newPassword).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Snackbar snackBar = Snackbar.make(activity_dashboard,"Password changed",Snackbar.LENGTH_SHORT);
snackBar.show();
}
}
});
}
}
This is manifest.xml :`
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DashBoard" />
<activity android:name=".ForgotPassword" />
<activity android:name= ".Firebase"/>
<activity android:name=".SignUp"></activity>
</application>
`
What should I write?
Change your code to this :
Intent intent = new Intent(DashBoard.this,Firebase.class);
startActivity(intent);
And Check if you delcared the second activity in Android Manifest.Xml like this:
<activity android:name=“.Firebase” />
Seems like the one or both of the ids listView or text1 are not inside the layout activity_main.xml in your Firebase class. Make sure they are there and that there is no typo.

Android - How to get a Session from my Spell Checker Service?

I am trying to implement a spell checker service as described here called SampleSpellCheckerService but it seems the tutorial is incomplete and the source code for it does not seem to be available.
I am struggling with how to get a session from my spell checker service in the setSuggestionsFor() method of my activity, as highlighted here:
public class SpellCheckerSettingsActivity extends AppCompatActivity implements SpellCheckerSession.SpellCheckerSessionListener {
private static final String LOG_TAG = SpellCheckerSettingsActivity.class.getSimpleName();
private TextView textView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spell_checker_settings);
final EditText editText = (EditText)findViewById(R.id.editText);
textView = (TextView)findViewById(R.id.textView);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchSuggestionsFor(editText.getText().toString());
}
});
startService(new Intent(this, SampleSpellCheckerService.class));
}
private void fetchSuggestionsFor(String input){
Log.d(LOG_TAG, "fetchSuggestionsFor(\"" + input + "\")");
/***************************************************
*
* This line is invalid. What do I replace it with?
*
***************************************************/
SpellCheckerSession session = SampleSpellCheckerService.getSession();
TextInfo[] textInfos = new TextInfo[]{ new TextInfo(input) };
int suggestionsLimit = 5;
session.getSentenceSuggestions(textInfos, suggestionsLimit);
}
#Override
public void onGetSuggestions(SuggestionsInfo[] results) {
Log.d(LOG_TAG, "onGetSuggestions(" + results + ")");
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText("Suggestions obtained (TODO - get from results[])");
}
});
}
#Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] results) {
Log.d(LOG_TAG, "onGetSentenceSuggestions(" + results + ")");
if (results != null) {
final StringBuffer sb = new StringBuffer("");
for (SentenceSuggestionsInfo result : results) {
int n = result.getSuggestionsCount();
for (int i = 0; i < n; i++) {
int m = result.getSuggestionsInfoAt(i).getSuggestionsCount();
for (int k = 0; k < m; k++) {
sb.append(result.getSuggestionsInfoAt(i).getSuggestionAt(k))
.append("\n");
}
sb.append("\n");
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(sb.toString());
}
});
}
}
#Override
public void onDestroy() {
stopService(new Intent(this, SampleSpellCheckerService.class));
super.onDestroy();
}
}
So what is the correct way to get a session from SampleSpellCheckerService?
For completeness, here is my spell checker service class:
public class SampleSpellCheckerService extends SpellCheckerService {
public static final String LOG_TAG = SampleSpellCheckerService.class.getSimpleName();
public SampleSpellCheckerService() {
Log.d(LOG_TAG, "SampleSpellCheckerService");
}
#Override
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "SampleSpellCheckerService.onCreate");
}
#Override
public Session createSession() {
Log.d(LOG_TAG, "createSession");
return new AndroidSpellCheckerSession();
}
private static class AndroidSpellCheckerSession extends SpellCheckerService.Session {
#Override
public void onCreate() {
Log.d(LOG_TAG, "AndroidSpellCheckerSession.onCreate");
}
#Override
public SentenceSuggestionsInfo[] onGetSentenceSuggestionsMultiple(TextInfo[] textInfos, int suggestionsLimit) {
Log.d(LOG_TAG, "onGetSentenceSuggestionsMultiple");
SentenceSuggestionsInfo[] suggestionsInfos = null;
//suggestionsInfo = new SuggestionsInfo();
//... // look up suggestions for TextInfo
return suggestionsInfos;
}
#Override
public SuggestionsInfo onGetSuggestions(TextInfo textInfo, int suggestionsLimit) {
Log.d(LOG_TAG, "onGetSuggestions");
SuggestionsInfo suggestionsInfo = null;
//suggestionsInfo = new SuggestionsInfo();
//... // look up suggestions for TextInfo
return suggestionsInfo;
}
#Override
public void onCancel() {
Log.d(LOG_TAG, "onCancel");
}
}
}
Here is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example">
<permission android:name="android.permission.BIND_TEXT_SERVICE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service
android:name="com.example.SampleSpellCheckerService"
android:label="#string/app_name"
android:enabled="true"
android:permission="android.permission.BIND_TEXT_SERVICE">
<intent-filter>
<action android:name="android.service.textservice.SpellCheckerService" />
</intent-filter>
<meta-data
android:name="android.view.textservice.scs"
android:resource="#xml/spellchecker" />
</service>
<activity android:name="com.example.SpellCheckerSettingsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And here is my spellchecker.xml:
<?xml version="1.0" encoding="utf-8"?>
<spell-checker
xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/spellchecker_name"
android:settingsActivity="com.example.SpellCheckerSettingsActivity">
<subtype
android:label="#string/subtype_generic"
android:subtypeLocale="en" />
/>
<subtype
android:label="#string/subtype_generic"
android:subtypeLocale="en_GB" />
/>
</spell-checker>
NB - I am testing with a Samsung device.
As far as I can see from the docs and some sample code, there seems to be some misconception of the android Spell Checking API, that result in your error.
As far as I can tell you can't call your service directly since the APIs goal is for you to define a spellchecker that the user has to select from the system settings first. Basically you mixed up the settings activity (that is displayed for service related settings) with a test activity for your service.
Some better tutorials are written in the android dev blog and here, some sample code for a testing client and an rudimentary example service could be found between the mirrored android samples on github.
What you got so far is the sample service (though the linked samples provide some more code to see how the methods could be implemented), you have your spellchecker.xml needed for locale definition and the spellchecker name appearing in the settings, you already have a settings activity (as defined in your spellchecker.xml, but not needed as long as you don't need any preferences) and you have an activity implementing your SpellCheckerSessionListener (although you named it as settings activity).
What you'd still need to do, is go to your settings -> Language & keyboard -> activate Spell checker and choose your spell checker.
To get a session from that spellchecker you can then make a call to the API with
final TextServicesManager tsm = (TextServicesManager) getSystemService(
Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);
as seen in the samples.
Edit:
if you don't need any settings for your service, you can remove the xml attribute from your xml:
android:settingsActivity="com.example.SpellCheckerSettingsActivity"

Android Error - Inconvertible types; cannot cast 'android.support.v4.app.FragmentActivity'

When I go to clean and compile my android project I am getting the following error that I cannot resolve: "Inconvertible types; cannot cast 'android.support.v4.app.FragmentActivity' to 'com.profile.activity.MainActivity'". This is the line of code that is giving me this error:
this.cpu = ((MainActivity) getActivity()).cpu
I thought adding the following line of code to the MainActivity.java would fix the error:
public CPU cpu = new CPU();
I didn't resolve the issue though. Here is my code under ProfilesFragment.java:
public void onAttach(Activity activity) {
super.onAttach(activity);
this.cpu = ((MainActivity) getActivity()).cpu; //This is the line of code giving me the error
}
Here is my code for MainActivity.java:
public class MainActivity extends Activity {
public CPU cpu = new CPU();
private String CANCEL;
private String DELETE;
private String EDIT;
private DatabaseAdapter dbHelper;
private ListView scheduleCustomListView;
public ArrayList<Schedule> scheduleList = new ArrayList();
public ArrayList<Schedule> getScheduleList() {
this.scheduleList = this.dbHelper.retrieveAllSchedules();
return this.scheduleList;
}
public void onCreate(Bundle savedInstanceState) {
this.dbHelper = new DatabaseAdapter(this);
this.dbHelper.open();
this.DELETE = getText(R.string.deleteSchedule).toString();
this.EDIT = getText(R.string.editSchedule).toString();
this.CANCEL = getText(R.string.cancel).toString();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.scheduleCustomListView = (ListView) findViewById(R.id.scheduleList);
this.scheduleCustomListView.setAdapter(new ListViewAdapter(this, R.layout.row, getScheduleList()));
this.scheduleCustomListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View arg1, int arg2, long arg3) {
Intent intentActivityUpdateSchedule = new Intent(MainActivity.this, UpdateScheduleActivity.class);
intentActivityUpdateSchedule.putExtra("schedule", (Serializable) MainActivity.this.scheduleList.get(arg2));
MainActivity.this.startActivity(intentActivityUpdateSchedule);
}
});
registerForContextMenu(this.scheduleCustomListView);
((LinearLayout) findViewById(R.id.bopenlayoutaddschedule)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MainActivity.this.startActivity(new Intent(MainActivity.this, AddNewScheduleActivity.class));
}
});
}
protected void onRestart() {
super.onRestart();
this.scheduleCustomListView.setAdapter(new ListViewAdapter(this, R.layout.row, getScheduleList()));
}
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
}
protected void onDestroy() {
super.onDestroy();
if (this.dbHelper != null) {
this.dbHelper.close();
}
}
Any help resolving this issue would be greatly appreciated.
I think you are using the Fragment from the Support package. Check the imports of your fragment class. You should import the fragment class "android.app.Fragment" and not the "android.support.v4.app.Fragment" (because you are using the base framework Activity class). If you want to use the support fragment then use also the activity from the support package ("AppCompatActivity").

Broadcast not receiving between two custom application

My program is about calculating calories of some food. This is a practice for CS course. I'm beginner on Android OS and I do not know why my receiving process cannot be completed or shown on Activity.
I just write the relevant code pieces here. I had some items on sqlite database and I can check my items on database with Log.d method and they are okay.
App1:
Manifest:
<receiver android:name="ItemBroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.example.furkan.datagenerator" />
</intent-filter>
</receiver>
Received.class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.received);
ItemBroadcastReceiver br = new ItemBroadcastReceiver();
Cursor cursor = (Cursor) br.receivedItem;
ReceivedItemsAdapter adapter = new ReceivedItemsAdapter(this, cursor);
ListView listView = getListView();
listView.setAdapter(adapter);
}
Adapter:
public class ReceivedItemsAdapter extends CursorAdapter {
public ReceivedItemsAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.received, parent, false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView name = (TextView) view.findViewById(R.id.name);
TextView cal = (TextView) view.findViewById(R.id.amountCal);
TextView unit = (TextView) view.findViewById(R.id.unit);
unit.setText(" cal");
name.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
cal.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}}
Broadcast Receiver:
public class ItemBroadcastReceiver extends BroadcastReceiver {
Item receivedItem;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
receivedItem = new Item(bundle.getString("name"),
Integer.parseInt(bundle.getString("calories")),
bundle.getString("category"),
null);
}}
App2:
MainActivity:
public class MainActivity extends AppCompatActivity {
final int DELAY = 60000;
ReceivedItem item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReceivedItemsDatabaseHelper dbHelper = new ReceivedItemsDatabaseHelper(this);
item = new ReceivedItem(dbHelper.fetchReceivedItem().getString(
dbHelper.fetchReceivedItem().getColumnIndex(
dbHelper.fetchReceivedItem().getColumnName(1))),
Integer.parseInt(dbHelper.fetchReceivedItem().getString(
dbHelper.fetchReceivedItem().getColumnIndex(
dbHelper.fetchReceivedItem().getColumnName(2)))),
dbHelper.fetchReceivedItem().getString(
dbHelper.fetchReceivedItem().getColumnIndex(
dbHelper.fetchReceivedItem().getColumnName(3))), null);
Thread thread = new Thread() {
public void run() {
synchronized (this) {
try {
Log.d("Response ", item.getName()+", "+item.getCategory()+", "+item.getCalories());
Intent intent = new Intent();
intent.setAction("com.example.furkan.datagenerator");
intent.putExtra("name", item.getName());
intent.putExtra("calories", item.getCalories());
intent.putExtra("category", item.getCategory());
sendBroadcast(intent);
sleep(DELAY);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
thread.start();
}}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.furkan.datagenerator");
ItemBroadcastReceiver br = new ItemBroadcastReceiver();
registerReceiver(br, filter);
You should read about BroadcastReceivers again.
ItemBroadcastReceiver br = new ItemBroadcastReceiver();
Cursor cursor = (Cursor) br.receivedItem;
ReceivedItemsAdapter adapter = new ReceivedItemsAdapter(this, cursor);
ListView listView = getListView();
listView.setAdapter(adapter);
This creates a new instance of the receiver and assigns the receivedItem to cursor. But receivedItem is null and since you never register br for broadcasts, it'll never be not null. Also I'm not sure, if Item could be cast to Cursor.
Considering the code you posted here and the title you used, using BroadcastReceiver might not be a good idea at all. You should try to pass data to Received via intent or load the data directly from persisted storage.
And at last your thread doesn't make any sense.

Updating a CircularButton in a custom Fragment created with FragmentGridPagerAdapter

I have a wearable app that has a couple of fragments created with FragmentGridPagerAdapter. One of the fragments has a couple of CircularButtons and I want to update the backcolor of the button when a message is received from handheld phone. I have no problems in receiving the message. However, button's color (or anything in UI) doesn't update. Do you know how can I fix this?
public class UIPageAdapter extends FragmentGridPagerAdapter {
private final Context mContext;
MainControlFragment[] mainControlFragments;
private List mRows;
uiChangeListener mUIChangeListener = new uiChangeListener();
public UIPageAdapter(Context ctx, FragmentManager fm) {
super(fm);
Log.i("pageAdapter", "constructor");
mContext = ctx;
mainControlFragments = new MainControlFragment[2];
mainControlFragments[0] = new MainControlFragment();
mainControlFragments[1] = new MainControlFragment();
LocalBroadcastManager.getInstance(ctx).registerReceiver(mUIChangeListener,new IntentFilter(Constants.BROADCAST_CONTROL_HOME));
}
#Override
public Fragment getFragment(int row, int col) {
Log.i("PageAdapter","Fragment #" + col +"is asked");
return mainControlFragments[col];
}
public void changeStatus(int button, boolean status) {
mainControlFragments[0].setStatus(button,status);
// notifyDataSetChanged();
}
public class uiChangeListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act == Constants.BROADCAST_CONTROL_HOME) {
int key = intent.getIntExtra(Constants.CONTROL_HOME_KEY,-1);
String command = intent.getStringExtra(Constants.CONTROL_HOME_COMMAND);
changeStatus(key,command.equals("on"));
}
}
}
#Override
public int getRowCount() {
return 1;
}
#Override
public int getColumnCount(int i) {
return 2;
}
}
Basically when a message received from the handheld device a WearableListener class broadcasts an update message to the UIPageAdapter
This is the listener class
public class ListenerService extends WearableListenerService
{
String tag = "ListenerService";
#Override
public void onMessageReceived(MessageEvent messageEvent) {
final String message = (new String(messageEvent.getData()));
Log.i(tag,message);
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Constants.BROADCAST_CONTROL_HOME)
.putExtra(Constants.CONTROL_HOME_KEY, messageEvent.getPath())
.putExtra(Constants.CONTROL_HOME_COMMAND,Integer.parseInt(message.substring(1)))
.putExtra("caller",tag));
}
#Override
public void onCreate() {
super.onCreate();
Log.i(tag, "onCreate");
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="smartstuff.com.tr.myautomationtool" >
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<uses-library
android:name="com.google.android.wearable"
android:required="false" />
<service android:name=".ListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault.Light" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Finally the custom fragment
public class MainControlFragment extends Fragment{
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("controlFragment","create");
this.container = container;
// Inflate the layout for this fragment
return inflater.inflate(R.layout.main_control, container, false);
}
public void setStatus(int button, boolean status) {
Log.i("controlFragment",button + " "+ status);
CircularButton[] btns = new CircularButton[4];
btns[0] = (CircularButton) container.findViewById(R.id.cbtnFront);
btns[1] = (CircularButton) container.findViewById(R.id.cbtnBack);
btns[2] = (CircularButton) container.findViewById(R.id.cbtnBed);
btns[3] = (CircularButton) container.findViewById(R.id.cbtnCoffee);
btns[button].setColor(status?Color.BLACK:Color.RED);
}
}
I also tried the notifyDataSetChanged(); method in UIPageAdapter however it it only calls onCreateView method in fragment. Any help is appreciated
I'm assuming you already resolved this but I had to add a call to invalidate() on the CircularButton after calling setColor():
_circularButton.setColor(ContextCompat.getColor(getActivity(), buttonColor));
_circularButton.invalidate();
Without the call to invalidate the UI only updated some of the time.

Categories

Resources