意图没有延续到下一个活动,一些小的遗漏

时间:2018-05-04 16:50:10

标签: android-intent firebase-realtime-database

我已经使用堆栈溢出将我的事件页面中的适配器位置使用Firebase Recycler View传递到我的详细视图,这样我就可以显示该事件,但是我写的代码并没有。似乎工作。

我确定它是正确的,但我错过了一些明显的东西。

这是我的MainActivity

公共类EventsDisplayActivity扩展了AppCompatActivity {

private RecyclerView mRecylerView;
private DatabaseReference mDatabase;
private EditText mSearch;
private FirebaseRecyclerAdapter<Events, EventsDisplayActivity.EventsViewHolder> mEventsAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_events_display);

    setTitle("Events");

    //"Events" here will reflect what you have called your database in Firebase.
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Events");
    mDatabase.keepSynced(true);

    mRecylerView = findViewById(R.id.result_list);
    mSearch = findViewById(R.id.editTextSearch);




    DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference().child("Events");
    Query query = dbRef.orderByKey();
    //Query search = dbRef.orderByChild("name").startAt(searchText).endAt(searchText + "\uf8ff");

    mRecylerView.hasFixedSize();
    mRecylerView.setLayoutManager(new LinearLayoutManager(this));

    FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Events>().setQuery(query, Events.class).build();

    mEventsAdapter = new FirebaseRecyclerAdapter<Events, EventsDisplayActivity.EventsViewHolder>(options) {
        @Override
        protected void onBindViewHolder(EventsViewHolder holder, final int position, final Events model) {
            holder.setName(model.getName());
            holder.setDescription(model.getDescription());
            holder.setImage(getBaseContext(), model.getImage());
        }

        @Override
        public EventsDisplayActivity.EventsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.event_list, parent, false);

            return new EventsDisplayActivity.EventsViewHolder(view);
        }
    };

    mRecylerView.setAdapter(mEventsAdapter);
}

@Override
public void onStart() {
    super.onStart();
    mEventsAdapter.startListening();
}

@Override
public void onStop() {
    super.onStop();
    mEventsAdapter.stopListening();


}

public static class EventsViewHolder extends RecyclerView.ViewHolder{
    View mView;
    public EventsViewHolder(View itemView){
        super(itemView);
        mView = itemView;
        mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = v.getContext();
                Intent intent = new Intent(context, EventDetailActivity.class);
                intent.putExtra(EventDetailActivity.EXTRA_POSITION, getAdapterPosition());
                context.startActivity(intent);
            }
        });
    }

    public void setName(String title){
        TextView post_title = mView.findViewById(R.id.event_title);
        post_title.setText(title);
    }
    public void setDescription(String desc){
        TextView post_desc = mView.findViewById(R.id.event_desc);
        post_desc.setText(desc);
    }
    public void setImage(Context context, String image){
        ImageView post_image = mView.findViewById(R.id.event_image);
        Picasso.with(context).load(image).into(post_image);
    }
}

}

这是详细的活动,由于某种原因没有得到意图。

public class EventDetailActivity扩展AppCompatActivity {

public static final String EXTRA_POSITION = "position";
private DatabaseReference mDatabase;
private DatabaseReference mEventReference;
private ValueEventListener mEventListener;
private String mEventKey;

private TextView mDetailName;
private TextView mDetailDesc;
private ImageView mDetailImage;
private static final String TAG = "EventDetailActivity";


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_event_detail);

    //Getting the selected event from intent
    mEventKey = getIntent().getStringExtra(EXTRA_POSITION);
    if(mEventKey == null) {
        throw new IllegalArgumentException("Must pass EXTRA_POSITION");
    }
    //Init the DB
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Events").child(mEventKey);
    mDatabase.keepSynced(true);


    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // Set Collapsing Toolbar layout to the screen
    CollapsingToolbarLayout collapsingToolbar =
            findViewById(R.id.collapsing_toolbar);
    // Set title of Detail page
    // collapsingToolbar.setTitle(getString(R.string.item_title));

    //Init Views
    mDetailName = findViewById(R.id.event_title_detail);
    mDetailDesc = findViewById(R.id.event_desc_detail);
    mDetailImage = findViewById(R.id.event_image_detail);
}

public void onStart() {
    super.onStart();

    // Event Listener to the view
    // [Start event_value_event_listener]
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get Event Object and use the values to update said UI
            Events events = dataSnapshot.getValue(Events.class);
            // [START_EXCLUDE]
            mDetailName.setText(events.name);
            mDetailDesc.setText(events.description);
            // [END_EXCLUDE]]
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            // [START_EXCLUDE]
            Toast.makeText(EventDetailActivity.this, "Failed to load events.",
                    Toast.LENGTH_SHORT).show();
            // [END_EXCLUDE]

        }
    };
    mEventReference.addValueEventListener(eventListener);
    // [END post_value_event_listener]

    // Keep copy of post listener so we can remove it when app stops
    mEventListener = eventListener;
}

@Override
public void onStop() {
    super.onStop();
    // Remove post value event listener
    if (mEventListener != null) {
        mEventReference.removeEventListener(mEventListener);
    }
}

}

欣赏它!

2 个答案:

答案 0 :(得分:0)

我检查了你的代码,看起来是正确的,我唯一的注意是RecyclerView.ViewHolder.getAdapterPosition()返回一个Integer原语,而不是一个字符串。

因此,在这种情况下,在您的详细活动中,检索意图的代码实际应该是:

mEventKey = getIntent().getIntExtra(EXTRA_POSITION, 0);

如果未设置0EXTRA_POSITION是默认值。

以下是Intent.getIntExtra上的官方文档:https://developer.android.com/reference/android/content/Intent#getIntExtra

答案 1 :(得分:0)

我在使用此代码时遇到了一些问题。

首先,适配器从0开始计数,但我的数据库从1开始。所以我暂时解决了这个问题,并将在以后订购我的数据库。

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $viewFolder = '';

    protected $viewType = '';

    protected $viewVariables = [];

    protected function setVariable($key, $value)
    {
        $this->viewVariables[$key] = $value;
    }

    protected function viewRender($view)
    {
        return view($this->viewFolder.'.pages.'.$this->viewType.'.'.$view, $this->viewVariables);
    }
}

我需要将上下文强制转换为主事件活动的字符串。

最后,使用Log.d,我检查了我是否得到了我需要的结果,结果证明它工作正常!

intent.putExtra(EventDetailActivity.EXTRA_POSITION, String.valueOf(getAdapterPosition() +1));