这行给我错误:-
preferenceManagers=新的首选项管理器(getApplicationContext(((;
我得到的这个错误:-
"PreferenceManager(("在"android.preference.PreferenceManager"中不是公共的。无法从包外部访问
这是我的.xlm:-
package com.dccodes.chugli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.dccodes.chugli.Adapters.MessagesAdapter;
import com.dccodes.chugli.Models.Message;
import com.dccodes.chugli.databinding.ActivityChatBinding;
import com.dccodes.chugli.utilities.Constants;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class ChatActivity extends AppCompatActivity {
ActivityChatBinding binding;
public PreferenceManager preferenceManagers;
MessagesAdapter adapter;
ArrayList<Message> messages;
String senderRoom, receiverRoom;
FirebaseDatabase database;
FirebaseFirestore databases;
FirebaseStorage storage;
ProgressDialog dialog;
String senderUid;
String receiverUid;
String token;
String name;
private String conversationId = null;
private List<Message> chatMessage;
private MessagesAdapter chatAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChatBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
preferenceManagers = new PreferenceManager(getApplicationContext());
setSupportActionBar(binding.toolbar);
database = FirebaseDatabase.getInstance();
storage = FirebaseStorage.getInstance();
dialog = new ProgressDialog(this);
dialog.setMessage("Uploading image...");
dialog.setCancelable(false);
messages = new ArrayList<>();
String name = getIntent().getStringExtra("name");
String profile = getIntent().getStringExtra("image");
String token = getIntent().getStringExtra("token");
//Toast.makeText(this, token, Toast.LENGTH_SHORT).show();
binding.name.setText(name);
Glide.with(ChatActivity.this).load(profile)
.placeholder(R.drawable.avatar)
.into(binding.profile);
binding.imageView2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
receiverUid = getIntent().getStringExtra("uid");
senderUid = FirebaseAuth.getInstance().getUid();
database.getReference().child("presence").child(receiverUid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
String status = snapshot.getValue(String.class);
if(!status.isEmpty()) {
if(status.equals("Offline")) {
binding.status.setVisibility(View.GONE);
} else {
binding.status.setText(status);
binding.status.setVisibility(View.VISIBLE);
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
senderRoom = senderUid + receiverUid;
receiverRoom = receiverUid + senderUid;
adapter = new MessagesAdapter(this, messages, senderRoom, receiverRoom);
binding.messageViewBox.setLayoutManager(new LinearLayoutManager(this));
binding.messageViewBox.setAdapter(adapter);
database.getReference().child("chats")
.child(senderRoom)
.child("messages")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
messages.clear();
for(DataSnapshot snapshot1 : snapshot.getChildren()) {
Message message = snapshot1.getValue(Message.class);
message.setMessageId(snapshot1.getKey());
messages.add(message);
binding.messageViewBox.smoothScrollToPosition(Objects.requireNonNull(binding.messageViewBox.getAdapter()).getItemCount());
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
binding.sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String messageTxt = binding.messageBox.getText().toString();
Date date = new Date();
Message message = new Message(messageTxt, senderUid, date.getTime());
binding.messageBox.setText("");
String randomKey = database.getReference().push().getKey();
HashMap<String, Object> lastMsgObj = new HashMap<>();
lastMsgObj.put("lastMsg", message.getMessage());
lastMsgObj.put("lastMsgTime", date.getTime());
database.getReference().child("chats").child(senderRoom).updateChildren(lastMsgObj);
database.getReference().child("chats").child(receiverRoom).updateChildren(lastMsgObj);
database.getReference().child("chats")
.child(senderRoom)
.child("messages")
.child(randomKey)
.setValue(message).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
database.getReference().child("chats")
.child(receiverRoom)
.child("messages")
.child(randomKey)
.setValue(message).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
sendNotification(name, message.getMessage(), token);
}
});
}
});
}
});
binding.attachment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(ChatActivity.this, "Feature Coming Soon...", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_GET_CONTENT);
// intent.setType("image/*");
// startActivityForResult(intent, 25);
}
});
binding.camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(ChatActivity.this, "Feature Coming Soon...", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_GET_CONTENT);
// intent.setType("image/*");
// startActivityForResult(intent, 25);
}
});
final Handler handler = new Handler();
binding.messageBox.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) {
}
@Override
public void afterTextChanged(Editable s) {
database.getReference().child("presence").child(senderUid).setValue("typing...");
handler.removeCallbacksAndMessages(null);
handler.postDelayed(userStoppedTyping,1000);
}
Runnable userStoppedTyping = new Runnable() {
@Override
public void run() {
database.getReference().child("presence").child(senderUid).setValue("Online");
}
};
});
getSupportActionBar().setDisplayShowTitleEnabled(false);
// getSupportActionBar().setTitle(name);
//
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void init(){
preferenceManagers = new PreferenceManager(getApplicationContext());
chatMessage = new ArrayList<>();
chatAdapter = new MessagesAdapter(
chatMessage,
preferenceManagers.getString()
)
}
void sendNotification(String name, String message, String token) {
try {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://fcm.googleapis.com/fcm/send";
JSONObject data = new JSONObject();
data.put("title", name);
data.put("body", message);
JSONObject notificationData = new JSONObject();
notificationData.put("notification", data);
notificationData.put("to",token);
JsonObjectRequest request = new JsonObjectRequest(url, notificationData
, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Toast.makeText(ChatActivity.this, "success", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ChatActivity.this, error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
String key = "Key=AAAAzSjNf6E:APA91bEKDbO2puvbS29Fdu3jxoznS8PG7m_fnXbk3KW04yEDFoX82vJ8NqqvSGghZkhZdowx_B9xS1KGx8EvnVryH4uQdZRRIhqJjQnjR-ie2AgKPM5f8VrDHQ6eGpyDxAi1i9qoWp5h";
map.put("Content-Type", "application/json");
map.put("Authorization", key);
return map;
}
};
queue.add(request);
} catch (Exception ex) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 25) {
if(data != null) {
if(data.getData() != null) {
Uri selectedImage = data.getData();
Calendar calendar = Calendar.getInstance();
StorageReference reference = storage.getReference().child("chats").child(calendar.getTimeInMillis() + "");
dialog.show();
reference.putFile(selectedImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
dialog.dismiss();
if(task.isSuccessful()) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String filePath = uri.toString();
String messageTxt = binding.messageBox.getText().toString();
Date date = new Date();
Message message = new Message(messageTxt, senderUid, date.getTime());
message.setMessage("photo");
message.setImageUrl(filePath);
binding.messageBox.setText("");
String randomKey = database.getReference().push().getKey();
HashMap<String, Object> lastMsgObj = new HashMap<>();
lastMsgObj.put("lastMsg", message.getMessage());
lastMsgObj.put("lastMsgTime", date.getTime());
database.getReference().child("chats").child(senderRoom).updateChildren(lastMsgObj);
database.getReference().child("chats").child(receiverRoom).updateChildren(lastMsgObj);
database.getReference().child("chats")
.child(senderRoom)
.child("messages")
.child(randomKey)
.setValue(message).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
database.getReference().child("chats")
.child(receiverRoom)
.child("messages")
.child(randomKey)
.setValue(message).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
});
//Toast.makeText(ChatActivity.this, filePath, Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
}
}
@Override
protected void onResume() {
super.onResume();
String currentId = FirebaseAuth.getInstance().getUid();
database.getReference().child("presence").child(currentId).setValue("Online");
}
@Override
protected void onPause() {
super.onPause();
String currentId = FirebaseAuth.getInstance().getUid();
database.getReference().child("presence").child(currentId).setValue("Offline");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chat_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onSupportNavigateUp() {
finish();
return super.onSupportNavigateUp();
}
private void checkForConversation(){
if(chatMessage.size() != 0){
checkForConversationRemotely(
preferenceManagers.getString()
);
}
}
private void checkForConversationRemotely(String senderUid, String receiverUid){
databases.collection(Constants.KEY_COLLECTION_CONVERSATIONS)
.whereEqualTo(Constants.KEY_SENDER_ID, senderUid)
.whereEqualTo(Constants.KEY_RECEIVER_ID, receiverUid)
.get()
.addOnCompleteListener(conversationOnCompleteListener);
}
private final OnCompleteListener<QuerySnapshot> conversationOnCompleteListener = task -> {
if(task.isSuccessful() && task.getResult()!=null && task.getResult().getDocuments().size() > 0){
DocumentSnapshot documentSnapshot = task.getResult().getDocuments().get(0);
conversationId = documentSnapshot.getId();
}
};
}
我不知道为什么会出现这个错误。。。!有人能帮我摆脱这个错误吗?以下句子在我的代码中用红色下划线:-
#line85preferenceManagers=新的PreferenceManager(getApplicationContext(((;
#line271preferenceManagers=新的PreferenceManager(getApplicationContext(((;
#line275preferenceManagers.getString((
#line423preferenceManagers.getString((
有人能帮我解决这个问题吗?我将非常感谢你。。。❤️❤️❤️
我认为构造函数PreferenceManager(context)
在it包中是私有的,所以您不能在代码中使用它。你可以在这里试试我的解决方案吗:
SharedPreferences sharedPreferences;
void init(context: Context) {
sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCE_KEY, Context.MODE_PRIVATE);
}
Boolean getString(String: key, String: defaultValue) {
sharedPreferences.getString(key, defaultValue);
}
void putString(String: key, Boolean: saveValue) {
sharedPreferences.edit().putString(key, saveValue).apply();
}