不可始终通过getString()访问Parcelable对象中的字符串资源字段的值

时间:2019-09-16 15:05:20

标签: android kotlin parcelable

我正在使用RecyclerView类设置Adapter,以使用由TextViewImageView组成的对象来填充它。我要用作我的TextView文本的字符串已传递并保存在我的Parcelable对象PlaceObject类中,并作为string resource保存。问题是,尽管我已经设法通过getString(placeObject.getName())类中的DetailsActivity访问字符串值,但是当我在{{ 1}}的{​​{1}}方法。有什么想法吗?

我已经阅读了其他文章,您可以像在Java中那样使用ResourceNotFoundException来执行相同的操作,但是由于我在文档中看到了可用的Resources.getSystem().getString(event.name)方法,因此我无法做到这一点不要接受LocalEventsAdapter作为参数。我还在另一篇文章中找到了onBindViewHolder解决方案,但这也不起作用。

这是我的getString类,扩展了getString

ints

现在下面是我的Resources.getSystem().getString()类,其中有一个PlaceObject实例以Parcelable interface的形式添加到我的class PlaceObject : Parcelable { // Implementing the Parcelable interface to allow for cleaner and faster code private val TAG = PlaceObject::class.java.simpleName private val baseMapSearchUrl = "https://www.google.com/maps/search/?api=1&query=" // Base url for launching a Map activity with a Search Intent // Using int so that the values can be accessed via R.string etc. var name: Int = 0 private set var description: Int = 0 private set var category: Int = 0 private set var locationDistance: String? = "location" private set private var finalMapSearchUrl = baseMapSearchUrl val mapSearchUrl: String get() { Log.d(TAG, "finalMapSearchUrl = $finalMapSearchUrl") return finalMapSearchUrl } internal constructor(name: Int, description: Int, category: Int, locationDistance: String, mapUrlParam: String) { this.name = name this.description = description this.locationDistance = locationDistance this.category = category finalMapSearchUrl += Uri.encode(mapUrlParam) } private constructor(`in`: Parcel) { name = `in`.readInt() description = `in`.readInt() locationDistance = `in`.readString() category = `in`.readInt() finalMapSearchUrl = `in`.readString().toString() } override fun describeContents(): Int { return 0 } override fun writeToParcel(parcel: Parcel, i: Int) { parcel.writeInt(name) parcel.writeInt(description) parcel.writeString(locationDistance) parcel.writeInt(category) parcel.writeString(finalMapSearchUrl) } companion object CREATOR : Parcelable.Creator<PlaceObject> { override fun createFromParcel(parcel: Parcel): PlaceObject { return PlaceObject(parcel) } override fun newArray(size: Int): Array<PlaceObject?> { return arrayOfNulls(size) } } } 包中,然后您可以看到,检索它,将其分配给本地DetailsActivity变量,然后在PlaceObject方法内部,我使用行MainActivity访问Parcelable资源。这似乎工作正常,并且资源ID从一个类传递到另一类而没有问题。

placeObject

但是在我的initializeData()类中,当我尝试做类似的事情时,当我在string方法中使用placeName.setText(getString(placeObject.getName()));时,我会被抛出public class DetailsActivity extends BaseActivity { private static final String TAG = DetailsActivity.class.getSimpleName(); // Intent Parcelable key private static final String PARCELABLE_KEY = "parcelable"; private PlaceObject placeObject; private String placeCategory; @BindView(R.id.details_toolbar) Toolbar detailsToolbar; @BindView(R.id.toolbar_title) TextView toolbarTitle; @BindView(R.id.show_in_map_button) Button mapButton; @BindView(R.id.place_image) ImageView placeImg; @BindView(R.id.place_name) TextView placeName; @BindView(R.id.place_description) TextView placeDesc; @BindView(R.id.place_location) TextView placeLocation; @OnClick(R.id.show_in_map_button) void openMap() { String mapSearchUrl = placeObject.getMapSearchUrl(); Log.d(TAG,"mapSearchUri = [" + mapSearchUrl + "]"); Uri gmIntentUri = Uri.parse(mapSearchUrl); // Create a Uri from a string. Use the result to create an Intent Intent mapIntent = new Intent(Intent.ACTION_VIEW,gmIntentUri); // Make the Intent explicit by settings the Google Maps package mapIntent.setPackage("com.google.android.apps.maps"); // Verify that there is an app available to receive the intent (e.g: Google Maps) if(mapIntent.resolveActivity(getPackageManager()) != null) { startActivity(mapIntent); // if the result is non-null there is at least one app that can handle the intent } else { Log.d(TAG,"Error resolving Activity for map Intent in openMap(), [Uri = " + gmIntentUri + "]."); Log.d(TAG,"mapIntent.resolveActivity() = " + mapIntent.resolveActivity(getPackageManager())); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); turnStatusBarTransparent(this); setContentView(R.layout.activity_details); ButterKnife.bind(this); // Toolbar-ActionBar related detailsToolbar.setNavigationIcon(R.drawable.baseline_arrow_back_ios_white_24); // setting the back button icon setSupportActionBar(detailsToolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(false); } toolbarTitle.setText(getResources().getString(R.string.details_page_title)); detailsToolbar.setNavigationOnClickListener(view -> finish()); // When the back button is pressed, end the activity scaleButtonDrawable(); getIntentData(getIntent()); initializeData(); } /** * Updates the layout's views with the right data */ private void initializeData() { placeName.setText(getString(placeObject.getName())); placeDesc.setText(getString(placeObject.getDescription())); placeLocation.setText(placeObject.getLocationDistance()); placeCategory = getString(placeObject.getCategory()); try { placeImg.setImageDrawable(determineImageResource()); } catch (NullPointerException npe) { npe.printStackTrace(); Log.d(TAG,"Null Pointer Exception in determineImageResource()"); } } /** * Determines which image drawable to use for the * selected UI item based on it's name. * @return Returns the drawable resource for the image */ private Drawable determineImageResource() { if(placeCategory.equals(getString(R.string.beach_category))) { switch (getString(placeObject.getName())) { case "Spilia": return getResources().getDrawable(R.drawable.spilia,null); case "Plakes": return getResources().getDrawable(R.drawable.plakes,null); case "Bisti": return getResources().getDrawable(R.drawable.bisti,null); default: Log.d(TAG,"Error resolving Beach name in determineImageResource()"); return getResources().getDrawable(R.drawable.beach_bg_placeholder,null); } } else if(placeCategory.equals(getString(R.string.museum_category))) { switch (getString(placeObject.getName())) { case "Historical Archives Museum": return getResources().getDrawable(R.drawable.historical_archives_museum,null); case "Ecclesiastical Museum": return getResources().getDrawable(R.drawable.ecclesiastical_museum,null); default: Log.d(TAG,"Error resolving Museum name in determineImageResource()"); return getResources().getDrawable(R.drawable.beach_bg_placeholder,null); } } else if(placeCategory.equals(getString(R.string.event_category))) { switch (getString(placeObject.getName())) { case "Miaoulia": disableMapButton(); return getResources().getDrawable(R.drawable.miaoulia_event,null); default: Log.d(TAG,"Error resolving Event name in determineImageResource()"); return getResources().getDrawable(R.drawable.beach_bg_placeholder,null); } } else if(placeCategory.equals("Restaurant")) { switch (getString(placeObject.getName())) { case "Techne": return getResources().getDrawable(R.drawable.techne_restaurant,null); case "Xeri Elia": return getResources().getDrawable(R.drawable.xeri_elia_restaurant,null); case "Sunset": return getResources().getDrawable(R.drawable.sunset_restaurant,null); default: Log.d(TAG,"Error resolving Restaurant name in determineImageResource()"); return getResources().getDrawable(R.drawable.beach_bg_placeholder,null); } } else { Log.d(TAG,"Couldn't determine imageResource in determineImageResource(). Using placeholder image."); return getResources().getDrawable(R.drawable.beach_bg_placeholder,null); } } /** * Hides the "Show In Map" button from the UI */ private void disableMapButton() { mapButton.setVisibility(View.GONE); } /** * Unpacks the data from the intent and assigns * it to the respective fields * @param intent The calling Intent */ private void getIntentData(Intent intent) { Bundle dataBundle = intent.getExtras(); if (dataBundle != null) { placeObject = dataBundle.getParcelable(PARCELABLE_KEY); } else { Log.d(TAG,"Data bundle in getIntentData() is null"); } } /** * Scales the "Show in Map" Button's drawable to fit * into the button correctly. */ private void scaleButtonDrawable() { // Scales down the button's drawable to fit the button Drawable drawable = getResources().getDrawable(R.drawable.location_btn,null); drawable.setBounds(new Rect(0,0,70,70)); mapButton.setCompoundDrawables(drawable,null,null,null); } } LocalEventsAdapter ResourceNotFoundException只是Resources.getSystem().getString(event.name)个对象中的onBindViewHolder()个,因此我认为这不是问题所在。

localEvents

我希望有一种与val类似的方法,可以“解码” Array变量的PlaceObject值并检索与之关联的class LocalEventsAdapter(private val localEvents : Array<PlaceObject>) : RecyclerView.Adapter<LocalEventsAdapter.LocalEventHolder>() { private val TAG:String = "LocalEventsAdapter" // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder. class LocalEventHolder(view:View) : RecyclerView.ViewHolder(view) { private var v : View = view var img : ImageView? = view.findViewById(R.id.localEventImg) var txt : TextView? = view.findViewById(R.id.localEventTXV) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalEventHolder { // Create a new view val eventName = LayoutInflater.from(parent.context) .inflate(R.layout.local_event_rcv_item,parent,false) // set the view's size, margins, paddings and layout parameters // ... return LocalEventHolder(eventName) } override fun onBindViewHolder(holder: LocalEventHolder, pos: Int) { // get element from your dataset at this position // replace the contents of the view with that element val event : PlaceObject = localEvents[pos] val eventName : String = event.name.toString() //Resources.getSystem().getString(event.name) holder.txt!!.text = eventName//TODO:sp Above commented line throws ResourceNotFoundException holder.img?.setImageDrawable(determineImgRes(eventName,pos)) if(holder.img == null) Log.d(TAG,"Image is null") } private fun determineImgRes(name:String, pos : Int): Drawable? { return when(name) { "Test Name" -> R.drawable.miaoulia_event.toDrawable() else -> R.drawable.local_events_placeholder.toDrawable() //TODO:sp Drawable isn't loading correctly, getting purple solid drawable instead } } // Return the size of your dataset (invoked by the layout manager) override fun getItemCount() = localEvents.size } ,但是我似乎找不到合适的。我在这里想念什么?

0 个答案:

没有答案