I made one NewsAdapter with image and two texts.When u click on image it ll lead you to new activity.Now i want to pass image and text's to new activity.i know with putExtra method you can pass data but i don't know how can i use it here.
this is my News_Fragment
public class News_Fragment extends Fragment {
private List<News> newsList = new ArrayList<>();
private RecyclerView recyclerView;
private NewsAdapter newAdapter;
BottomBar bottombar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.News_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(newAdapter);
newAdapter = new NewsAdapter(newsList,getContext());
// Inflate the layout for this fragment
JSONObject jsonObject = new JSONObject();
new NewsTask() {
#Override
protected void onPostExecute(APIResponse apiResponse) {
if(apiResponse != null && apiResponse.data != null & apiResponse.data.size()>0) {
newsList = apiResponse.data;
//apiResponse.data.toArray();
//newAdapter.notifyDataSetChanged();
newAdapter = new NewsAdapter(newsList,getContext());
recyclerView.setAdapter(newAdapter);
}
Log.i("resp", "onPostExecute");
}
}.execute(jsonObject);
return rootView;
}
}
this is NewsAdapter
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {
private List<News> newsList;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView image,nextArrowimage;
public TextView desc;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.News_title);
image = (ImageView) view.findViewById(R.id.News_imageView);
nextArrowimage = (ImageView)view.findViewById(R.id.news_NextArrow);
desc = (TextView) view.findViewById(R.id.News_desc);
}
}
public NewsAdapter(List<News> newsList,Context context) {
this.newsList = newsList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_list_row, parent, false);
MyViewHolder holder = new MyViewHolder(itemView);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final News news = newsList.get(position);
holder.title.setText(news.getTitle());
//holder.image.setImageResource(Integer.parseInt(news.getImage()));
context = holder.image.getContext();
holder.nextArrowimage.setImageResource(R.drawable.nextbutton);
//Picasso.with(context).load("https://www.simplifiedcoding.net/wp-content/uploads/2015/10/advertise.png").resize(100,100).into(holder.image);
Picasso.with(context).load("http://bitstobyte.in/upload/"+news.getImage()).placeholder(R.drawable.ic_favorite_white_24dp).error(R.drawable.ic_map_24dp).resize(100,100).into(holder.image);
//Picasso.with(context).load("http://bitstobyte.in/upload/"+ news.getImage()).resize(100,100).into(holder.image);
holder.desc.setText(news.getDesc().trim());
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView title = (TextView)v.findViewById(R.id.News_title);
TextView desc = (TextView)v.findViewById(R.id.News_desc);
String str3 = "http://bitstobyte.in/api/news/"+getItemId(position)+news.getImage();
Intent intent = new Intent(context.getApplicationContext(), News_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intent);
intent.putExtra("title",str3);
Toast.makeText(context, "You Clicked " + newsList.get(position), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return newsList.size();
}
}
this is my News_Activity
public class News_Activity extends AppCompatActivity {
TextView textView1,
textView2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#fdfafa'> News View </font>"));
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
//upArrow.setColorFilter(getResources().getColor(R.color.ActionBarText), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String Title1 = getIntent().getStringExtra("title");
textView1 = (TextView)findViewById(R.id.activity_news_Title);
textView1.setText(Title1);
textView2 = (TextView)findViewById(R.id.activity_news_desc);
textView2.setText(Title1);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home){
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
From the adapter you can call this way ->
Intent intent = new Intent(context,News_Activity.class);
intent.putExtra("image",IMAGE_URL);
intent.putExtra("data", DATA_TO_PASS);
context.startActivity(intent);
Intent intent = new Intent(context, News_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",str3);
context.startActivity(intent);
or
Intent intent = new Intent(getActivity(), News_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",str3);
getActivity().startActivity(intent);
Did you try putting the data into intent before actually starting it?? And use getActivity() or directly context instead of context.getApplicationContext()
You need to putExtras into the intent before starting the activity to pass the values :)
The issue is the Intent flag FLAG_ACTIVITY_NEW_TASK. This opens the activity in a new task which is probably why the data isn't passed properly.
for similar issue see:
Intent from notification does not have extras
Do the following:
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView title = (TextView)v.findViewById(R.id.News_title);
TextView desc = (TextView)v.findViewById(R.id.News_desc);
String str3 = "http://bitstobyte.in/api/news/"+getItemId(position)+news.getImage();
Intent intent = new Intent(context.getApplicationContext(), News_Activity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",str3);
context.getApplicationContext().startActivity(intent);
Toast.makeText(context, "You Clicked " + newsList.get(position), Toast.LENGTH_LONG).show();
}
});
If you want to pass image , you can pass it by converting to bitmap and use it.
try{
String str3 = "http://bitstobyte.in/api/news/"+getItemId(position)+news.getImage();
URL url = new URL(str3);
Bitmap imagebitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Intent intent = new Intent(context.getApplicationContext(), News_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intent);
intent.putExtra("title",str3);
intent.putExtra("imagebitmap", imagebitmap);
context.startActivity(intent);
} catch (Exception e) {
Log.error("Exception", e);
}
For getting data..
Intent intent = getIntent();
String title = getIntent().getExtras().getString("title");
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("imagebitmap");
Thanks..
Related
I built an application that read contacts from a phone (in this case my phone). For the activity where contacts has been displayed, I used TabLayout along with a ViewPager. For displaying the contacts I used RecyclerView. The point is that I handle it how to read contacts and my next movement after that was to open an external activity (MessageToContact_Activity) after clicking on a contact. In present in this activity (MessageToContact_Activity) I want to send a message to the contact that I have selected and for that firstly I am trying to set the contact's name and number to the toolbar's title and subtitle. Instead of default ActionBar I've decided to use a toolbar because is more flexible. The problem is that I don't know how to get the values of name and number and use them into MessageToContact_Activity.
Here is the implementation for Contacts_Fragment:
public class Contacts_Fragment extends Fragment {
View v;
public Contacts_Fragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.contacts_fragment, container, false);
RecyclerView recyclerView = v.findViewById(R.id.recycleView_search);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager = linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
ContactsAdapter adapter = new ContactsAdapter(getContext(), getContacts());
recyclerView.setAdapter(adapter);
return v;
}
private List<ContactModel> getContacts() {
List<ContactModel> list = new ArrayList<>();
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_CONTACTS}, 1);
}
Cursor cursor = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.moveToNext()) {
list.add(new ContactModel(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
)), cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
return list;
}
}
Here is the implementation for ContactsAdapter:
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
private List<ContactModel> mListContacts;
public ContactsAdapter(Context context, List<ContactModel> listContacts){
this.mContext = context;
this.mListContacts = listContacts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.item_contact,parent, false);
final ViewHolder viewHolder = new ViewHolder(view);
viewHolder.item_contact.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Toast.makeText(mContext, "Test Click "+String.valueOf(viewHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
/*This is where I've tried to get them with setters and use them
with getters in MessageToContact_Activity*/
String name = mListContacts.get(viewHolder.getAdapterPosition()).getName();
String number = mListContacts.get(viewHolder.getAdapterPosition()).getNumber();
MessageToContact_Activity mC = new MessageToContact_Activity();
mC.setName(name);
mC.setNumber(number);
/*----------------------------------------------------------------------------*/
onContactClick(view);
}
});
return viewHolder;
}
public void onContactClick(View v){
Intent myIntent = new Intent(v.getContext(), MessageToContact_Activity.class);
mContext.startActivity(myIntent);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
TextView c_name, c_number;
c_name = holder.cV_name;
c_number = holder.cV_number;
c_name.setText(mListContacts.get(position).getName());
c_number.setText(mListContacts.get(position).getNumber());
}
#Override
public int getItemCount() {
return mListContacts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView cV_name, cV_number;
AppCompatImageButton messageButton;
private LinearLayout item_contact;
public ViewHolder(View itemView){
super(itemView);
cV_name = itemView.findViewById(R.id.name_contact);
cV_number = itemView.findViewById(R.id.phone_contact );
messageButton = itemView.findViewById(R.id.message_button);
item_contact = (LinearLayout) itemView.findViewById(R.id.contact_item_id);
}
}
}
Where you see some code between /**..*/ and /**..*/, I just tried to isolate my methods of getting the values of name and number and to use them for setting the title and subtitle from MessageToContact_Activity.
Here is the implementation for MessageToContact_Activity:
public class MessageToContact_Activity extends AppCompatActivity{
private String name, number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_to_contact);
Toolbar toolbar = findViewById(R.id.messageToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/*************************/
getSupportActionBar().setTitle(getName());
getSupportActionBar().setSubtitle(getNumber());
/*************************/
}
/*************************/
public MessageToContact_Activity(){}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
/*************************/
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
Here are the items of a contact :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Contact Name"
android:id="#+id/name_contact" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number"
android:id="#+id/phone_contact"/>
</LinearLayout>
Here is the output when I use getSupportActionBar().setTitle(getName()); and getSupportActionBar().setSubtitle(getNumber());
Here is the output when I use getSupportActionBar().setTitle("Name"); and getSupportActionBar().setSubtitle("Number");
I will be so thankful to anyone who could help me. I have a hunch that the solution is not so hard but I still don't know it. And forgive me if there are some things wrong in my code but I'm still at the beginning with android application development.
Activities are not created using new MyActivity(), instead they need to be launched using an intent, as in:
Intent i = new Intent(this, MyActivity.class);
startActivity(i);
If you need to pass to your new activity some parameters, you add them to your intent as extras, like so:
Intent i = new Intent(this, MyActivity.class);
i.putExtra("name", "Bob");
i.putExtra("number", "12345");
startActivity(i);
So in your case, you need to replace your onClick method with something like this:
#Override
public void onClick(View view) {
String name = mListContacts.get(viewHolder.getAdapterPosition()).getName();
String number = mListContacts.get(viewHolder.getAdapterPosition()).getNumber();
Intent myIntent = new Intent(v.getContext(), MessageToContact_Activity.class);
myIntent.putExtra("name", name);
myIntent.putExtra("number", number);
mContext.startActivity(myIntent);
}
Then in your MessageToContact_Activity you can access those extras via:
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
String number = extras.getString("number");
I am trying to send an ArrayList from NoteActivity to MainActivity.
ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_pad);
final FloatingActionButton button =
(FloatingActionButton)findViewById(R.id.save_button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SaveData();
}
});
}
public void SaveData()
{
FileOutputStream outputStream;
try
{
EditText editText = findViewById(R.id.textView3);
final String str = editText.getText().toString();
String content = findViewById(R.id.textView).toString();
Log.d("Test","inside try block");
outputStream = openFileOutput(str, Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
Toast.makeText(getApplicationContext(),"Note
saved",Toast.LENGTH_SHORT).show();
Log.d("Test","save done");
final String str1 = editText.getText().toString();
data.add(str1);
SendData();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void SendData()
{
EditText editText = findViewById(R.id.textView3);
Log.d("Check","str:"+data);
Intent intent = new Intent(NotePad.this,MainActivity.class);
intent.putExtra(EXTRA_MESSAGE, data);
startActivity(intent);
}
}
My Main Activity
public class MainActivity extends AppCompatActivity
{
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<String> notes = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
notes = intent.getStringArrayListExtra(NotePad.EXTRA_MESSAGE);
Log.d("Check","title added: "+notes);
final FloatingActionButton button =
(FloatingActionButton)findViewById(R.id.add_notebutton);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,NotePad.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView)findViewById(R.id.recycle_list);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(notes);
recyclerView.setAdapter(mAdapter);
}
}
my Adapter code
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
ArrayList<String> Notes_list = new ArrayList<String>();
public MyAdapter(ArrayList<String> notes)
{
Notes_list = notes;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_items,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position)
{
holder.mTextView.setText(Notes_list.get(position));
}
#Override
public int getItemCount()
{
return Notes_list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
TextView mTextView;
public MyViewHolder(#NonNull View itemView)
{
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.view_holder);
}
}
}
I dont receive any data in my notes (arrayList). When I run the code
The app instantly crashes with a null pointer exception.
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int
java.util.ArrayList.size()' on a null object reference at
com.example.quicknote.MyAdapter.getItemCount(MyAdapter.java:39)
You are trying to pass ArrayList and you read data from intent with getStringArrayListExtra method. You have to put data like this:
intent.putStringArrayListExtra(EXTRA_MESSAGE, data);
Edit: Check if intent has key:
if (intent.hasExtra(NotePad.EXTRA_MESSAGE)) {
notes = intent.getStringArrayListExtra(NotePad.EXTRA_MESSAGE);
}
Note: If this is just a playground it is OK. But if you trying to
build something then your architecture is wrong. It is not a good idea
to pass same array every time between two activity. You can use
startActivityForResult method and get new note onActivityResult method
of MainActivity.
Try this:-
Intent intent = new Intent(NotePad.this,MainActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("EXTRA_MESSAGE", data);
intent.putExtras(bundle);
//in MainActivity.class
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
ArrayList<String> data=(ArrayList<String>)bundle.getSerializable("EXTRA_MESSAGE");
The best way given in android document to send the arraylist or any custom object from one activity to another to Try the light weight process for this in android
Read the full overview about it https://developer.android.com/reference/android/os/Parcelable
hope it will help for you
I have a ListView developed in Android Studio, I have a few items that will go to a specific activity however the majority of the items will go to a Detail_Activity. The problem that I am having is that I don't know how to get the image and title text from the ListView to display on the Detail_Activity. Can someone explain how I can make this happen? Thanks
I have tried to use the code that I developed as shown but it will not display the image or name on the Detail_Activity when the row is clicked.
Here is the code minus all the list items in MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
final ArrayList<Object> list = new ArrayList<>();
list.add(new String("Government Codes"));
list.add(new LTCItem("Reciprocity", "Agreements With Other States", R.drawable.handshake));
listView.setAdapter(new LTCAdapter(this, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 1) {
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
}
if (position == 2) {
Intent intent = new Intent(MainActivity.this, Activity2.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this, Detail.class);
startActivity(intent);
}
}
});
}
}
Here is the code from the Detail_Activity.java file:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Detail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
}
Here is the code from the Item.java file:
public class LTCItem {
private String name;
private String subtitle;
private int image;
public LTCItem(String name, String subtitle, int image) {
this.name = name;
this.subtitle = subtitle;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
Here is the code from the Adapter.java file:
public class LTCAdapter extends BaseAdapter {
ArrayList<Object> list;
private static final int LTC_Item = 0;
private static final int HEADER = 1;
private LayoutInflater inflater;
public LTCAdapter(Context context, ArrayList<Object> list) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (list.get(position) instanceof LTCItem) {
return LTC_Item;
} else {
return HEADER;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
switch (getItemViewType(i)) {
case LTC_Item:
view = inflater.inflate(R.layout.item_list_view, null);
break;
case HEADER:
view = inflater.inflate(R.layout.item_listview_header, null);
break;
}
}
switch (getItemViewType(i)) {
case LTC_Item:
ImageView image = (ImageView) view.findViewById(R.id.itemListViewImgIcon);
TextView name = (TextView) view.findViewById(R.id.itemListViewTxtTopicName);
TextView subtitle = (TextView) view.findViewById(R.id.itemListViewTxtTopicSubtitle);
image.setImageResource(((LTCItem) list.get(i)).getImage());
name.setText(((LTCItem) list.get(i)).getName());
subtitle.setText(((LTCItem) list.get(i)).getSubtitle());
break;
case HEADER:
TextView title = (TextView) view.findViewById(R.id.itemListViewHeader);
title.setText(((String) list.get(i)));
break;
}
return view;
}
}
I expect the Detail_Activity to display name, image from the ListView when clicked, and I will add a description text to the Detail_Activity as well.
for this, you just have to pass your data using intent put extra methods like this in the first activity
Intent = intent = new Intent(this , Detail.class)
intent.putString("name",list.get(position).getName());
intent.putString("image",list.get(position).getImage());
startctivity(intent)
Now just get your data in the Detail activity's onCreatae method just like this
if(getIntent().getExtras()!=null){
String namae = getIntent().getStringExtra("name");
String image= getIntent().getStringExtra("image");
}
Now you can use your image or name where you want to use them
You should add it in intent extra
From main activity:
Intent i = new Intent(MainActivity.this, DetailActivity.class);
i.putExtra("title",list.get(position).getTitle)
startActivity(i);
In detail activity:
String title = getIntent().getStringExtra("title");
I have two activities, one shows the movie list, and the other shows movie details. I have a shared element transition on a movie's poster. It works fine when I use with linearlayoutmanager, but when I use a gridLayoutManager for the recyclerView, after I press back button get back from the detail activity, the other image becomes blank as shown here.image
In this picture, I clicked on x-men's movie poster, but the image next to it becomes blank.
I have set a unique transitionName for every item. It's probably not the reason.
this is my activity
public class MainActivity extends AppCompatActivity implements MovieGridAdapter.OnItemClickListener {
private MovieGridAdapter mAdapter;
private int mPosition;
private Toolbar mToolbar;
private RecyclerView mMovieGridLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mMovieGridLayout = (RecyclerView) findViewById(R.id.movie_grid);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
mMovieGridLayout.setLayoutManager(gridLayoutManager);
mAdapter = new MovieGridAdapter();
mAdapter.setOnItemClickListener(this);
mMovieGridLayout.setAdapter(mAdapter);
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortBy = sharedPreferences.getString(getString(R.string.sort_by_key), getString(R.string.popularity));
MoviePuller.getMoviePuller().discoverMovies(sortBy);
}
#Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingActivity.class);
startActivity(intent);
return true;
} else if (id == R.id.action_refresh) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortBy = sharedPreferences.getString(getString(R.string.sort_by_key), getString(R.string.popularity));
MoviePuller.getMoviePuller().discoverMovies(sortBy);
}
return super.onOptionsItemSelected(item);
}
#Subscribe
public void onPullSuccessEvent(Integer eventId) {
if (eventId == EventId.PULL_SUCCESS) {
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onItemClick(View v, int position) {
mPosition = position;
Intent intent = new Intent(this, MovieDetailActivity.class);
ImageView imageView = (ImageView) v.findViewById(R.id.poster);
TextView title = (TextView) v.findViewById(R.id.title);
ActivityOptionsCompat scaleUpAnimationOptions = createScaleUpAnimationOptions(imageView,title);
intent.putExtra(Constants.POSITION, position);
ActivityCompat.startActivity(this, intent, scaleUpAnimationOptions.toBundle());
}
private ActivityOptionsCompat createScaleUpAnimationOptions(View view, View view2) {
Pair<View,String> pair = new Pair<>(view,view.getTransitionName());
Pair<View,String> pair2 = new Pair<>(view2,view2.getTransitionName());
Pair<View,String> pair3 = new Pair<View, String>(mToolbar,mToolbar.getTransitionName());
// View statusBar = getWindow().getDecorView().findViewById(android.R.id.navigationBarBackground);
// Pair<View,String> pair4 = new Pair<>(statusBar, ViewCompat.getTransitionName(statusBar));
return ActivityOptionsCompat.makeSceneTransitionAnimation(this,pair,pair2,pair3);
}
}
this is my adapter
public class MovieGridAdapter extends RecyclerView.Adapter<MovieGridAdapter.MyHolder> {
private JSONArray mMovies;
private OnItemClickListener mOnItemClickListener;
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView cardView = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie, parent, false);
return new MyHolder(cardView,mOnItemClickListener);
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
mMovies = MoviePuller.getMovies();
if (mMovies != null) {
return mMovies.length();
}
return 0;
}
public interface OnItemClickListener {
void onItemClick(View v, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView mPoster;
public TextView mTitle;
private OnItemClickListener mOnItemClickListener;
public MyHolder(View itemView, OnItemClickListener listener) {
super(itemView);
mOnItemClickListener = listener;
mTitle = (TextView) itemView.findViewById(R.id.title);
mPoster = (ImageView) itemView.findViewById(R.id.poster);
itemView.setOnClickListener(this);
}
public void bind(int position) {
if (mMovies != null) {
try {
JSONObject movie = mMovies.getJSONObject(position);
String title = movie.getString(Constants.KEY_TITLE);
String posterPath = movie.getString(Constants.KEY_POSTER_PATH);
Picasso.with(itemView.getContext()).
load(MoviePuller.POSTER_BASE_URL + posterPath).into(mPoster);
mPoster.setTransitionName(itemView.getResources().getString(R.string.transition_poster) + position);
mTitle.setText(title);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v, getAdapterPosition());
}
}
}
}
this is my detail activity
public class MovieDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_moviedetail);
Slide slide = new Slide(Gravity.BOTTOM);
slide.addTarget(R.id.divider);
slide.addTarget(R.id.vote_average);
slide.addTarget(R.id.release_date);
slide.addTarget(R.id.plot_synopsis);
slide.addTarget(R.id.rating);
slide.addTarget(R.id.divider1);
getWindow().setEnterTransition(slide);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ImageView poster = (ImageView) findViewById(R.id.poster);
TextView tvTitle = (TextView) findViewById(R.id.title);
RatingBar voteAverage = (RatingBar) findViewById(R.id.vote_average);
TextView tvReleaseDate = (TextView) findViewById(R.id.release_date);
TextView tvPlotSynopsis = (TextView) findViewById(R.id.plot_synopsis);
TextView tvRating = (TextView) findViewById(R.id.rating);
int position = getIntent().getIntExtra(Constants.POSITION, -1);
poster.setTransitionName(getString(R.string.transition_poster) + position);
JSONArray movies = MoviePuller.getMovies();
if(movies != null && movies.length() > position) {
try {
JSONObject movie = movies.getJSONObject(position);
String title = movie.getString(Constants.KEY_TITLE);
String poster_path = movie.getString(Constants.KEY_POSTER_PATH);
String release_date = movie.getString(Constants.KEY_RELEASE_DATE);
String vote_average = movie.getString(Constants.KEY_VOTE_AVERAGE);
String overview = movie.getString(Constants.KEY_OVERVIEW);
String id = movie.getString(Constants.KEY_ID);
MoviePuller.getMoviePuller().getTrailers(id);
MoviePuller.getMoviePuller().getReviews(id);
toolbar.setTitle(title);
setSupportActionBar(toolbar);
Picasso.with(this).load(MoviePuller.POSTER_BASE_URL+poster_path).into(poster);
tvTitle.setText(title);
tvReleaseDate.setText(release_date);
tvPlotSynopsis.setText(overview);
voteAverage.setRating(Float.parseFloat(vote_average)/2);
tvRating.setText(vote_average);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Subscribe
public void onEvent(EventId eventId){
if(eventId.mId == EventId.GET_TRAILER_SUCCESS){
JSONArray trailerArray = (JSONArray) eventId.mEventObject;
}else if(eventId.mId == EventId.GET_REVIEW_SUCCESS){
JSONArray reviewArray = (JSONArray) eventId.mEventObject;
}
}
}
the recyclerView xml is like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activities.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/movie_grid"/>
</RelativeLayout>
What should i do to avoid this?
i record a gif
I guess the problem is with the way you are passing positions of the views between DetailActivity and the MainActivity.
In MainActivity onItemClick() method replace this
intent.putExtra(Constants.POSITION, position);
with this
Bundle bundle = new Bundle();
bundle.putInt(Constants.POSITION, position);
intent.putExtras(bundle);
And in DetailActivity replace this
int position = getIntent().getIntExtra(Constants.POSITION, -1);
with this
int position = getIntent().getExtras().getInt(Constants.POSITION);
Also, what is itemView in MyHolder class, bind() method. You need to pass context to the adapter and use that.
Create this constructor in MovieGridAdapter :
public MovieGridAdapter(Context context) {
this.context = context;
}
and In bind() method replace occurences of itemView:
Picasso.with(context).load(MoviePuller.POSTER_BASE_URL + posterPath).into(mPoster);
mPoster.setTransitionName(context.getString(R.string.transition_poster) + position);
Initialize MovieGridAdapter in MainActivity in this way:
mAdapter = new MovieGridAdapter(this);
I'm using Parse.com to populate a ListView in the second activity of my app. Clicking on an item in the ListView opens up a third activity. The problem is that when using the Up button to return to the second activity the ListView is gone. For some reason this behavior does not occur when the Back button is used. Also, it does not occur when just using a normal query in the 2nd activity. Something about the query.whereEqualsTo("department", department) line is throwing the whole thing off.
1st Activity:
public class MainActivity extends ActionBarActivity {
private Button mMEButton;
private Button mCEButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMEButton = (Button)findViewById(R.id.meButton);
mCEButton = (Button)findViewById(R.id.ceButton);
mMEButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProfessorsActivity.class);
intent.putExtra("department", "ME");
startActivity(intent);
}
});
mCEButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProfessorsActivity.class);
intent.putExtra("department", "CE");
startActivity(intent);
}
});
}
2nd Activity:
public class ProfessorsActivity extends ActionBarActivity {
private ParseQueryAdapter<ParseObject> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_professors);
Intent intent = getIntent();
final String department = intent.getStringExtra("department");
ParseQueryAdapter.QueryFactory<ParseObject> factory =
new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Professor");
query.whereEqualTo("department", department);
return query;
}
};
adapter = new ParseQueryAdapter<ParseObject>(this, factory) {
#Override
public View getItemView(ParseObject professor, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.professor_item, null);
}
TextView contentView = (TextView) v.findViewById(R.id.professorNameTextView);
contentView.setText(professor.getString("lastName") + ", " + professor.getString("firstName"));
return v;
}
};
//adapter.setTextKey("lastName");
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ParseObject tappedProfessor = adapter.getItem(position);
String professorId = tappedProfessor.getObjectId();
Intent intent = new Intent(ProfessorsActivity.this, OfficeHoursActivity.class);
intent.putExtra("professorId", professorId);
startActivity(intent);
}
});
}
3rd Activity:
public class OfficeHoursActivity extends ActionBarActivity {
private TextView mNameTextView;
private TextView mTimeTextView1;
private TextView mDaysTextView1;
private TextView mTimeTextView2;
private TextView mDaysTextView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_office_hours);
Intent intent = getIntent();
String professorId = intent.getStringExtra("professorId");
mNameTextView = (TextView) findViewById(R.id.professorName);
mTimeTextView1 = (TextView) findViewById(R.id.officeHourTime1);
mDaysTextView1 = (TextView) findViewById(R.id.officeHourDays1);
mTimeTextView2 = (TextView) findViewById(R.id.officeHourTime2);
mDaysTextView2 = (TextView) findViewById(R.id.officeHourDays2);
mNameTextView.setVisibility(INVISIBLE);
mTimeTextView1.setVisibility(INVISIBLE);
mDaysTextView1.setVisibility(INVISIBLE);
mTimeTextView2.setVisibility(INVISIBLE);
mDaysTextView2.setVisibility(INVISIBLE);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Professor");
// Retrieve the object by id
query.getInBackground(professorId, new GetCallback<ParseObject>() {
public void done(ParseObject currentProfessor, ParseException e) {
if (e == null) {
mNameTextView.setText(currentProfessor.getString("lastName") + ", " + currentProfessor.getString("firstName"));
mTimeTextView1.setText(currentProfessor.getString("start1") + " - " + currentProfessor.getString("end1"));
mDaysTextView1.setText(currentProfessor.getString("days1"));
mNameTextView.setVisibility(VISIBLE);
mTimeTextView1.setVisibility(VISIBLE);
mDaysTextView1.setVisibility(VISIBLE);
if (currentProfessor.getString("start2") != null) {
mTimeTextView2.setText(currentProfessor.getString("start2") + " - " + currentProfessor.getString("end2"));
mDaysTextView2.setText(currentProfessor.getString("days2"));
mTimeTextView2.setVisibility(VISIBLE);
mDaysTextView2.setVisibility(VISIBLE);
}
} else {
//something went wrong
}
}
});
The up button creates a new instance of the parent activity by default.
If you want it to behave as the back button just override "onOptionsItemSelected" in "OfficeHoursActivity" and do the following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void ListView(){
ParseQueryAdapter.QueryFactory<ParseObject> factory =
new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Professor");
query.whereEqualTo("department", department);
return query;
}
};
adapter = new ParseQueryAdapter<ParseObject>(this, factory) {
#Override
public View getItemView(ParseObject professor, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.professor_item, null);
}
TextView contentView = (TextView) v.findViewById(R.id.professorNameTextView);
contentView.setText(professor.getString("lastName") + ", " + professor.getString("firstName"));
return v;
}
};
//adapter.setTextKey("lastName");
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
Now call this method from onResume(). Don't call it from onCreate().
#Override
public void onResume(){
super.onResume();
ListView();
}
Now check.. May be you problem will solved..!!!
I solved this problem by adding the following tag to the second activity within the AndroidManifest.xml file.
android:launchMode="singleTop"
This prevents the Up button from recreating the activity when it is clicked.