如何从 Java 类中的另一个包调用 Kotlin 函数?
有一个包fcmpushnotificationshttpv1,其中有一个用 Kotlin 实现的类ChatViewModel.kt。
还有一个dem.corp.androidmessenger包含类的包NewChatFragment。我想从类中另一个包中的类中NewChatFragment调用一个函数。sendMessageChatViewModel
为此我编写了以下代码:
//ymy NEW test
new fcmpushnotificationshttpv1.ChatViewModel.ChatViewModel();
fcmpushnotificationshttpv1.sendMessage(true);
但是我收到一个编译错误:
C:\androidSDK\AndroidStudioProjects\AndroidMessenger-main\app\src\main\java\dem\corp\androidmessenger\bottomnav\new_chat\NewChatFragment.java:56: error: package fcmpushnotificationshttpv1.ChatViewModel does not exist
new fcmpushnotificationshttpv1.ChatViewModel.ChatViewModel();
为什么看不到这个包?
它甚至没有帮助//import com.plcoding.fcmpushnotificationshttpv1.ChatViewModel;
也没有看到SDK包。
我按照 Nowhere Man 所说的写了,但是出现了错误:
C:\androidSDK\AndroidStudioProjects\AndroidMessenger-main\app\src\main\java\dem\corp\androidmessenger\bottomnav\new_chat\NewChatFragment.java:30: error: package fcmpushnotificationshttpv1 does not exist
import fcmpushnotificationshttpv1.ChatViewModel;
^
以下是该文件的内容NewChatFragment.java:
package dem.corp.androidmessenger.bottomnav.new_chat;
import static androidx.fragment.app.FragmentManager.TAG;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
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 fcmpushnotificationshttpv1.ChatViewModel;
//import fcmpushnotificationshttpv1.ChatViewModel;
import java.util.ArrayList;
import dem.corp.androidmessenger.databinding.FragmentNewChatBinding;
import dem.corp.androidmessenger.users.User;
import dem.corp.androidmessenger.users.UsersAdapter;
//import fcmpushnotificationshttpv1.ChatViewModel;
//import fcmpushnotificationshttpv1.ChatViewModel;
//import fcmpushnotificationshttpv1.ChatViewModel;
//import fcmpushnotificationshttpv1.ChatViewModel;
//import fcmpushnotificationshttpv1.ChatViewModel;
public class NewChatFragment extends Fragment {
private FragmentNewChatBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentNewChatBinding.inflate(inflater, container, false);
loadUsers();
return binding.getRoot();
}
private void loadUsers(){
ArrayList<User> users = new ArrayList<User>();
FirebaseDatabase.getInstance().getReference().child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()){
if (userSnapshot.getKey().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())){
continue;
}
//ymy NEW test
// вызов конструктора класса ChatViewModel
// вызов конструктора класса ChatViewModel
ChatViewModel chatViewModel = new fcmpushnotificationshttpv1.ChatViewModel();
// вызов package-level функции
fcmpushnotificationshttpv1.ChatViewModel.sendMessage(true);
// вызов package-level функции
fcmpushnotificationshttpv1.ChatViewModel.sendMessage(true);
// ChatViewModel.sendMessage(true);
// new fcmpushnotificationshttpv1.ChatViewModel();
// fcmpushnotificationshttpv1.ChatViewModel.class.
//my test OK
//показывает flase у всех юзеров String username = String.valueOf(userSnapshot.getKey().equals(FirebaseAuth.getInstance().getCurrentUser().getUid()));
String username = userSnapshot.child("username").getValue().toString();
Log.w(TAG, "Error getting documents. 2222 username=" + username);
String uid = userSnapshot.getKey();
Log.w(TAG, "Error getting documents. 2222 uid=" + uid);
//String username = Objects.requireNonNull(userSnapshot.child("username").getValue()).toString();
String profileImage = String.valueOf(userSnapshot.child("profileImage").getValue());
users.add(new User(uid, username, profileImage));
}
binding.usersRv.setLayoutManager(new LinearLayoutManager(getContext()));
binding.usersRv.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
binding.usersRv.setAdapter(new UsersAdapter(users));
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
以下是该文件的内容ChatViewModel.kt:
@file:JvmName("ChatViewModel")
package fcmpushnotificationshttpv1
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import retrofit2.HttpException
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.create
import java.io.IOException
class ChatViewModel: ViewModel() {
var state by mutableStateOf(ChatState())
private set
private val api: FcmApi = Retrofit.Builder()
// .baseUrl("http://10.0.2.2:8084/")
.baseUrl("http://109.195.103.21:8084/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create()
init {
viewModelScope.launch {
Firebase.messaging.subscribeToTopic("chat").await()
}
}
fun onRemoteTokenChange(newToken: String) {
state = state.copy(
remoteToken = newToken
)
}
fun onSubmitRemoteToken() {
state = state.copy(
isEnteringToken = false
)
}
fun onMessageChange(message: String) {
state = state.copy(
messageText = message
)
}
fun sendMessage(isBroadcast: Boolean) {
viewModelScope.launch {
val messageDto = SendMessageDto(
to = if(isBroadcast) null else state.remoteToken,
notification = NotificationBody(
title = "New message!",
body = state.messageText
)
)
try {
if(isBroadcast) {
api.broadcast(messageDto)
} else {
api.sendMessage(messageDto)
}
state = state.copy(
messageText = ""
)
} catch(e: HttpException) {
e.printStackTrace()
} catch(e: IOException) {
e.printStackTrace()
}
}
}
}
