2015-11-08 10 views
-3

Я работаю над приложением, которое не показывает мне никаких ошибок и работает нормально, но после второго просто сработает, я пробовал все, но не смог найти ошибку (будучи новой) скажи мне, где я делаю не так, какПриложение аварийно завершает работу через несколько секунд

LogCat

11-08 12:57:16.011 5886-5886/com.koshur.socialnetwork E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: com.koshur.socialnetwork, PID: 5886 
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.koshur.socialnetwork.adapters.HomeListAdapter.setPosts(java.util.List)' on a null object reference 
      at com.koshur.socialnetwork.activities.ProfilePreview.updateView(ProfilePreview.java:334) 
      at com.koshur.socialnetwork.activities.ProfilePreview.access$300(ProfilePreview.java:42) 
      at com.koshur.socialnetwork.activities.ProfilePreview$5.success(ProfilePreview.java:308) 
      at com.koshur.socialnetwork.activities.ProfilePreview$5.success(ProfilePreview.java:300) 
      at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45) 
      at android.os.Handler.handleCallback(Handler.java:739) 
      at android.os.Handler.dispatchMessage(Handler.java:95) 
      at android.os.Looper.loop(Looper.java:135) 
      at android.app.ActivityThread.main(ActivityThread.java:5293) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 

Java класс

public class ProfilePreview extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener { 
public TextView userProfileName, 
     userTotalFollowers, 
     userTotalPosts, 
     userProfileAddress, 
     userProfileJob, 
     followProfileBtn, 
     contactProfileBtn, 
     userPostsBtn; 
public userItem user; 
public RecyclerView postsList; 
public LinearLayoutManager layoutManager; 
int currentPage = 1; 
private HomeListAdapter mHomeListAdapter; 
private SwipeRefreshLayout mSwipeRefreshLayout; 
public ImageView userProfilePicture, userProfileCover; 
public LinearLayout actionProfileArea; 
public int userID = 0; 
private CacheManager mCacheManager; 
private ThinDownloadManager downloadManager; 

private Gson mGson; 
LoadingView loginLoadingView; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if (M.getToken(this) == null) { 
     Intent mIntent = new Intent(this, LoginActivity.class); 

     startActivity(mIntent); 
     finish(); 

    } else { 
     setContentView(R.layout.activity_profile_preview); 
     initializeView(); 
     loginLoadingView = (LoadingView)findViewById(R.id.loginLoadingView); 
     if (getIntent().hasExtra("userID")) { 
      userID = getIntent().getExtras().getInt("userID"); 
     } 
     mCacheManager = CacheManager.getInstance(getApplicationContext()); 

     mGson = new Gson(); 
     getUser(); 
     getPosts(); 
    } 

} 

private void initializeView() { 
    downloadManager = new ThinDownloadManager(AppConst.DOWNLOAD_THREAD_POOL_SIZE); 
    userProfileName = (TextView) findViewById(R.id.userProfileName); 
    userProfilePicture = (ImageView) findViewById(R.id.userProfilePicture); 
    userTotalFollowers = (TextView) findViewById(R.id.userTotalFollowers); 
    userTotalPosts = (TextView) findViewById(R.id.userTotalPosts); 
    followProfileBtn = (TextView) findViewById(R.id.followProfileBtn); 
    contactProfileBtn = (TextView) findViewById(R.id.contactProfileBtn); 
    actionProfileArea = (LinearLayout) findViewById(R.id.actionProfileArea); 
    userProfileAddress = (TextView) findViewById(R.id.userProfileAddress); 
    userProfileJob = (TextView) findViewById(R.id.userProfileJob); 
    userProfileCover = (ImageView) findViewById(R.id.userProfileCover); 
    userPostsBtn = (TextView) findViewById(R.id.userPostsBtn); 
    userPostsBtn.setOnClickListener(this); 
    followProfileBtn.setOnClickListener(this); 
    contactProfileBtn.setOnClickListener(this); 
    postsList = (RecyclerView) findViewById(R.id.postsList); 

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeHome); 
    mSwipeRefreshLayout.setOnRefreshListener(this); 

    postsList.setOnScrollListener(new HidingScrollListener(layoutManager) { 
     @Override 
     public void onHide() { 
     } 

     @Override 
     public void onShow() { 
     } 

     @Override 
     public void onLoadMore(int currentPage) { 
      setCurrentPage(currentPage); 
      getPosts(); 
     } 
    }); 
} 



private void getUser() { 
    if (M.isNetworkAvailable(getApplicationContext())) { 
     loginLoadingView.setLoading(true); 
     UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this)); 
     mUsersAPI.getUser(userID, new Callback<userItem>() { 
      @Override 
      public void success(userItem user, retrofit.client.Response response) { 
       try { 
        mCacheManager.write(mGson.toJson(user), "Profile-" + userID + ".json"); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       updateView(user); 
      } 

      @Override 
      public void failure(RetrofitError error) { 
       loginLoadingView.setLoading(false); 
       M.T(ProfilePreview.this, getString(R.string.ServerError)); 
      } 
     }); 

    } else { 

     try { 
      String profile = mCacheManager.readString("Profile-" + userID + ".json"); 
      Gson mGson = new Gson(); 
      updateView((userItem) mGson.fromJson(profile, new TypeToken<userItem>() { 
      }.getType())); 
     } catch (Exception e) { 
      M.L(e.getMessage()); 
     } 
    } 
} 

private void downloadFile(String url, String hash) { 
    if (getFilePath(hash) == null) { 
     Uri downloadUri = Uri.parse(url); 
     Uri destinationUri = Uri.parse(M.getFilePath(getApplicationContext(), hash)); 
     DownloadRequest downloadRequest = new DownloadRequest(downloadUri) 
       .setDestinationURI(destinationUri); 
     downloadManager.add(downloadRequest); 
    } 
} 

private void updateView(userItem user) { 
    this.user = user; 
    if (user.isMine()) { 
     actionProfileArea.setVisibility(View.GONE); 
    } else { 
     actionProfileArea.setVisibility(View.VISIBLE); 
    } 
    if (user.isFollowed()) { 
     followProfileBtn.setText(getString(R.string.UnFollow)); 
     contactProfileBtn.setVisibility(View.VISIBLE); 
    } else { 
     followProfileBtn.setText(getString(R.string.Follow)); 
     contactProfileBtn.setVisibility(View.GONE); 
    } 

    if (user.getName() != null) { 
     userProfileName.setText(user.getName()); 
    } else { 
     userProfileName.setText(user.getUsername()); 
    } 
    if (user.getAddress() != null) { 
     userProfileAddress.setVisibility(View.VISIBLE); 
     userProfileAddress.setText(user.getAddress()); 
    } else { 
     userProfileAddress.setVisibility(View.GONE); 
    } 
    if (user.getJob() != null) { 
     userProfileJob.setVisibility(View.VISIBLE); 
     userProfileJob.setText(user.getJob()); 
    } else { 
     userProfileJob.setVisibility(View.GONE); 
    } 
    if (getFilePath(user.getPicture()) != null) { 
     Picasso.with(this) 
       .load(new File(getFilePath(user.getPicture()))) 
       .transform(new CropSquareTransformation()) 
       .placeholder(R.drawable.image_holder) 
       .error(R.drawable.image_holder) 
       .into(userProfilePicture); 
    } else { 
     Picasso.with(this) 
       .load(AppConst.IMAGE_PROFILE_URL + user.getPicture()) 
       .transform(new CropSquareTransformation()) 
       .placeholder(R.drawable.image_holder) 
       .error(R.drawable.image_holder) 
       .into(userProfilePicture); 
     downloadFile(AppConst.IMAGE_PROFILE_URL + user.getPicture(), user.getPicture()); 
    } 
    if (user.getCover() != null) { 
     if (getFilePath(user.getCover()) != null) { 
      userProfileCover.setImageURI(Uri.parse(getFilePath(user.getCover()))); 
     } else { 
      Picasso.with(this) 
        .load(AppConst.IMAGE_COVER_URL + user.getCover()) 
        .placeholder(R.drawable.header) 
        .error(R.drawable.header) 
        .into(userProfileCover); 
      downloadFile(AppConst.IMAGE_COVER_URL + user.getCover(), user.getCover()); 
     } 
    } else { 
     Picasso.with(this) 
       .load(R.drawable.header) 
       .into(userProfileCover); 
    } 
    userTotalFollowers.setText(user.getTotalFollowers() + ""); 
    userTotalPosts.setText(user.getTotalPosts() + ""); 
    loginLoadingView.setLoading(false); 
} 

private String getFilePath(String hash) { 
    return M.filePath(getApplicationContext(), hash); 
} 

@Override 
public void onClick(View v) { 
    switch (v.getId()) { 
     case R.id.followProfileBtn: 
      UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this)); 
      mUsersAPI.followToggle(userID, new Callback<ResponseModel>() { 
       @Override 
       public void success(ResponseModel responseModel, Response response) { 
        if (responseModel.isDone()) { 
         if (user.isFollowed()) { 
          user.setFollowed(false); 
          followProfileBtn.setText(getString(R.string.Follow)); 
          loginLoadingView.setLoading(true); 
          contactProfileBtn.setVisibility(View.GONE); 
          loginLoadingView.setLoading(false); 
         } else { 
          user.setFollowed(true); 
          followProfileBtn.setText(getString(R.string.UnFollow)); 
          contactProfileBtn.setVisibility(View.VISIBLE); 
         } 
        } else { 
         M.T(ProfilePreview.this, responseModel.getMessage()); 
        } 
       } 

       @Override 
       public void failure(RetrofitError error) { 
        M.T(ProfilePreview.this, getString(R.string.ServerError)); 
       } 
      }); 
      break; 
     case R.id.contactProfileBtn: 
      Intent messagingIntent = new Intent(this, MessagingActivity.class); 
      messagingIntent.putExtra("conversationID", 0); 
      messagingIntent.putExtra("recipientID", userID); 
      startActivity(messagingIntent); 
      break; 
     case R.id.userPostsBtn: 
      Intent userPostsIntent = new Intent(this, UserPosts.class); 
      userPostsIntent.putExtra("userID", userID); 
      startActivity(userPostsIntent); 
      finish(); 
      break; 
    } 
} 
public void getPosts() { 
    if (M.isNetworkAvailable(this)) { 

     if (!mSwipeRefreshLayout.isRefreshing()) { 
      mSwipeRefreshLayout.setRefreshing(true); 
     } 
     PostsAPI mPostsAPI = APIService.createService(PostsAPI.class, M.getToken(this)); 
     mPostsAPI.getUserPosts(userID, getCurrentPage(), new Callback<List<PostsItem>>() { 
      @Override 
      public void success(List<PostsItem> postsItems, retrofit.client.Response response) { 
       try { 
        mCacheManager.write(mGson.toJson(postsItems), "UserPosts-" + userID + ".json"); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       updateView(postsItems); 
      } 

      @Override 
      public void failure(RetrofitError error) { 
       loginLoadingView.setLoading(false); 
      } 
     }); 
    } else { 
     try { 
      String UserPostsString = mCacheManager.readString("UserPosts-" + userID + ".json"); 
      updateView((List<PostsItem>) mGson.fromJson(UserPostsString, new TypeToken<List<PostsItem>>() { 
      }.getType())); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

private void updateView(List<PostsItem> postsItems) { 

    if (getCurrentPage() != 1) { 
     List<PostsItem> oldItems = mHomeListAdapter.getPosts(); 
     oldItems.addAll(postsItems); 
     mHomeListAdapter.setPosts(oldItems); 
    } else { 
     mHomeListAdapter.setPosts(postsItems); 
    } 
    if (mSwipeRefreshLayout.isRefreshing()) { 
     mSwipeRefreshLayout.setRefreshing(false); 
    } 
} 

@Override 
public void onRefresh() { 
    setCurrentPage(1); 
    getPosts(); 
} 

public int getCurrentPage() { 
    return currentPage; 
} 

public void setCurrentPage(int currentPage) { 
    this.currentPage = currentPage; 
} 

}

+3

[Что такое 'NullPointerException' и как его исправить?] (Http://stackoverflow.com/ Вопросы/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) - Проблема заключается в том, что 'mHomeListAdapter' является' null', вероятно, потому что вы ** редактируете: ** никогда инициализировать его – PPartisan

ответ

0

По крайней мере, из кода, который вы отправили, вы не инициализируете свой mhomelistadapter, поэтому он имеет значение null при вызове setPosts.

Смежные вопросы