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.
Related
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.
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"/>
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/
I am trying to send a simple message from my wear [Emulator] to my android phone, The message should have been sent according to my logs on the wear but it does not trigger my "showToast" method on my phone [it should be triggered when a message is received]. Anyone has an idea what I could be doing wrong?
This is my Wear Manifest
<manifest package="georgikoemdzhiev.weartesttwo"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:name="android.hardware.type.watch"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<uses-library
android:name="com.google.android.wearable"
android:required="false"/>
<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>
This is my Mobile manifest
<manifest package="georgikoemdzhiev.weartesttwo"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<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>
<service android:name=".ReceiveMessageService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/prefix" />
</intent-filter>
</service>
</application>
This is my Wear logic [I have a button that sends the showToast message]
public class MainActivity extends WearableActivity {
private static final long CONNECTION_TIME_OUT_MS = 2500;
private static final String TAG = MainActivity.class.getSimpleName();
private CircularButton mSendButton;
private List<Node> myNodes = new ArrayList<>();
private static final SimpleDateFormat AMBIENT_DATE_FORMAT =
new SimpleDateFormat("HH:mm", Locale.UK);
private BoxInsetLayout mContainerView;
private TextView mTextView;
private TextView mClockView;
private GoogleApiClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAmbientEnabled();
mSendButton = (CircularButton)findViewById(R.id.sendToast);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendToastMessage();
}
});
mClient = new GoogleApiClient.Builder(this)
.addApiIfAvailable(Wearable.API)
.build();
getNodes();
mContainerView = (BoxInsetLayout) findViewById(R.id.container);
mTextView = (TextView) findViewById(R.id.text);
mClockView = (TextView) findViewById(R.id.clock);
}
private void sendToastMessage() {
Log.d(TAG,"Sending message... Nodes List size:" + myNodes.size());
// send toast message logic...
new Thread(new Runnable() {
#Override
public void run() {
for(Node n:myNodes) {
Log.d(TAG,"Sending message to node:"+n.getDisplayName());
Wearable.MessageApi.sendMessage(mClient,n.getId(),"/showToast",null);
}
}
});
}
private List<Node> getNodes(){
new Thread(new Runnable() {
//
#Override
public void run() {
Log.d(TAG,"Getting nodes...");
mClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
NodeApi.GetConnectedNodesResult result = Wearable.NodeApi.getConnectedNodes(mClient).await();
List<Node> nodes = result.getNodes();
for(Node n:nodes){
Log.d(TAG,"Adding Node: "+n.getDisplayName());
myNodes.add(n);
}
Log.d(TAG,"Getting nodes DONE!");
}
}).start();
return null;
}
}
This is my ReceiveMessageService in Mobile
public class ReceiveMessageService extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d("ReceiveMessageService","onMessageReceived");
//if(messageEvent.getPath().equals("/showToast")) {
showToast(messageEvent.getPath());
//}
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
This is my MainActivity in Mobile
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private static final String TAG = MainActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG,"onConnected");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG,"onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"onConnectionFailed");
}
It looks like you are using wrong pathPrefix in your mobile side AndroidManifest. Try to replace
<data android:scheme="wear" android:host="*" android:pathPrefix="/prefix" />
with
<data android:scheme="wear" android:host="*" android:pathPrefix="/showToast" />
Edit
Also keep in mind that MessageApi is not guarantee to deliver a message even if it returns a successful result code as Google's document stated:
Note: A successful result code does not guarantee delivery of the message. If your app requires data reliability, use DataItem objects or the ChannelApi class to send data between devices.
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!