Search dialog box doesn't shows up - android

I tried to follow the developers guide line and checked the error that are similar to this my manifest and searchable file looks ok but still search dialog box doesn't appears. Any help is appreciated thanks in advance.
ser.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/hint">
</searchable>
manifest.xml
<activity
android:name="e.ftsexample.MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/ser" />
</activity>
Mainactivity
public class MainActivity extends Activity {
DbS cr;
private String[] from;
private int[] to;
private SimpleCursorAdapter str;
private ListView LS;
SQLiteDatabase ss;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cr = new DbS(getApplicationContext());
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
GetMysearch(getIntent());
// views
LS = (ListView) findViewById(R.id.listView1);
from = new String[] { DbS.Name_Col, DbS.Number_col };
to = new int[] { R.id.sV, R.id.sVS };
ss = cr.getWritableDatabase();
Cursor currr = ss.query(DbS.Table_Name, new String[] { " rowid _id ",
DbS.Name_Col, DbS.Number_col }, null, null, null, null, null);
str = new SimpleCursorAdapter(this, R.layout.qss, currr, from, to, 0);
LS.setAdapter(str);
}
private void GetMysearch(Intent myint) {
// TODO Auto-generated method stub
// Intent myint = getIntent();
if (Intent.ACTION_SEARCH.equals(myint.getAction())) {
String query = myint.getStringExtra(SearchManager.QUERY);
Log.e("Reached", "intent");
doMySearch(query);
}
}
private void doMySearch(String query) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "QUERY REACHED",
Toast.LENGTH_SHORT).show();
}
#Override
public boolean onSearchRequested() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "onSearchRequested",
Toast.LENGTH_SHORT).show();
return super.onSearchRequested();
}
#Override
protected void onNewIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "Intet passed",
Toast.LENGTH_SHORT).show();
setIntent(intent);
GetMysearch(intent);
}
}

try adding this to your activity:
<meta-data
android:name="android.app.default_searchable"
android:value="e.ftsexample.MainActivity" />
Edit: The reason is that you configured your activity to receive search query, but not to initiate a search.you can add this to any other activity and start search by callin
onSearchRequested();
hope this help.

Related

Music app that reads external storage audio is working on emulator and not working on real devices

I have a list view that displays all the songs in my device in the application, then when I click on the song another activity opens where you can play the song, on emulator when I click on the song in the list it takes me to the other activity and I can play and hear the song, but on real device I'm not getting any error but when I select an item from the list, I get the name and artist of the song, but when i click on play it doesn't work, I don't hear sound nor can I jump to middle of song etc..
the list is like this:
When clicked:
I'm using media player to read the audio files, and the code for my main activity is:
public class MusicPlayerOffline extends AppCompatActivity implements View.OnClickListener {
TextView tvTime,tvDuration,tvTitle,tvArtist;
SeekBar seekBarTime,seekBarVolume;
Button btnPlay;
MediaPlayer musicPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player_offline);
Songs song = (Songs) getIntent().getSerializableExtra("song");
tvTime=findViewById(R.id.tvTime);
tvDuration=findViewById(R.id.tvDuration);
seekBarTime=findViewById(R.id.seekBarTime);
seekBarVolume=findViewById(R.id.seekBarVolume);
btnPlay=findViewById(R.id.btnPlay);
tvTitle=findViewById(R.id.tvTitle);
tvArtist=findViewById(R.id.tvArtist);
tvTitle.setText(song.getTitle());
tvArtist.setText(song.getArtist());
musicPlayer=new MediaPlayer();
try {
musicPlayer.setDataSource(song.getPath());
musicPlayer.prepare();
}catch (IOException e){
e.printStackTrace();
}
musicPlayer.setLooping(true);
musicPlayer.seekTo(0);
musicPlayer.setVolume(0.5f, 0.5f);
String duration = millisecondsToString(musicPlayer.getDuration());
tvDuration.setText(duration);
btnPlay.setOnClickListener(this );
seekBarVolume.setProgress(50);
seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float volume = progress /100f;
musicPlayer.setVolume(volume, volume);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBarTime.setMax(musicPlayer.getDuration());
seekBarTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
musicPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
new Thread(new Runnable() {
#Override
public void run() {
while (musicPlayer != null){
if (musicPlayer.isPlaying()){
try {
final double current = musicPlayer.getCurrentPosition();
final String elapsdTime = millisecondsToString((int) current);
runOnUiThread(new Runnable() {
#Override
public void run() {
tvTime.setText(elapsdTime);
seekBarTime.setProgress((int) current);
}
});
Thread.sleep(1000);
}catch (InterruptedException e){}
}
}
}
}).start();
}// end main
public String millisecondsToString(int time){
String elapsedTime = "";
int minutes = time / 1000 / 60;
int seconds = time / 1000 % 60;
elapsedTime = minutes+":";
if (seconds < 10){
elapsedTime += "0";
}
elapsedTime += seconds;
return elapsedTime;
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnPlay){
if (musicPlayer.isPlaying()){
// is playing
musicPlayer.pause();
btnPlay.setBackgroundResource(R.drawable.ic_play);
}else {
// on pause
musicPlayer.start();
btnPlay.setBackgroundResource(R.drawable.ic_pause);
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home){
finish();
if (musicPlayer.isPlaying()){
musicPlayer.stop();
}
}
return super.onOptionsItemSelected(item);
}
}
The code for my listviewmusic activity from where I retrieve title artist and audio is:
public class ListMusicActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSION = 99;
ArrayList<Songs> songArrayList;
ListView tvSongs;
SongsAdapter songsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_music);
tvSongs = findViewById(R.id.tvSongs);
songArrayList = new ArrayList<>();
songsAdapter = new SongsAdapter(this, songArrayList);
tvSongs.setAdapter(songsAdapter);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
return;
}else {
// you have permission to read from external storage
getSongs();
}
tvSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Songs song = songArrayList.get(position);
Intent openMusicPlayer = new Intent(ListMusicActivity.this, MusicPlayerOffline.class);
openMusicPlayer.putExtra("song", song);
startActivity(openMusicPlayer);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSION){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
getSongs();
}
}
}
private void getSongs() {
// read songs from phone
ContentResolver contentProvider = getContentResolver();
Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songCursor = contentProvider.query(songUri,null,null,null,null);
if (songCursor != null && songCursor.moveToNext()) {
int indexTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int indexArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int indexData = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do {
String title = songCursor.getString(indexTitle);
String artist = songCursor.getString(indexArtist);
String path = songCursor.getString(indexData);
songArrayList.add(new Songs(title, artist, path));
}while (songCursor.moveToNext());
}
songsAdapter.notifyDataSetChanged();
}
}
My adapter:
public class SongsAdapter extends ArrayAdapter<Songs> {
public SongsAdapter(#NonNull Context context, #NonNull List<Songs> objects) {
super(context,0, objects);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_song, null);
TextView tvTitle = convertView.findViewById(R.id.tvTitle);
TextView tvArtist = convertView.findViewById(R.id.tvArtist);
Songs song = getItem(position);
tvTitle.setText(song.getTitle());
tvArtist.setText(song.getArtist());
return convertView;
}
}
I have no idea why it's not working, I don't get any error in the logcat, the music just doesn't start, it stays frozen at 0:00, and I cant jump to middle of it etc, although the name and artist name get obtained successfully just no audio
My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.smallacademy.authenticatorapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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"
android:windowSoftInputMode="adjustPan">
<activity android:name=".ListMusicActivity"></activity>
<activity android:name=".MusicPlayerOffline" />
<activity android:name=".MusicplayerOnline" />
<activity android:name=".Musicplayer" />
<activity
android:name=".Admin_crud_Illness"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar" />
<activity
android:name=".Admin_crud_food"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"
android:windowSoftInputMode="adjustPan" />
<activity android:name=".CaloriesCounterAdmin" />
<activity android:name=".Admin_addIllness" />
<activity android:name=".Admin_addfood" />
<activity android:name=".WaterInfo" />
<activity android:name=".WaterIntake" />
<activity android:name=".Share" />
<activity android:name=".Weather_Act" />
<activity android:name=".CalorieCounter" />
<activity android:name=".FetchFeedbacks" />
<activity android:name=".AdminHome" />
<activity android:name=".FeedBack" />
<activity android:name=".AdminDel" />
<activity android:name=".UpdateData" />
<activity android:name=".Fetchdata" />
<activity android:name=".Admin_add" />
<activity android:name=".BmiInfo" />
<activity android:name=".AdminAct" />
<activity android:name=".Loseweight_nutrition" />
<activity android:name=".Maintainweight_nutrition" />
<activity android:name=".Overweight_nutrition" />
<activity android:name=".Nutrition" />
<activity android:name=".CalmMood" />
<activity android:name=".AnnoyedMood" />
<activity android:name=".AngryMood" />
<activity android:name=".SadMood" />
<activity android:name=".HappyMood" />
<activity android:name=".MoodFeature" />
<activity android:name=".Calendar" />
<activity android:name=".Alarm" />
<activity
android:name=".StopWatch"
android:parentActivityName=".Home" />
<activity android:name=".Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Exercice"
android:windowSoftInputMode="adjustPan" />
<activity android:name=".BMI_Calculator" />
<activity android:name=".Home" />
<activity android:name=".EditProfile" />
<activity android:name=".Login" />
<activity android:name=".Register" />
<activity android:name=".MainActivity" />
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<receiver
android:name=".AlertReceiver"
android:enabled="true"
android:exported="true"
android:process=":remote" />
</application>
</manifest>

quick tiles is shown but not active in notification bar

I am trying to implement simple quick settings tile with the help of google docs,
but my tile appears to be there but greyed out(intent activity)- I can't click or do anything with it and cant remove it either without restarting my phone(one plus 3T/oreo8.0.0).
and the same thing goes with sample code google provided.
what things do i need to keep in mind/ how to do it?
is there anything I am missing?
I saw one similar question but it was a bit over my head.
MANIFEST
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
<service
android:name=".QSIntentService"
android:icon="#drawable/ic_android_black_24dp"
android:label="#string/qs_intent_tile_label"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
</service>
<activity
android:name=".ResultActivity"
android:label="#string/result_label"/>
</application>
JAVA (Main ACtivity)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
QSintentservice.java
public class QSIntentService extends TileService{
private static final String SERVICE_STATUS_FLAG = "serviceStatus";
private static final String PREFERENCES_KEY = "com.google.android_quick_settings";
#Override
public void onClick() {
updateTile();
boolean isCurrentlyLocked = this.isLocked();
if (!isCurrentlyLocked) {
Resources resources = getApplication().getResources();
Tile tile = getQsTile();
String tileLabel = tile.getLabel().toString();
String tileState = (tile.getState() == Tile.STATE_ACTIVE) ?
resources.getString(R.string.service_active) :
resources.getString(R.string.service_inactive);
Intent intent = new Intent(getApplicationContext(),
ResultActivity.class);
intent.putExtra(ResultActivity.RESULT_ACTIVITY_NAME_KEY,
tileLabel);
intent.putExtra(ResultActivity.RESULT_ACTIVITY_INFO_KEY,
tileState);
startActivityAndCollapse(intent);
}
}
private void updateTile() {
Tile tile = this.getQsTile();
boolean isActive = getServiceStatus();
Icon newIcon;
String newLabel;
int newState;
if (isActive) {
newLabel = String.format(Locale.US,
"%s %s",
getString(R.string.tile_label),
getString(R.string.service_active));
newIcon = Icon.createWithResource(getApplicationContext(), ic_android_black_24dp);
newState = Tile.STATE_ACTIVE;
} else {
newLabel = String.format(Locale.US,
"%s %s",
getString(R.string.tile_label),
getString(R.string.service_inactive));
newIcon =
Icon.createWithResource(getApplicationContext(),
android.R.drawable.ic_dialog_alert);
newState = Tile.STATE_INACTIVE;
}
tile.setLabel(newLabel);
tile.setIcon(newIcon);
tile.setState(newState);
tile.updateTile();
}
private boolean getServiceStatus() {
SharedPreferences prefs =
getApplicationContext()
.getSharedPreferences(PREFERENCES_KEY,
MODE_PRIVATE);
boolean isActive = prefs.getBoolean(SERVICE_STATUS_FLAG, false);
isActive = !isActive;
prefs.edit().putBoolean(SERVICE_STATUS_FLAG, isActive).apply();
return isActive;
}
}
Result.java
public class ResultActivity extends AppCompatActivity {
public static final String RESULT_ACTIVITY_INFO_KEY = "resultActivityInfo";
public static final String RESULT_ACTIVITY_NAME_KEY = "resultActivityName";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
if (getIntent() != null) {
Bundle extras = getIntent().getExtras();
assert extras != null;
String tileState = extras.getString(RESULT_ACTIVITY_INFO_KEY);
String tileName = extras.getString(RESULT_ACTIVITY_NAME_KEY);
TextView outputText = findViewById(R.id.result_info);
outputText.setText(String.format(Locale.US,
getString(R.string.result_output),
tileName,
tileState));
TextView returnHome = findViewById(R.id.result_return_main);
returnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goHome = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(goHome);
}
});
}
}
}
This code works fine on other devices. However, there is an issue in one plus quick setting menu as its observed and brought to notice. Check the below link to verify,
https://forums.oneplus.net/threads/android-oreo-8-0-oxigenos-quick-settings-bug.690621/

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.

How to use facebook login from a sub activity instead mainactivity

I am kind of new to all these integrations of facebook and android SDKs.
I followed the beginners tutorials from facebook developers to perform a login and it worked,
but when i combined it with my application it didn't work from the following reason:
In my project i wrote a calling from the main activity to another Fragmentactivity (FBProfile) which is calling the login fragment.
After facebook's authentication it is returned to OnResume in MainActivity instead the overided onActivityresult inside LoginFragment.
I need to create this flow (if its possible):
MainActivity->FBProfile(FragmentActivity)->LoginFragment->Facebook->LoginFragment
The activity that is called by MainActivity:
public class FBProfile extends FragmentActivity{
private LoginFragment loginfragment;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
Log.i(" Facebook: ", "FBProfile->OnCreate");
if(savedInstanceState==null)
{
loginfragment=new LoginFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, loginfragment).commit();
}
else
{
loginfragment=(LoginFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
}
}
The LoginFragment which is called from FBProfile:
public class LoginFragment extends Fragment {
private View login_view;
private boolean isResumed = false;
private static final String TAG="LoginFragment";
private UiLifecycleHelper uihelper;
private LoginButton authbutton;
private TextView userInfoTextView;
private Session.StatusCallback callback=new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
// TODO Auto-generated method stub
onSessionStatechange(session, state, exception);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.i(" Facebook: ", "FBProfile->OnCreate->LoginFragment");
login_view=inflater.inflate(R.layout.profilepage, container,false);
userInfoTextView = (TextView) login_view.findViewById(R.id.userInfoTextView);
authbutton=(LoginButton) login_view.findViewById(R.id.login_button);
authbutton.setFragment(this);
authbutton.setReadPermissions(Arrays.asList("public_profile","email","user_birthday"));
return login_view;
}
#SuppressWarnings("deprecation")
private void onSessionStatechange(Session session,SessionState state,Exception exception)
{
if (isResumed) {
if (session != null && session.isOpened()) {
Intent intent = new Intent(getActivity(),
FBProfile.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
if(state.isOpened()){
Log.i(" Facebook: ", "LOGGED IN....");
userInfoTextView.setVisibility(View.VISIBLE);
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if (user != null) {
// Display the parsed user info
userInfoTextView.setText(buildUserInfoDisplay(user));
}
}
});
Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_LONG).show();
}
else
{
userInfoTextView.setVisibility(View.INVISIBLE);
if (Session.getActiveSession() != null) {
Session.getActiveSession().closeAndClearTokenInformation();
}
Session.setActiveSession(null);
Toast.makeText(getActivity(), "Logged Out", Toast.LENGTH_LONG).show();
Log.i(" Facebook: ", "LOGGED OUT....");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
uihelper=new UiLifecycleHelper(getActivity(), callback);
uihelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Session session=Session.getActiveSession();
if((session!=null)&&(session.isOpened()||session.isClosed()))
{
onSessionStatechange(session, session.getState(), null);
}
isResumed = true;
uihelper.onResume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
uihelper.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
uihelper.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
uihelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("LoginFragment: ","onActivityResult Called");
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
/**
*
* #param user
* #return
*/
private String buildUserInfoDisplay(GraphUser user) {
StringBuilder userInfo = new StringBuilder("");
// Example: typed access (name)
// - no special permissions required
userInfo.append(String.format("Name: %s\n\n",
user.getName()));
// Example: typed access (birthday)
// - requires user_birthday permission
userInfo.append(String.format("Birthday: %s\n\n",
user.getBirthday()));
// Example: partially typed access, to location field,
// name key (location)
// - requires user_location permission
// userInfo.append(String.format("Location: %s\n\n",
// user.getLocation().getProperty("name")));
// Example: access via property name (locale)
// - no special permissions required
// userInfo.append(String.format("Locale: %s\n\n",
// user.getProperty("locale")));
// Example: access via key for array (languages)
// - requires user_likes permission
JSONArray languages = (JSONArray)user.getProperty("languages");
if (languages.length() > 0) {
ArrayList<String> languageNames = new ArrayList<String> ();
for (int i=0; i < languages.length(); i++) {
JSONObject language = languages.optJSONObject(i);
// Add the language name to a list. Use JSON
// methods to get access to the name field.
languageNames.add(language.optString("name"));
}
userInfo.append(String.format("Languages: %s\n\n",
languageNames.toString()));
}
return userInfo.toString();
}
}
Part of my manifest settings:
<uses-sdk android:minSdkVersion="14"
android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/APP_FB_ID"/>
<activity
android:name=".Splash"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:noHistory="false"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEAFULT" />
</intent-filter>
</activity>
Solved. In the Menifast the fragment's father activity was set on nohistory.
I changed it to false and it was solved.

Categories

Resources