【问题标题】:How to get one string value from the Mainactivity to a cardview Adapter?如何从 Mainactivity 获取一个字符串值到 cardview 适配器?
【发布时间】:2022-02-01 02:38:14
【问题描述】:

我在 mainactivity 上运行了 get location 方法,它获取用户的纬度和经度并将其以字符串的形式存储。 我的cardview在mainactivity本身中以recyclerview的形式保存了用户在手机中添加的联系人。

如何将我从主要活动中获得的纬度和经度这两个字符串传输到我的 cardview customAdapter,它应该获取该位置并在按下特定联系人的 cardview 时发送一条短信。

我尝试使用putExtra 传递字符串,但我现在收到cannot resolve method 错误。

这是我在MainActivity中记录位置数据的updateLocation()方法

   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

}

}

这是我现在的主要活动

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");
}
 }

我真的很想帮助我解决这个问题。

【问题讨论】:

  • 在哪里调用 updateLocation()
  • 目前应该在MainActivity中调用,周期性刷新位置。我目前可以将位置数据保存在 Mainactivity 中,甚至可以对其进行烘烤。但我无法弄清楚如何将该值传递给 cardview 的适配器。

标签: java android android-studio android-intent adapter


【解决方案1】:

如果我对情况的理解正确,您可以这样做:-

像这样在适配器构造函数中添加两个参数:

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(); 
}

如果您需要任何进一步的说明,请告诉我。

【讨论】:

  • 啊,我明白了,我将两个字符串参数 LatitudeLongitude 添加到 customAdapter 并将 mainactivity 中的私有参数定义为 'mLatitude', mLongitude 这样在构造函数中它目前看起来像这样“this.Latitude=mLatitude”。然后我添加了'customAdapter.notifyDataSetChanged();'到 updateLocation 方法。但是,当我现在尝试敬酒卡片视图时,纬度和经度都显示为空。我不确定我现在做错了什么。
  • @udbhavshrivastava 我认为您正在为旧的 xy 变量敬酒。请重新检查。
  • @udbhavshrivastava 你应该为那些新的私人公司干杯:mLatitudemLongitude
  • 很抱歉造成混乱,mainactivity 的 toast 仍然可以正常工作。然而,当我发送短信时的祝酒词也应该使用Toast.makeText(this,"Latitude = "+mLatitude,Toast.LENGTH_SHORT).show();Toast.makeText(this,"Longitude = "+mLongitude,Toast.LENGTH_SHORT).show();这两个命令显示位置显示空。
  • 我已经删除了 mainactivity 中对 x 和 y 的任何引用,因为它们开始令人困惑。我目前正在使用 mLatitudemLongitude 。但目前的问题似乎是我在某处犯了一个错误,即 mLatitude 和 mLongitude 的值没有被传输到 customAdapter 的纬度和经度变量。
【解决方案2】:

好的,你可以通过CustomAdapter的构造函数传递经度和纬度,同时在MainActivity中创建一个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";

  //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

 }

}

MainActivity.java 文件中,您需要在获得经度和纬度的值后创建 CustomAdapter 的对象,否则它将抛出 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.

但是,我不建议您这样做,更好的方法是使用接口。 }

【讨论】:

  • 我正在尝试执行此操作,但似乎在某处犯了错误,以至于 mLatitude 和 mLongitude 的值没有被传输到 customAdapter。我已经用更新的代码更新了我的原始帖子,希望它有助于澄清我所犯的任何错误。
猜你喜欢
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
相关资源
最近更新 更多