如何从 Mainactivity 获取一个字符串值到 cardview 适配器?
How to get one string value from the Mainactivity to a cardview Adapter?
我在 mainactivity 上有获取位置的方法 运行,它获取用户的纬度和经度并将其以字符串的形式存储。
我的 cardview 以 recyclerview 的形式保存用户在 phone 中添加的联系人 activity 本身。
如何将从主 activity 获得的两个纬度和经度字符串传输到我的 cardview customAdapter,它应该占据该位置并在按下特定联系人的 cardview 时发送短信。
我尝试使用 putExtra
传递字符串,但我现在收到 cannot resolve method
错误。
这是我的updateLocation()
在MainActivity
中记录位置数据的方法
private void updateLocation(Location location) {
//update the location of the person
x = String.valueOf(location.getLatitude());
y = String.valueOf(location.getLongitude());
Toast.makeText(this,"Latitude = "+x,Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Longitude = "+y,Toast.LENGTH_SHORT).show();
Intent SendLocation = new Intent(this, CustomAdapter.class);
SendLocation.putExtra("mLatitude", x);
SendLocation.putExtra("mLongitude", y);
}
这是我的 cardview customAdapter
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
public ArrayList Contact_id, Contact_Name, Contact_number;
public ImageView mDelete, mMakeCall, mSendText;
public String Latitude="0",Longitude="0";
CustomAdapter(Context context, ArrayList Contact_id, ArrayList Contact_Name, ArrayList Contact_number,String mLatitude,String mLongitude) {
this.context = context;
this.Contact_id = Contact_id;
this.Contact_Name = Contact_Name;
this.Contact_number = Contact_number;
this.Latitude= mLatitude;
this.Longitude=mLongitude;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardview_contact_item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.Contact_Name_txt.setText(String.valueOf(Contact_Name.get(position)));
holder.Contact_Number_txt.setText(String.valueOf(Contact_number.get(position)));
}
@Override
public int getItemCount() {
return Contact_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Contact_id_txt, Contact_Name_txt, Contact_Number_txt;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mDelete = itemView.findViewById(R.id.Cardview_delete);
mMakeCall = itemView.findViewById(R.id.Cardview_MakeCall);
mSendText = itemView.findViewById(R.id.Cardview_MakeText);
Contact_Name_txt = itemView.findViewById(R.id.CardView_Name);
Contact_Number_txt = itemView.findViewById(R.id.CardView_Number);
SharedPreferences mPreference = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPreference.edit();
mDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Item Removed", Toast.LENGTH_SHORT).show();
}
});
mMakeCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Calling Contact", Toast.LENGTH_SHORT).show();
}
});
mSendText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
String phonenumber = Contact_Number_txt.getText().toString();
try {
Latitude = "drats";
SmsManager mySmsManager = SmsManager.getDefault();
mySmsManager.sendTextMessage(phonenumber, null, "I NEED HELP AT LATITUDE:" + Latitude + "LONGITUDE" + Longitude, null, null);
Toast.makeText(context, "Alert Message Sent", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "LATITUDE:" + Latitude, Toast.LENGTH_SHORT).show();
Toast.makeText(context, "LONGITUDE:" + Longitude, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(context, "Something went wrong/Fields are Empty", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(context,"The number is "+phonenumber, Toast.LENGTH_SHORT).show();
}
});
}//End of OnCreate
}
}
这是我现在的主要activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
//widgets
public ImageButton eAddContact;
RecyclerView recyclerView;
DatabaseHelper myDB;
ArrayList<String> Contact_id, Contact_Name, Contact_Number;
CustomAdapter customAdapter;
Button btnEnterContact;
private FusedLocationProviderClient fusedLocationProviderClient;
//Google's api for location services.
//private final int REQUEST_CHECK_CODE=8989;
private LocationSettingsRequest.Builder builder;
private String mLatitude,mLongitude;
private static final int REQUEST_LOCATION = 1;
private static final int REQUEST_SMS = 0;
Intent mIntent;
LocationManager locationManager;
LocationRequest locationRequest;
LocationCallback locationCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//permissions
if(ContextCompat.checkSelfPermission(this,Manifest.permission.SEND_SMS)!=PackageManager.PERMISSION_GRANTED)
{
//if permission is not granted then check if user has denied
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.SEND_SMS)){
}else
{
//popup for asking permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},REQUEST_SMS);
}
}
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED)
{
//if permission is not granted then check if user has denied
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)){
}else
{
//popup for asking permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}
}
eAddContact = findViewById(R.id.btnAddContact);
eAddContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick:opening dialog");
Dialog_AddContact dialog = new Dialog_AddContact();
dialog.show(getSupportFragmentManager(), "Add Contact Dialog");
}
});
//Toast.makeText(getApplicationContext(),"@#",Toast.LENGTH_SHORT).show();
myDB = new DatabaseHelper(MainActivity.this);
Contact_id = new ArrayList<>();
Contact_Name = new ArrayList<>();
Contact_Number = new ArrayList<>();
recyclerView = findViewById(R.id.RecyclerView);
customAdapter = new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number,mLatitude,mLongitude);
//set all the properties of LocationRequest
locationRequest = new LocationRequest();
//how often does location check occur
locationRequest.setInterval(1000*30);
locationRequest.setFastestInterval(1000*50);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
updateGPS();
//Display cardview data
storeDataInArrays();
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//will check requestCode
switch(requestCode)
{
case REQUEST_SMS:
{
//check if length of grantResults is greater than 0 and equal to PERMISSION_GRANTED
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"SMS Permission Granted",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this,"SMS Permission Denied",Toast.LENGTH_LONG).show();
}
}
case REQUEST_LOCATION:
{
//check if length of grantResults is greater than 0 and equal to PERMISSION_GRANTED
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Location Permission Granted",Toast.LENGTH_LONG).show();
updateGPS();
}
else
{
Toast.makeText(this,"Location Permission Denied",Toast.LENGTH_LONG).show();
}
}
}//switch
}
private void updateGPS(){
//get permissions from the user to track GPS
//get current location
//update string
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
//user gave the permissions
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
//we got permissions. put the values of location.
updateLocation(location);
}
});
}
else{
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}
}
}
private void updateLocation(Location location) {
//update the location of the person
mLatitude = String.valueOf(location.getLatitude());
mLongitude = String.valueOf(location.getLongitude());
Toast.makeText(this,"Latitude = "+mLatitude,Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Longitude = "+mLongitude,Toast.LENGTH_SHORT).show();
customAdapter.notifyDataSetChanged();
}
void storeDataInArrays() {
Contact_id.clear();
Contact_Name.clear();
Contact_Number.clear();
Cursor cursor = myDB.getEveryone();
if (cursor.getCount() == 0) {
//Add blank page
} else {
while (cursor.moveToNext()) {
Contact_id.add(cursor.getString(0));
Contact_Name.add(cursor.getString(1));
Contact_Number.add(cursor.getString(2));
}
}
customAdapter.notifyDataSetChanged();
}
//public void onRequestPermissionResult(int requestCOde,String permissions[],int[] grantResults){}//method
public void onLocationChanged(Location location) {
Double x = location.getLatitude();
Double y = location.getLongitude();
}
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
我真的很乐意帮助我解决这个问题。
如果我理解正确的话,你可以这样做:-
像这样在适配器构造函数中再添加两个参数:
CustomAdapter(Context context, ArrayList Contact_id, ArrayList Contact_Name, ArrayList Contact_number, String Latitude, String Longitude) {
this.context = context;
this.Contact_id = Contact_id;
this.Contact_Name = Contact_Name;
this.Contact_number = Contact_number;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
现在,在您的 MainActivity 中,有两个这样的字符串:
public class MainActivity extends AppCompatActivity {
...//Other variables and stuff
private String Latitude="0", Longitude="0";
...//onCreate(), etc
}
并在创建实例时将这两个临时传递到适配器中。
并将 updateLocation() 更改为如下内容:
private void updateLocation(Location location) {
//update the location of the person
Latitude = String.valueOf(location.getLatitude());
Longitude = String.valueOf(location.getLongitude());
Toast.makeText(this,"Latitude = " + Latitude, Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Longitude = " + Longitude , Toast.LENGTH_SHORT).show();
recyclerView.setAdapter(new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number,mLatitude,mLongitude));
recyclerView.invalidate();
}
如果您需要任何进一步的说明,请告诉我。
好的,您可以在下面的代码 MainActivity.Follow 中创建 CustomAdapter 的对象时通过 CustomAdapter 构造函数传递 Longitude 和 Latitude:
public class CustomAdapter extends
RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
public ArrayList Contact_id, Contact_Name, Contact_number;
public ImageView mDelete, mMakeCall, mSendText;
public String Latitude="0",Longitude="0";
//passing latitude and longitude value through CustomAdapter consturctor.
CustomAdapter(Context context, ArrayList Contact_id, ArrayList Contact_Name,
ArrayList Contact_number, String Latitude, String Longitude) {
this.context = context;
this.Contact_id = Contact_id;
this.Contact_Name = Contact_Name;
this.Contact_number = Contact_number;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardview_contact_item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.Contact_Name_txt.setText(String.valueOf(Contact_Name.get(position)));
holder.Contact_Number_txt.setText(String.valueOf(Contact_number.get(position)));
}
@Override
public int getItemCount() {
return Contact_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Contact_id_txt, Contact_Name_txt, Contact_Number_txt;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mDelete = itemView.findViewById(R.id.Cardview_delete);
mMakeCall = itemView.findViewById(R.id.Cardview_MakeCall);
mSendText = itemView.findViewById(R.id.Cardview_MakeText);
Contact_Name_txt = itemView.findViewById(R.id.CardView_Name);
Contact_Number_txt = itemView.findViewById(R.id.CardView_Number);
mDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Item Removed", Toast.LENGTH_SHORT).show();
}
});
mMakeCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Calling Contact", Toast.LENGTH_SHORT).show();
}
});
mSendText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
String phonenumber = Contact_Number_txt.getText().toString();
try {
SmsManager mySmsManager = SmsManager.getDefault();
mySmsManager.sendTextMessage(phonenumber, null, "I NEED HELP AT LATITUDE:" + Latitude + "LONGITUDE" + Longitude, null, null);
Toast.makeText(context, "Alert Message Sent", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(context, "Something went wrong/Fields are Empty", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(context,"The number is "+phonenumber, Toast.LENGTH_SHORT).show();
}
});
}//End of OnCreate
}
}
In MainActivity.java file you need to create an object of CustomAdapter only after you have the value of Longitude and Latitude else it will throw NullPointerException.
private void updateLocation(Location location){
......
....
//creating an object of CustomAdapter
CustomAdapter customAdapter = new CustomAdapter(.....,x,y); //x is latitude, y is longitude as per your code.
但是,我不建议您这样做,更好的方法是使用接口。
}
我在 mainactivity 上有获取位置的方法 运行,它获取用户的纬度和经度并将其以字符串的形式存储。 我的 cardview 以 recyclerview 的形式保存用户在 phone 中添加的联系人 activity 本身。
如何将从主 activity 获得的两个纬度和经度字符串传输到我的 cardview customAdapter,它应该占据该位置并在按下特定联系人的 cardview 时发送短信。
我尝试使用 putExtra
传递字符串,但我现在收到 cannot resolve method
错误。
这是我的updateLocation()
在MainActivity
private void updateLocation(Location location) {
//update the location of the person
x = String.valueOf(location.getLatitude());
y = String.valueOf(location.getLongitude());
Toast.makeText(this,"Latitude = "+x,Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Longitude = "+y,Toast.LENGTH_SHORT).show();
Intent SendLocation = new Intent(this, CustomAdapter.class);
SendLocation.putExtra("mLatitude", x);
SendLocation.putExtra("mLongitude", y);
}
这是我的 cardview customAdapter
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
public ArrayList Contact_id, Contact_Name, Contact_number;
public ImageView mDelete, mMakeCall, mSendText;
public String Latitude="0",Longitude="0";
CustomAdapter(Context context, ArrayList Contact_id, ArrayList Contact_Name, ArrayList Contact_number,String mLatitude,String mLongitude) {
this.context = context;
this.Contact_id = Contact_id;
this.Contact_Name = Contact_Name;
this.Contact_number = Contact_number;
this.Latitude= mLatitude;
this.Longitude=mLongitude;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardview_contact_item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.Contact_Name_txt.setText(String.valueOf(Contact_Name.get(position)));
holder.Contact_Number_txt.setText(String.valueOf(Contact_number.get(position)));
}
@Override
public int getItemCount() {
return Contact_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Contact_id_txt, Contact_Name_txt, Contact_Number_txt;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mDelete = itemView.findViewById(R.id.Cardview_delete);
mMakeCall = itemView.findViewById(R.id.Cardview_MakeCall);
mSendText = itemView.findViewById(R.id.Cardview_MakeText);
Contact_Name_txt = itemView.findViewById(R.id.CardView_Name);
Contact_Number_txt = itemView.findViewById(R.id.CardView_Number);
SharedPreferences mPreference = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPreference.edit();
mDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Item Removed", Toast.LENGTH_SHORT).show();
}
});
mMakeCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Calling Contact", Toast.LENGTH_SHORT).show();
}
});
mSendText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
String phonenumber = Contact_Number_txt.getText().toString();
try {
Latitude = "drats";
SmsManager mySmsManager = SmsManager.getDefault();
mySmsManager.sendTextMessage(phonenumber, null, "I NEED HELP AT LATITUDE:" + Latitude + "LONGITUDE" + Longitude, null, null);
Toast.makeText(context, "Alert Message Sent", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "LATITUDE:" + Latitude, Toast.LENGTH_SHORT).show();
Toast.makeText(context, "LONGITUDE:" + Longitude, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(context, "Something went wrong/Fields are Empty", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(context,"The number is "+phonenumber, Toast.LENGTH_SHORT).show();
}
});
}//End of OnCreate
}
}
这是我现在的主要activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
//widgets
public ImageButton eAddContact;
RecyclerView recyclerView;
DatabaseHelper myDB;
ArrayList<String> Contact_id, Contact_Name, Contact_Number;
CustomAdapter customAdapter;
Button btnEnterContact;
private FusedLocationProviderClient fusedLocationProviderClient;
//Google's api for location services.
//private final int REQUEST_CHECK_CODE=8989;
private LocationSettingsRequest.Builder builder;
private String mLatitude,mLongitude;
private static final int REQUEST_LOCATION = 1;
private static final int REQUEST_SMS = 0;
Intent mIntent;
LocationManager locationManager;
LocationRequest locationRequest;
LocationCallback locationCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//permissions
if(ContextCompat.checkSelfPermission(this,Manifest.permission.SEND_SMS)!=PackageManager.PERMISSION_GRANTED)
{
//if permission is not granted then check if user has denied
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.SEND_SMS)){
}else
{
//popup for asking permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},REQUEST_SMS);
}
}
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED)
{
//if permission is not granted then check if user has denied
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)){
}else
{
//popup for asking permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}
}
eAddContact = findViewById(R.id.btnAddContact);
eAddContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick:opening dialog");
Dialog_AddContact dialog = new Dialog_AddContact();
dialog.show(getSupportFragmentManager(), "Add Contact Dialog");
}
});
//Toast.makeText(getApplicationContext(),"@#",Toast.LENGTH_SHORT).show();
myDB = new DatabaseHelper(MainActivity.this);
Contact_id = new ArrayList<>();
Contact_Name = new ArrayList<>();
Contact_Number = new ArrayList<>();
recyclerView = findViewById(R.id.RecyclerView);
customAdapter = new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number,mLatitude,mLongitude);
//set all the properties of LocationRequest
locationRequest = new LocationRequest();
//how often does location check occur
locationRequest.setInterval(1000*30);
locationRequest.setFastestInterval(1000*50);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
updateGPS();
//Display cardview data
storeDataInArrays();
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//will check requestCode
switch(requestCode)
{
case REQUEST_SMS:
{
//check if length of grantResults is greater than 0 and equal to PERMISSION_GRANTED
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"SMS Permission Granted",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this,"SMS Permission Denied",Toast.LENGTH_LONG).show();
}
}
case REQUEST_LOCATION:
{
//check if length of grantResults is greater than 0 and equal to PERMISSION_GRANTED
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Location Permission Granted",Toast.LENGTH_LONG).show();
updateGPS();
}
else
{
Toast.makeText(this,"Location Permission Denied",Toast.LENGTH_LONG).show();
}
}
}//switch
}
private void updateGPS(){
//get permissions from the user to track GPS
//get current location
//update string
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
//user gave the permissions
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
//we got permissions. put the values of location.
updateLocation(location);
}
});
}
else{
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}
}
}
private void updateLocation(Location location) {
//update the location of the person
mLatitude = String.valueOf(location.getLatitude());
mLongitude = String.valueOf(location.getLongitude());
Toast.makeText(this,"Latitude = "+mLatitude,Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Longitude = "+mLongitude,Toast.LENGTH_SHORT).show();
customAdapter.notifyDataSetChanged();
}
void storeDataInArrays() {
Contact_id.clear();
Contact_Name.clear();
Contact_Number.clear();
Cursor cursor = myDB.getEveryone();
if (cursor.getCount() == 0) {
//Add blank page
} else {
while (cursor.moveToNext()) {
Contact_id.add(cursor.getString(0));
Contact_Name.add(cursor.getString(1));
Contact_Number.add(cursor.getString(2));
}
}
customAdapter.notifyDataSetChanged();
}
//public void onRequestPermissionResult(int requestCOde,String permissions[],int[] grantResults){}//method
public void onLocationChanged(Location location) {
Double x = location.getLatitude();
Double y = location.getLongitude();
}
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
我真的很乐意帮助我解决这个问题。
如果我理解正确的话,你可以这样做:-
像这样在适配器构造函数中再添加两个参数:
CustomAdapter(Context context, ArrayList Contact_id, ArrayList Contact_Name, ArrayList Contact_number, String Latitude, String Longitude) {
this.context = context;
this.Contact_id = Contact_id;
this.Contact_Name = Contact_Name;
this.Contact_number = Contact_number;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
现在,在您的 MainActivity 中,有两个这样的字符串:
public class MainActivity extends AppCompatActivity {
...//Other variables and stuff
private String Latitude="0", Longitude="0";
...//onCreate(), etc
}
并在创建实例时将这两个临时传递到适配器中。
并将 updateLocation() 更改为如下内容:
private void updateLocation(Location location) {
//update the location of the person
Latitude = String.valueOf(location.getLatitude());
Longitude = String.valueOf(location.getLongitude());
Toast.makeText(this,"Latitude = " + Latitude, Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Longitude = " + Longitude , Toast.LENGTH_SHORT).show();
recyclerView.setAdapter(new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number,mLatitude,mLongitude));
recyclerView.invalidate();
}
如果您需要任何进一步的说明,请告诉我。
好的,您可以在下面的代码 MainActivity.Follow 中创建 CustomAdapter 的对象时通过 CustomAdapter 构造函数传递 Longitude 和 Latitude:
public class CustomAdapter extends
RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
public ArrayList Contact_id, Contact_Name, Contact_number;
public ImageView mDelete, mMakeCall, mSendText;
public String Latitude="0",Longitude="0";
//passing latitude and longitude value through CustomAdapter consturctor.
CustomAdapter(Context context, ArrayList Contact_id, ArrayList Contact_Name,
ArrayList Contact_number, String Latitude, String Longitude) {
this.context = context;
this.Contact_id = Contact_id;
this.Contact_Name = Contact_Name;
this.Contact_number = Contact_number;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardview_contact_item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.Contact_Name_txt.setText(String.valueOf(Contact_Name.get(position)));
holder.Contact_Number_txt.setText(String.valueOf(Contact_number.get(position)));
}
@Override
public int getItemCount() {
return Contact_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Contact_id_txt, Contact_Name_txt, Contact_Number_txt;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mDelete = itemView.findViewById(R.id.Cardview_delete);
mMakeCall = itemView.findViewById(R.id.Cardview_MakeCall);
mSendText = itemView.findViewById(R.id.Cardview_MakeText);
Contact_Name_txt = itemView.findViewById(R.id.CardView_Name);
Contact_Number_txt = itemView.findViewById(R.id.CardView_Number);
mDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Item Removed", Toast.LENGTH_SHORT).show();
}
});
mMakeCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Calling Contact", Toast.LENGTH_SHORT).show();
}
});
mSendText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
String phonenumber = Contact_Number_txt.getText().toString();
try {
SmsManager mySmsManager = SmsManager.getDefault();
mySmsManager.sendTextMessage(phonenumber, null, "I NEED HELP AT LATITUDE:" + Latitude + "LONGITUDE" + Longitude, null, null);
Toast.makeText(context, "Alert Message Sent", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(context, "Something went wrong/Fields are Empty", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(context,"The number is "+phonenumber, Toast.LENGTH_SHORT).show();
}
});
}//End of OnCreate
}
}
In MainActivity.java file you need to create an object of CustomAdapter only after you have the value of Longitude and Latitude else it will throw NullPointerException.
private void updateLocation(Location location){
......
....
//creating an object of CustomAdapter
CustomAdapter customAdapter = new CustomAdapter(.....,x,y); //x is latitude, y is longitude as per your code.
但是,我不建议您这样做,更好的方法是使用接口。 }