- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试连接到 firebase 以获取 display_name 和 profile_photo对于我的帖子,例如 Instagram像这个 example image但是当我运行我的应用程序时,它说我的变量上有 nullPointerExceptionmUserAccountSettings 导致我的应用程序无法运行 onDataChanged() 或 onDataCancelled()功能。
我已经尝试从 Profile 类的 mUserAccountSettings 获取数据,实际上它工作得很好,但在 ViewFragment 类中它不起作用
它说:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.jesslyn.foodylife, PID: 5655 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings.getProfile_photo()' on a null object reference at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.setupWidgets(ViewPostFragment.java:156) at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.onCreateView(ViewPostFragment.java:117) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595) at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149) at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710) at android.os.Handler.handleCallback(Handler.java:742) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:5544) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) E/MQSEventManagerDelegate: failed to get MQSService.
这是我在 ViewFragment 类中的代码:
package com.example.jesslyn.foodylife.FoodyLife.Utils;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.LoginFilter;
import android.util.EventLogTags;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.example.jesslyn.foodylife.FoodyLife.Utils.BottomNavigationViewHelper;
import com.example.jesslyn.foodylife.FoodyLife.Utils.FirebaseMethods;
import com.example.jesslyn.foodylife.FoodyLife.Utils.GridImageAdapter;
import com.example.jesslyn.foodylife.FoodyLife.Utils.SquareImageView;
import com.example.jesslyn.foodylife.FoodyLife.Utils.UniversalImageLoader;
import com.example.jesslyn.foodylife.FoodyLife.models.Photo;
import com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings;
import com.example.jesslyn.foodylife.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GetTokenResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import junit.framework.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.Executor;
/**
* Created by Jesslyn on 12/4/2017.
*/
public class ViewPostFragment extends Fragment {
private static final String TAG = "ViewPostFragment";
private SquareImageView mPostImage;
private BottomNavigationViewEx bottomNavigationViewEx;
private TextView mBackLabel, mCaption, mUsername, mTimeStamp;
private ImageView mBackArrow, mEllipses, mProfileImage;
private RatingBar mStars;
private String photoUrl;
private Photo mPhoto;
private int mActivityNumber = 0;
private String photoUsername = "";
private String profilePhotoUrl = "";
private UserAccountSettings mUserAccountSettings;
// firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
private String userID;
public ViewPostFragment() {
super();
setArguments(new Bundle());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_post, container, false);
mPostImage = (SquareImageView) view.findViewById(R.id.post_image);
bottomNavigationViewEx = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mBackArrow = (ImageView) view.findViewById(R.id.backArrow);
mBackLabel = (TextView) view.findViewById(R.id.tvBackLabel);
mCaption = (TextView) view.findViewById(R.id.image_caption);
mUsername = (TextView) view.findViewById(R.id.username);
mTimeStamp = (TextView) view.findViewById(R.id.image_time_posted);
mEllipses = (ImageView) view.findViewById(R.id.iv_ellipses);
mStars = (RatingBar) view.findViewById(R.id.ratingBar);
mStars.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RatingBar bar = (RatingBar) v;
Log.d(TAG,"VALUE IS : "+bar.getRating()+" **************************************************");
}
});
mStars.setRating(0);
mProfileImage = (ImageView) view.findViewById(R.id.profile_photo);
try {
mPhoto = getPhotoFromBundle();
UniversalImageLoader.setImage(mPhoto.getImage_path(), mPostImage, null, "");
} catch (NullPointerException e) {
Log.e(TAG, "onCreateView NullPointerException : " + e.getMessage());
}
setupBottomNavigationView();
setupFirebaseAuth();
getPhotoDetails();
setupWidgets();
return view;
}
private void getPhotoDetails(){
Log.d(TAG, "getPhotoDetails: retrieving photo details.");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_account_settings))
.orderByChild(getString(R.string.field_user_id))
.equalTo(mPhoto.getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: ");
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: " +singleSnapshot.getValue().toString());
mUserAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
Log.d(TAG, "onDataChange: "+mUserAccountSettings.getUsername());
}
setupWidgets();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
private void setupWidgets(){
String timestampDiff = getTimeStampDifference();
if(!timestampDiff.equals("0")){
mTimeStamp.setText(timestampDiff + " DAYS AGO");
}else{
mTimeStamp.setText("TODAY");
}
UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
mUsername.setText(mUserAccountSettings.getUsername());
}
//get how many days ago of post
private String getTimeStampDifference() {
Log.d(TAG, "getTimeStampDifference : getting time difference");
String difference = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss'Z'", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));
Date timestamp;
Date today = c.getTime();
sdf.format(today);
final String photoTimestamp = mPhoto.getDate_created();
try {
timestamp = sdf.parse(photoTimestamp);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
} catch (ParseException e) {
Log.e(TAG, "PARSE EXCEPTION : " + e.getMessage());
difference = "0";
}
return difference;
}
private int getActivityFromBundle() {
Log.d(TAG, "getActivityFromBundle arguments : " + getArguments());
Bundle bundle = this.getArguments();
if (bundle != null) {
return bundle.getInt(getString(R.string.activity_number));
} else {
return 0;
}
}
private Photo getPhotoFromBundle() {
Log.d(TAG, "getPhotoFromBundle arguments : " + getArguments());
Bundle bundle = this.getArguments();
if (bundle != null) {
return bundle.getParcelable(getString(R.string.photo));
} else {
return null;
}
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(getActivity(), getActivity(), bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(mActivityNumber);
menuItem.setChecked(true);
}
/**
* ----------------------------------Firebase stuffs-----------------------------------------
*/
//setup the firebase auth obj
private void setupFirebaseAuth() {
Log.d(TAG, "setupFirebaseAuth : setting up firebase auth");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//user is signed in
Log.d(TAG, "user is signed in" + user.getUid());
} else {
//user is signed out
Log.d(TAG, "onAuthStateChanged : signed out");
}
}
};
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
最佳答案
这是因为变量mUserAccountSettings
是在onDataChange()
方法中初始化的,该方法是一个回调,并且是异步执行的。在此之前,它初始化了您的主线程,并尝试在 setupWidgets()
一个可能的修复方法是将以下代码从 setupWidgets()
移动到 onDataChange()
。
UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
注意:这并不是为了向您展示任何最佳实践。这个解决方案只是为了表明所有依赖于服务器值的 UI 更新都应该在您从服务器获得响应时发生。
关于java - query.addListenerForSingleValueEvent 不会运行...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47695387/
以下哪一个更好(EJB 3 JPA) //查询 一个)。 getEntityManager().createQuery("select o from User o"); //命名查询,其中 findA
也许其他人和我有同样的问题。我遇到了错误: Cannot execute queries while other unbuffered queries are active.Consider usin
我的代码 package com.tl666.elasticsearch.pojo; import lombok.AllArgsConstructor; import lombok.Data; imp
简短版:我想查询另一个查询的结果,以便选择更有限的结果集。但是,添加 where 子句会重写第一个查询而不是处理结果,因此我得不到我需要的答案。 详情:我有两个模型,支票和蜱虫。检查 has_many
我正在尝试使用 Doctrine 在 Symfony 框架中执行原始查询。 这是代码: class MessagesHandler { /** @var \Doctrine\Common\Pe
我正在运行以下两个语句: 首先是 A) 它做它需要做的事情并工作: SELECT itemColumn ,valueColumn ,label FROM rstCombinedChartD
我有一个脚本来查询数据库以获取订单信息,然后查询该查询以获取订单总数。代码看起来像这样。 SELECT oi.OrderQty, oi.ItemPrice FROM Ord
这个问题在这里已经有了答案: MySQL Insert query doesn't work with WHERE clause (31 个答案) 关闭 4 年前。 我正在从 php 更新数据库中的
在使用 Skygear JS SDK 时,查询是否返回数组? readDummy: function(){ const Test = skygear.Record.extend('
我想在一个表上运行 MySQL 查询,然后在该表上运行子查询。我有一个对象列表。每个对象都有一个主要版本和一个次要版本。对于一个对象,我试图找到该对象的“最后版本”:这意味着我想找到该对象的最大值(主
我正在尝试在 pod 中启动 prometheus,并在 k8s 中使用持久卷。 当我启动 pod 时,我看到: level=info ts=2021-09-12T13:58:13.120Z ca
基本上,我从 kube-prometheus-stack 安装了 Prometheues-Grafana使用提供的 helm chart repo prometheus-community # hel
是否可以根据另一个查询的结果在 TFS 2010 中创建新查询? 例如,一个(父)查询选择位于某个工作项下的所有工作项(假设 ID=5 的工作项)。现在我想创建其他查询,从第一个查询的结果中选择所有错
在 Delphi 中,每当我使用 TQuery 对数据库执行 SELECT 时,我都会在 Query.Open 后面加上 try..finally,并在finally 部分中使用 Query.Clos
我只是从一台服务器移动到另一台服务器。我的脚本在旧服务器上运行良好,但是我开始在新服务器上收到此错误: "Declaration of ezSQL_mysql::query() should be c
我想问一下有什么区别 for row in session.Query(Model1): pass 和 for row in session.Query(Model1).all():
如何使用注释通过spring-data-elasticsearch进行@Query(value =“{” query“:”“}”)的聚合? 最佳答案 您不能使用@Query注释来完成此操作,该注释的唯
我有一个对可变字符串执行 LIKE 条件的查询: 当变量包含一个包含单引号的单词时,返回一些结果,但不是全部: SELECT ID FROM MyQoQ
我有我的查询范围,它返回数百条记录。我需要在 Controller 中使用不同的过滤器查询这个集合。 我怎样才能做到这一点?可能吗? 查询范围: Client::join('transactions_
我有这样的数据库模式 用户 编号 初中生 文档 编号 标题 user_id(用户的外键) 模式(可以接受 PUBLIC 或 PRIVATE) 我想检索所有公开的文档和属于给定用户(矩阵)的所有文档 我
我是一名优秀的程序员,十分优秀!