Receive Images from another app to our app - android

So when I am in other media apps like google photos I select an image and click the share button then in the share window I want my app to be displayed so that i can click it and get that image to my app.
I have build a simple chat application where users can send text and images to each other where all the data is stored in Firebase.
So when one clicks my app in the sharing screen the image should take me to the Chat activity where i have all my chats so that i click one of my chats and the image is then sent to them.
So how to achieve this process?I have searched everywhere and couldn't get the hang of the right tutorial all i am finding is sharing data from our app and not from other app to our app.
Thank you.
Edit : I have created a separate activity that should be launched when a user choses to share a image from other app.But when i click my app in the sharing menu then my app goes all white screen instead of launching the SharingActivity.
Below is my code and manifest file.
SharingActivity.java
package com.pappu5.navigation;
public class SharingActivity extends AppCompatActivity {
FirebaseRecyclerAdapter<FriendsData, SharingActivity.ShareHolder> frv;
private RecyclerView rv;
private DatabaseReference dr, drUsers;
private FirebaseAuth auth;
private String user;
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
rv = (RecyclerView) findViewById(R.id.friendsView);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser().getUid();
dr = FirebaseDatabase.getInstance().getReference().child("Friends_Formed").child(user);
drUsers = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles");
dr.keepSynced(true);
drUsers.keepSynced(true);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Query personsQuery = dr.orderByKey();
FirebaseRecyclerOptions<FriendsData> options =
new FirebaseRecyclerOptions.Builder<FriendsData>().setLifecycleOwner(this)
.setQuery(personsQuery, FriendsData.class)
.build();
frv = new FirebaseRecyclerAdapter<FriendsData, SharingActivity.ShareHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final SharingActivity.ShareHolder holder, int position, #NonNull FriendsData model) {
holder.setDate(model.getDate());
holder.setImage(model.getThumb_image());
final String listUsers = getRef(position).getKey();
if (!listUsers.equals(null))
drUsers.child(listUsers).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String username = dataSnapshot.child("name").getValue().toString();
String thumb = dataSnapshot.child("thumb_image").getValue().toString();
//String online = dataSnapshot.child("onlineStatus").getValue().toString();
if (dataSnapshot.hasChild("onlineStatus")) {
String userOnline = dataSnapshot.child("onlineStatus").getValue().toString();
holder.setOnlineStatus(userOnline);
}
holder.setName(username);
holder.setImage(thumb);
//holder.setOnlineStatus(online);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence[] actions = new CharSequence[]{"Share to " + username};
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Select an Action");
builder.setItems(actions, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
intent.putExtra("id", listUsers);
intent.putExtra("user_name", username);
startActivity(intent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public SharingActivity.ShareHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.friends_status, parent, false);
return new SharingActivity.ShareHolder(view);
}
};
rv.setAdapter(frv);
}
public static class ShareHolder extends RecyclerView.ViewHolder {
View view;
public ShareHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setDate(String date) {
TextView username = (TextView) view.findViewById(R.id.status2);
username.setText(date);
}
public void setImage(String image) {
CircleImageView thumb = (CircleImageView) view.findViewById(R.id.circleImageView2);
Picasso.get().load(image).placeholder(R.drawable.default_avatar).into(thumb);
}
public void setName(String name) {
TextView username = (TextView) view.findViewById(R.id.name2);
username.setText(name);
}
public void setOnlineStatus(String onlineStatus) {
ImageView image = (ImageView) view.findViewById(R.id.onlineStatus);
if (onlineStatus.equals("true")) {
image.setVisibility(View.VISIBLE);
} else {
image.setVisibility(View.INVISIBLE);
}
}
}
}
AndroidManifest.xml
<activity android:name=".SharingActivity">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>

You have to add below code inside Manifest.xml under activity tag like
<activity
android:name=".MainActivity"
android:configChanges="orientation"
android:noHistory="true"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
// below code with show your app as sharing option
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
You can change mimeType according to your need.
Hope this will help you.

Related

With support library 27.1.1, when i start an activity my app freezes

I'm trying to update the compileSDKVersion to 27, so I also changed the support library to 27.1.1.
Now my app starts as always but when I try to start a new activity the app freezes.
It also freezes when resuming after the background mode.
Some code:
HomeActivity
This is the first activity that works, freeze only if resumed after background
public class HomeActivity extends BaseActivity implements SharedPreferences.OnSharedPreferenceChangeListener,
FirebaseUpdaterController.Listener{
private static final String TAG = "HomeActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null) { // first opened
savedInstanceState = getIntent().getExtras();
}
if (savedInstanceState != null && savedInstanceState.getString(COUPLE_UID) != null) {
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.PARTNER_UID, savedInstanceState.getString(PARTNER_UID));
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.PARTNER_USERNAME, savedInstanceState.getString(PARTNER_USERNAME));
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.PARTNER_IMAGE_URI, savedInstanceState.getString(PARTNER_IMAGE_URI));
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.COUPLE_UID, savedInstanceState.getString(COUPLE_UID));
super.updateRepositories();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
Utility.askStoragePermission(this);
if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(MULTI_COUPLE_NOTIFICATIONS)) {
BottomSheetDialogFragment bottomSheetDialogFragment = new ChangeCoupleBottomSheetDialogFragment();
//show it
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
}
mToolbar = (Toolbar) findViewById(R.id.home_toolbar);
mToolbar.getBackground().setAlpha(0);
mToolbar.getLayoutParams().height = UtilisGraphic.getStatusBarHeight(this) + (int) getResources().getDimension(R.dimen.app_bar_height);
mToolbar.setPadding(0, UtilisGraphic.getStatusBarHeight(this), 0, 0);
mToolbar.requestLayout();
setSupportActionBar(mToolbar);
mFirebaseSuggestionsController = new FirebaseSuggestionsController(
mUserUid,
Utility.getStringPreference(getApplicationContext(), SharedPrefKeys.USERNAME),
Utility.getStringPreference(getApplicationContext(), SharedPrefKeys.DEBUG)
);
mFirebaseUpdaterController = new FirebaseUpdaterController(
mUserUid,
Utility.getStringPreference(getApplicationContext(), SharedPrefKeys.DEBUG)
);
mFirebaseUpdaterController.setListener(this);
mDialog =
new MaterialDialog.Builder(this)
.iconRes(R.drawable.suggestions_icon)
.limitIconToDefaultSize()
.title(R.string.questioner_dialog_title)
.customView(R.layout.custom_dialog_suggestions, true)
.positiveText(R.string.affermative_suggestions_dialog)
.negativeText(R.string.negative_suggestions_dialog)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
suggestionText = suggestionInput.getText().toString();
sendSuggestions(selectedRadio, suggestionText);
Utility.saveBooleanPreference(getApplicationContext(), SharedPrefKeys.SUGGESTION_SENT, true);
mMenu.findItem(R.id.menu_suggestions).setVisible(false);
}
})
.build();
positiveActionSuggestion = mDialog.getActionButton(DialogAction.POSITIVE);
suggestionInput = (EditText) mDialog.getCustomView().findViewById(R.id.suggestion_input_edittex);
suggestionInput.setVisibility(View.GONE);
suggestionInput.addTextChangedListener(
new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveActionSuggestion.setEnabled(s.toString().trim().length() > 5);
}
#Override
public void afterTextChanged(Editable s) {}
});
RadioGroup radioGroup = (RadioGroup) mDialog.getCustomView().findViewById(R.id.myRadioGroup);
radioGroup.check(R.id.radio_0);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId)
{
case R.id.radio_0:
selectedRadio = 0;
suggestionInput.setVisibility(View.GONE);
suggestionInput.clearFocus();
break;
case R.id.radio_1:
selectedRadio = 1;
suggestionInput.setVisibility(View.GONE);
suggestionInput.clearFocus();
break;
case R.id.radio_2:
selectedRadio = 2;
suggestionInput.setVisibility(View.GONE);
suggestionInput.clearFocus();
break;
case R.id.radio_other:
selectedRadio = 3;
suggestionInput.setVisibility(View.VISIBLE);
suggestionInput.requestFocus();
if(suggestionInput.getText().length() < 6) {
positiveActionSuggestion.setEnabled(false);
}
break;
}
}
});
mView = (HomeFragment) getSupportFragmentManager()
.findFragmentById(R.id.home_fragment_container);
if (mView == null) {
mView = HomeFragment.newInstance(getIntent().getExtras());
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.home_fragment_container, mView);
transaction.commit();
}
}
#Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
Intent intent = getIntent();
if(intent.getStringExtra(URI) != null){
mUri = Uri.parse(intent.getStringExtra(URI));
ChatRepository.getInstance(getApplicationContext()).setUriImportWa(mUri);
intent.removeExtra(URI);
//changePageTo(DashboardPagerAdapter.HOME_TAB);
}
}}
BaseActivity
All activities extend this base class
public class BaseActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
SharedPreferences.OnSharedPreferenceChangeListener,
GoogleApiClient.ConnectionCallbacks,
ForceUpdateChecker.OnUpdateNeededListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
// set in-app defaults
Map<String, Object> remoteConfigDefaults = new HashMap();
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_REQUIRED, false);
remoteConfigDefaults.put(ForceUpdateChecker.KEY_CURRENT_VERSION, "1.0.0");
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_URL,
"https://google.com");
firebaseRemoteConfig.setDefaults(remoteConfigDefaults);
firebaseRemoteConfig.fetch(MINUTE_TO_FETCH) // fetch every minutes
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(BASE_TAG, "remote config is fetched.");
firebaseRemoteConfig.activateFetched();
}
}
});
// Getting utils data for all activity
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(sp.getBoolean(SharedPrefKeys.USER_RELATIONSHIP_STATUS_CHANGED, false)){
checkUserRelationshipStatus();
}
mUserUid = sp.getString(SharedPrefKeys.USER_UID, SharedPrefKeys.DEFAULT_VALUE);
mCoupleUid = sp.getString(SharedPrefKeys.COUPLE_UID, mUserUid);
if(MainActivity.apiServiceAmazon == null){
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofitAmazon = new Retrofit.Builder()
.baseUrl(BASE_URL_AMAZON_EB)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
MainActivity.apiServiceAmazon = retrofitAmazon.create(ServerApiAmazonInterface.class);
Retrofit retrofitCloud = new Retrofit.Builder()
.baseUrl(BASE_URL_CLOUD_FUNCTION)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
MainActivity.apiServiceCloud = retrofitCloud.create(ServerApiCloudFunctionInterface.class);
}
if (MainActivity.db == null) {
MainActivity.db = Room.databaseBuilder(getApplicationContext(),
SweetieDatabase.class, "DB").fallbackToDestructiveMigration().build();
}
/* Setup the Google API object to allow Google logins */
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_ID))
.requestEmail()
.build();
/* Setup the Google API object to allow Google+ logins */
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.enableAutoManage(this, this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(LocationServices.API)
.build();
mFirebaseAuth = FirebaseAuth.getInstance();
}
HomeFragment
Fragment where i start other activities that freeze the app.
public class HomeFragment extends Fragment implements LifecycleOwner, SweetboxCardAdapter.SweetboxCardAdapterListener, SweetBoxReadScanner.onCounter, ChooseCoupleAdapter.ChooseCoupleAdapterListener {
public static HomeFragment newInstance(Bundle bundle) {
HomeFragment newHomeFragment = new HomeFragment();
newHomeFragment.setArguments(bundle);
return newHomeFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
mAnimShow = AnimationUtils.loadAnimation( getContext(), R.anim.slide_in_left);
mAnimShowFadeIn = AnimationUtils.loadAnimation( getContext(), R.anim.fade_in);
mAnimscaleIn = AnimationUtils.loadAnimation(getContext(),R.anim.scale_up);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
root = inflater.inflate(R.layout.home_layout_scrollable, container, false);
mCustomView = inflater.inflate(R.layout.import_progress_dialog_view,null);
mCompleteImportCustomView = inflater.inflate(R.layout.import_complete_dialog_view, null);
mCompleteImportCustomView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCompleteImportDialog.dismiss();
}
});
mTitleTextView = (EmojiconTextView) root.findViewById(R.id.action_item_title);
mDiaryDescription = (TextView) root.findViewById(R.id.sweetbox_card_description_view);
mDescriptionTextView = (EmojiconTextView) root.findViewById(R.id.action_item_subtitle);
mDateTextView = (TextView) root.findViewById(R.id.action_item_date);
mAppBarImageView = (CircleImageView) root.findViewById(R.id.app_bar_image_view);
mAppBarImageView.setVisibility(View.GONE);
mNoAppBarImageTextView = (TextView) root.findViewById(R.id.app_bar_no_image_text);
mNoAppBarImageTextView.setVisibility(View.GONE);
mHeartOff = root.findViewById(R.id.sweetbox_card_heart_off);
mFullHeart = root.findViewById(R.id.sweetbox_card_full_heart);
mAppBarExtension = root.findViewById(R.id.toolbar);
mAppBarExtension.getLayoutParams().height =(int) UtilisGraphic.dpToPx(50, getContext()) + UtilisGraphic.getStatusBarHeight(getContext());
mAppBarExtension.requestLayout();
mAvatarImageView = (ImageView) root.findViewById(R.id.image_action_list_item);
mNoImageTextView = (TextView) root.findViewById(R.id.action_no_image_text);
mTypeIcon = (ImageView) root.findViewById(R.id.action_item_type);
mNotificCounter = (TextView) root.findViewById(R.id.action_item_notification_counter);
avatarClickZone = (View) root.findViewById(R.id.avatar_click_zone);
actionClickZone = (View) root.findViewById(R.id.action_click_zone);
mChangeCoupleFab = (FloatingActionButton) root.findViewById(R.id.change_couple_fab);
mChangeCoupleFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomSheetDialogFragment bottomSheetDialogFragment = ChangeCoupleBottomSheetDialogFragment.getInstance(getActivity());
//show it
bottomSheetDialogFragment.show(getActivity().getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
}
});
mDiaryCard = (CardView) root.findViewById(R.id.diary_card_view);
mDiaryCard.setVisibility(View.GONE);
mChatCard = (CardView) root.findViewById(R.id.chat_card_view);
mChatCard.setVisibility(View.GONE);
mCardStackView = (SwipeFlingAdapterView) root.findViewById(R.id.home_sweetbox_recycler_view);
mArrayList = new ArrayList<MessageVM>();
mSweetboxAdapter = new SweetboxCardAdapter(getContext());
mCardStackView.setAdapter(mSweetboxAdapter);
mSweetboxAdapter.setListener(this);
mCardStackView.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
}
#Override
public void onLeftCardExit(Object dataObject) {
mHeartOff.startAnimation(mAnimscaleIn);
MessageVM messageVM = (MessageVM) dataObject;
ChatRepository.getInstance(getContext()).discardMessage(messageVM, MessageVM.TEXT_MSG);
}
#Override
public void onRightCardExit(Object dataObject) {
mFullHeart.startAnimation(mAnimscaleIn);
MessageVM messageVM = (MessageVM) dataObject;
messageVM.setBookmarked(true);
ChatRepository.getInstance(getContext()).bookmarkMessage(messageVM, MessageVM.TEXT_MSG);
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
}
#Override
public void onScroll(float v) {
}
});
mHomeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
createObservers();
setupAppBar();
setupChatCard();
setupDiaryCard();
return root;
}
#Override
public void onResume() {
super.onResume();
if(ChatRepository.getInstance(getContext()).isImportWa()){
mUri = ChatRepository.getInstance(getContext()).getUriImportWa();
mFileName = "cache_file.txt";
try {
mTextFileStream = new DataInputStream(getContext().getContentResolver().openInputStream(mUri));
File file = new File(getContext().getCacheDir(), mFileName);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[1024]; // or other buffer size
int read;
while ((read = mTextFileStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
mTextFileStream.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
if(mTextFileStream != null) {
mUri = null;
((HomeActivity)getActivity()).clearUri();
ChatRepository.getInstance(getContext()).clearUriImportWa();
mDialog = new MaterialDialog.Builder(getContext())
.title(R.string.where_import)
// second parameter is an optional layout manager. Must be a LinearLayoutManager or GridLayoutManager.
.adapter(new ChooseCoupleAdapter(getContext(),this), new GridLayoutManager(getActivity(),3))
.build();
mDialog.show();
} else {
Log.d(TAG, "Can't open the uri");
}
}
}
private void setupChatCard() {
final String coupleUid = Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID);
String userUid = Utility.getStringPreference(getContext(), SharedPrefKeys.USER_UID);
mTitleText = getString(R.string.personal_messages);
if(!userUid.equals(coupleUid)){
mTitleText = Utility.getStringPreference(getContext(),SharedPrefKeys.PARTNER_USERNAME);
}
mTitleTextView.setText(mTitleText);
mHomeViewModel.getMainChatDate(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatDateObserver);
mHomeViewModel.getMainChatDescription(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatDescriptionObserver);
mHomeViewModel.getMainChatImage(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatImageObserver);
mHomeViewModel.getMainChatNotificCounter(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatNotificCounterObserver);
avatarClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if in couples
if(coupleUid != null && !coupleUid.equals(Utility.getStringPreference( getContext(),SharedPrefKeys.USER_UID))){
startActivity(new Intent(getActivity(), CoupleDetailsActivity.class));
}else{
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(ChatActivity.ACTION_DATABASE_KEY, coupleUid);
startActivity(intent);
}
}
});
actionClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(ChatActivity.ACTION_DATABASE_KEY, coupleUid);
animateChatIntent(mChatCard, intent);
}
});
mChatCard.setVisibility(View.VISIBLE);
mChatCard.startAnimation(mAnimShow);
}
Manifest
<application
android:name=".MyApplication"
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 -->
<activity android:name=".MainActivity"
android:theme="#style/AppTheme"
android:launchMode="singleTask"
android:screenOrientation="sensorPortrait" >
<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.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
<data android:mimeType="*/*"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
<data android:mimeType="*/*"/>
</intent-filter>
</activity>
<activity android:name=".tutorial.InitTutorialActivity"
android:theme="#style/ChatTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".login.LoginActivity"
android:theme="#style/ChatTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".registration.RegistrationActivity"
android:theme="#style/ChatTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".pairing.PairingActivity"
android:parentActivityName=".home.HomeActivity"
android:theme="#style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
</activity>
<activity android:name=".chatMVVM.ChatActivity"
android:parentActivityName=".home.HomeActivity"
android:theme="#style/ChatTheme"
android:windowSoftInputMode="adjustResize"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
<intent-filter>
<action android:name="open_chat_intent_filter" />
</intent-filter>
</activity>
<activity android:name=".couple.CoupleActivity"
android:parentActivityName=".home.HomeActivity"
android:noHistory="true"
android:theme="#style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
</activity>
<activity android:name=".couple.CoupleDetailsActivity"
android:theme="#style/AppTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".settings.SettingsActivity"
android:parentActivityName=".home.HomeActivity"
android:theme="#style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
</activity>
<activity android:name=".chatMVVM.ChatInfoActivity"
android:parentActivityName=".chatMVVM.ChatActivity"
android:theme="#style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".chatMVVM.ChatActivity"/>
</activity>
<activity android:name=".home.HomeActivity"
android:theme="#style/HomeTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".diaryMVVM.DiaryActivity"
android:theme="#style/AppTheme"
android:screenOrientation="sensorPortrait"/>

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/

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.

Opening android deep links from app

I am implementing deep links inside my app and could not find a way, or example about opening them from inside my own app. For example: I wish that opening certain banner would open myapp://game/1 link which would lead to another activity inside my app. How can I do that ?
In the manifest you should register the deep linking scheme.
<activity android:name=".DeepLinkingActivity"
android:configChanges="orientation|screenSize" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="myapp" />
</intent-filter>
</activity>
With this the DeepLinkingActivity will open when the the link with the defined scheme is clicked. And in the activity handle what to do:
private final String GAME_LINK = "game";
private final String VIDEO_LINK = "video";
private static String PASSED_LINK = "PassedLink";
public static Intent createIntent(String link, Context context) {
Intent intent = new Intent(context, DeepLinkingActivity.class);
intent.putExtra(PASSED_LINK, link);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
String host;
String link = getIntent().getStringExtra(PASSED_LINK);
if(TextUtils.isEmpty(link)) {
Intent intent = getIntent();
if (intent.getData() != null) {
Uri data = intent.getData();
host = data.getHost();
} else {
// No links
}
} else {
Uri data = Uri.parse(link);
host = data.getHost();
}
if(host.equals(GAME_LINK)) {
// myapp://game/
// Do something
} else if(host.equals(VIDEO_LINK)){
// myapp://video/
// Do something
} else {
// Do something
}
...
}
Then you can call from your widget:
widget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(DeepLinkingActivity.createIntent("linik_for_this_wiget"), getContext());
}
});
If you have links in WebView you could also override shouldOverrideUrlLoading

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