I've managed to populate an Activity (which we'll call Activity A) with a custom listview which works fine.
When the user clicks on an item from the list of items in Activity A, I want to pass details of that item into Activity B.
This is what my activity A looks like:
public class ChannelList extends Activity implements OnItemClickListener {
public static final String[] names = new String[] { "BBC One", "BBC Two" };
public static final String[] descs = new String[] { "London, SD", "England, SD"};
ListView listView;
List<ChannelItem> channelItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel_list);
channelItems = new ArrayList<ChannelItem>();
for (int i = 0; i < names.length; i++) {
ChannelItem item = new ChannelItem(names[i], descs[i]);
channelItems.add(item);
}
listView = (ListView) findViewById(R.id.listView1);
ChannelListViewAdapter adapter = new ChannelListViewAdapter(this, R.layout.item_channel_list, channelItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// Toast toast = Toast.makeText(getApplicationContext(), "Item " + (position + 1) + ": " + channelItems.get(position), Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
// toast.show();
Intent intent = new Intent(this, ScheduleList.class);
startActivity(intent);
}
}
Based on my interpretation of the Android API documentation, I'm supposed to pass data into the Activity B call using Intent.putExtra();
Question is, how do I pass the name and description elements of the list item that the user clicks on?
For example, when I call Activity B, it should be able to download TV schedule data for BBC One if BBC One is clicked on from the listview. How do I make Activity B know which listitem click triggered Activity B?
How about
intent.putExtra("name", names[position]);
in Activity A's onItemClick method and
String name = getIntent().getStringExtra("name");
in Activity B's onCreate method?
Related
I have a ListView that displays an ArrayList that is dynamically created using an adapter. However, certain elements of each list item view are calculated based on previous item values. I am using Intents to open another activity where the user can edit a selected list item, and the updates are passed back to the main activity. In the main activity I've placed the getIntent, and the associated setters, after the ArrayList is generated and before the adapter. When the main activity is first created the adapter correctly calculates all list view items. But when the user accepts updates in the edit activity and returns to the main activity, only the selected list item is updated. Having the entire list cycle through and update would be fine (it will never be a very long list), but I'm a little surprised that only the selected list item is getting updated. I expected that either the adapter would run as it does when the activity is first created and all items would get updated, or that it wouldn't run at all and none would get updated.
public class MainActivity extends AppCompatActivity {
private final Context thisContext = MainActivity.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView planListView = findViewById(R.id.plan_listview);
final ArrayList<ItemProfile> planSteps = BuildPlan();
if(getIntent().getExtras() != null)
{
int stepNumber = getIntent().getIntExtra("stepNumber", 0);
ItemProfile thisStep = (ItemProfile) getIntent().getSerializableExtra("itemProfile");
planSteps.get(stepNumber-1).setDepth(thisStep.getDepth());
planSteps.get(stepNumber-1).setTime(thisStep.getTime());
planSteps.get(stepNumber-1).setInterval(thisStep.getInterval());
}
ItemsListAdapter planAdapter = new ItemsListAdapter(this, planSteps);
planListView.setAdapter(planAdapter);
planListView.setOnItemClickListener(
new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l)
{
int index = pos-1;
Intent i = new Intent(thisContext, EditItemActivity.class);
i.putExtra("stepNumber", pos);
i.putExtra("stepProfile", planSteps.get(index));
if (index > 0)
{
i.putExtra("groupStart", planSteps.get(index-1).getGroupEnd());
}
startActivity(i);
}
}
);
}
}
Update... I've added the mainActivity code. It creates an ArrayList plan (I'm using a BuildPlan method to populate a dummy plan while I'm developing) then checks for an intent that is returning an updated plan step. If an intent exists the specified step is updated in the plan. The list adapter is then created and set. Finally the clickListener is created and set.
I've done something relatively similar but I used dynamic spinners and listviews from a database.
Here is the code. Basically you invalidate the list view, reset the data and call notifyDataSetChanged() on the adapter.
public ListView lv;
Spinner suburbSpinner;
ArrayAdapter<String> suburbAdapter;
ArrayList<String> suburbs = new ArrayList<>();
ArrayList<Resource> resources = new ArrayList<>();
ArrayAdapter<Resource> arrayAdapter;
public void updateList(String type, String suburb, String businessType, int suburbPos) {
DatabaseHelper db = new DatabaseHelper(this, "fairCanberraDB", null, 1);
lv = findViewById(R.id.list);
// Reset suburb spinner, get new list view resources.
lv.invalidateViews();
resources = db.resourceQuery(type, suburb, businessType);
System.out.println("resource: " + resources);
ArrayList<Resource> suburbQuery = db.resourceQuery(type, "All", businessType);
Spinner suburbSpinner = findViewById(R.id.suburbSpinner);
suburbs.clear();
suburbs.add("All");
for (int x = 0; x < suburbQuery.size(); x++) {
if (suburbs.contains(suburbQuery.get(x).getSuburb())) {
continue;
} else {
suburbs.add(suburbQuery.get(x).getSuburb());
}
}
db.close();
suburbAdapter.notifyDataSetChanged();
arrayAdapter.notifyDataSetChanged();
ArrayAdapter<Resource> arrayAdapter = new ArrayAdapter<Resource>(
this,
android.R.layout.simple_list_item_1,
resources);
lv.setAdapter(arrayAdapter);
if(suburbPos < suburbSpinner.getCount())
{ suburbSpinner.setSelection(suburbPos);}
setSpinnerListener(suburbSpinner);
}
// Register listener for a spinner
public void setSpinnerListener(Spinner spinner)
{
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
Spinner businessTypeSpinner = (Spinner) findViewById(R.id.businessTypeSpinner);
Spinner suburbSpinner = (Spinner) findViewById(R.id.suburbSpinner);
String businessType = businessTypeSpinner.getSelectedItem().toString();
if(businessType.contains("Private"))
{
businessType = "private user";
}
updateList(typeSpinner.getSelectedItem().toString(), suburbSpinner.getSelectedItem().toString(),
businessType, suburbSpinner.getSelectedItemPosition());
}
I have two activities. When an item in a RecyclerView is selected, it takes the user to the second activity and fills in the details with the related RecyclerView item.
In the second RecyclerView activity, there is a Spinner. Depending on the item selected in the spinner, different RecyclerViews become visible/invisible to the user on the second activity.
How do I make it work so that the information is sent from the first activity to command the spinner on what to do?This is how Second Activity looks
SecondActivity.java
public class SecondActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private TextView tv_title, tv_description;
private ImageView PartiesThumbnailImg,PartiesCoverImg;
private RecyclerView RvPartyMembers;
private PartyMembersAdapter partyMembersAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parties_detail);
Spinner spinner = findViewById(R.id.spnConstituencies);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.constituencies, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//ini views
iniViews();
//Setting up members list
setupRvPartyMembers();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
void iniViews() {
RvPartyMembers = findViewById(R.id.rv_party_members);
String partiesTitle = getIntent().getExtras().getString("title");
String partiesDescription = getIntent().getExtras().getString("description");
int imageResourceId = getIntent().getExtras().getInt("imgURL");
int imagecover = getIntent().getExtras().getInt("imgCover");
PartiesThumbnailImg = findViewById(R.id.detail_members_img);
Glide.with(this).load(imageResourceId).into(PartiesThumbnailImg);
PartiesThumbnailImg.setImageResource(imageResourceId);
PartiesCoverImg = findViewById(R.id.detail_members_cover);
Glide.with(this).load(imagecover).into(PartiesCoverImg);
tv_title = findViewById(R.id.tvPartyTitle);
tv_title.setText(partiesTitle);
tv_description = findViewById(R.id.tvPartyDesc);
tv_description.setText(partiesDescription);
}
void setupRvPartyMembers(){
List<PartyMembers> mdata = new ArrayList<>();
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
partyMembersAdapter = new PartyMembersAdapter(this,mdata);
RvPartyMembers.setAdapter(partyMembersAdapter);
RvPartyMembers.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
}
These are the important pieces of code of the FirstActivity.java
#Override
public void onPartiesItemClick(PartiesOireachtas partiesOireachtas, ImageView partiesImageView) {
Intent intent = new Intent(getContext(),PartiesDetailActivity.class);
intent.putExtra("title", partiesOireachtas.getTitle());
intent.putExtra("description",partiesOireachtas.getDescription());
intent.putExtra("imgURL", partiesOireachtas.getThumbnail());
intent.putExtra("imgCover",partiesOireachtas.getCoverPhoto());
and
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//RecyclerView Setup
//int data
lstPartiesOireachtas = new ArrayList<>();
lstPartiesOireachtas.add(new PartiesOireachtas("Fianna Fáil", "example1", R.drawable.fianna_fail_logo,R.drawable.fianna_fail_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Sinn Féin", "example2", R.drawable.sinn_fein_logo,R.drawable.sinn_fein_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Fine Gael", "example4", R.drawable.fine_gael_logo,R.drawable.fine_gael_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Green Party", "example9", R.drawable.green_party_logo,R.drawable.green_party_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Social Democrats", "example3", R.drawable.soc_dems_logo,R.drawable.soc_dems_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Independent", "example2", R.drawable.independent_party_logo,R.drawable.independent_party_cover));
As you probably noticed an activity doesn't have a default constructor, but uses an onCreate(Bundle savedInstanceState) method. This means you should pass your information using this Bundles, or use something like SharedPreferences / SQLite. Since SharedPreferences / SQLite is a bit overkill for this in my opinion, you can add the object upon creating an intent.
Intent intent = new Intent();
intent.putExtra("name", parcelableObject);
If you want to pass a custom object you have to implement the Parcelable interface, this is pretty straightforward since you can basically auto generate all code for this in Android studio (just hit alt-enter a few times). For more information you can check out the following link.
https://developer.android.com/reference/android/os/Parcelable
In the receiving activity you can do the following:
Bundle bundle = getIntent().getExtras();
Object object = bundle.getObject("name"); //Don't forget to cast!
I have declared a ViewModel.class for the RecyclerView an Adapter and I have parsed to the MainActivity and to another Activity so I have the same adapter for both activities.
I can show the parsed data in both activities but the problem it is I cannot take the data of the selected item to MainActivity and then to set to that btnSearch for a click so then I can share between activities the data from the selected item.
Every time when the app is open the first item is selected. What I am trying to achieve is.
Get the item position to the MainActivity so when I click for a button search the data of the selectedItem will going to intent.putExtra and then get the data at another Activity.
If I click the second item and go to another Activity the same item will be selected.
Here is what I have tried so far.
The SearchEngineAdapter.class
public class SearchEngineAdapter extends RecyclerView.Adapter<SearchEngineAdapter.ViewHolder> {
private int selectedItem = 0;
private static RecyclerViewClickListener itemListener;
private Context context;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
public SearchEngineAdapter(Context context, ArrayList<SearchEngine> arrayList, int selectedItem) {
this.context = context;
this.arrayList = arrayList;
this.selectedItem = selectedItem;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
holder.tvIcon.setImageResource(arrayList.get(i).getIcon());
holder.tvId.setText(arrayList.get(i).getId());
holder.tvSearchUrl.setText(arrayList.get(i).getUrl());
final String url = holder.tvSearchUrl.getText().toString();
SharedPreferences sp = context.getSharedPreferences("SavedSelected", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("selected", selectedItem);
editor.apply();
sp = context.getSharedPreferences("SavedSelected", Context.MODE_PRIVATE);
int myIntValue = sp.getInt("selected", -1);
Log.d("Selected", "SharedPreferences" + myIntValue);
if (selectedItem == i) {
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
intent.putExtra("selected", selectedItem);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else {
holder.tvIcon.setBackgroundColor(Color.parseColor("#00000000"));
}
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
int PreviousSelectedItem = selectedItem;
selectedItem = i;
intent.putExtra("selected", selectedItem);
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
}
// ... Other necessary functions.
}
Now the MainActivity.class
RecyclerView paramRecyclerView;
SearchEngineAdapter sEngineAdapter;
paramRecyclerView = findViewById(R.id.lvEngines);
paramRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
paramRecyclerView.setHasFixedSize(true);
Intent intent = getIntent();
int intValue = intent.getIntExtra("selected", 0);
sEngineAdapter = new SearchEngineAdapter(context, arrayList, intValue);
paramRecyclerView.setAdapter(sEngineAdapter);
// Calling network APIs to populate the arrayList.
The onResume function of the MainActivity looks like the following.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
}
This is the click handler defined in MainActivity which send me to another Activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("url", url );
intent.putExtra("name", newEntry);
intent.putExtra("selected", selectedItem2);
startActivity(intent);
}
});
And the other activity which is ActivitySearchEngine.class
public class ActivitySearchEngine extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
public String selectedName;
public int selectedID;
public String selectedSearchUrl;
RecyclerView mListView;
RecyclerView paramRecyclerView;
SearchEngineAdapter sEngineAdapter;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
final Context context = this;
int selectedItem;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
// Variables initialization
// Setting up adapter
paramRecyclerView.setAdapter(sEngineAdapter);
sEngineAdapter.notifyDataSetChanged();
// Calling network APIs to populate the arrayList here
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id", 1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("url");
// Loading the url in a WebView for searching
}
}
I could share the selected item position between these two activities. However, I am not sure how to achieve the behavior of the item is being selected in the RecyclerView of the second activity as well. If I select another item in the RecyclerView of the second activity, the change should be reflected in the first (i.e. MainActivity) as well when I get back to it.
Any help would be appreciated.
There was a lot of changes in the question and hence the last update of this answer below is the final version.
As far as I could understand about the problem, I can see you are very close to the solution if I had understood correctly. The SearchEngineAdapter already has a selectedItem variable in it which can be used for highlighting the item selected in ActivitySearchEngine as well. You just have to modify the adapter a little bit like the following. I am rewriting the adapter here.
public class SearchEngineAdapter extends RecyclerView.Adapter<SearchEngineAdapter.ViewHolder> {
private int selectedItem = 0;
private static RecyclerViewClickListener itemListener;
private Context context;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
// Added another argument to be passed in the constructor
public SearchEngineAdapter(Context context, ArrayList<SearchEngine> arrayList, int selectedItem) {
this.context = context;
this.arrayList = arrayList;
this.selectedItem = selectedItem;
}
#NonNull
#Override
public SearchEngineAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
if (selectedItem == i) {
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
} else {
holder.tvIcon.setBackgroundColor(Color.parseColor("#00000000"));
}
holder.tvIcon.setImageResource(arrayList.get(i).getIcon());
holder.tvId.setText(arrayList.get(i).getId());
holder.tvSearchUrl.setText(arrayList.get(i).getUrl());
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int PreviousSelectedItem = selectedItem;
selectedItem = i;
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView tvId, tvSearchUrl;
ImageView tvIcon;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.ivEngineText);
tvIcon = itemView.findViewById(R.id.ivEngine);
tvSearchUrl = itemView.findViewById(R.id.ivSearchUrl);
}
}
}
Check that, I just have modified the constructor of your adapter, taking another extra variable which is selectedItem. Just pass the selected item position when you are initializing the adapter in both activities. In the default case, you can pass -1, I think you get the idea.
You have passed the selected item position to the ActivitySearchEngine as well. Which can be used for initializing for the desired behavior. Hope that helps!
Update 1:
I would like to suggest you put the following code to your onResume function in the ActivitySearchEngine class. You might consider removing the lines from the onCreate function of your code as well.
#Override
public void onResume() {
super.onResume();
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id", 1); // NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("url");
sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedID);
paramRecyclerView.setAdapter(sEngineAdapter);
}
Update 2:
The RecyclerView in your MainActivity is getting reloaded as you are setting the adapter again to the RecyclerView in the onResume function. Moreover, you are trying to get data from intent which is not available here I think because you have not set any data to be sent to the MainActivity when you return back from the ActivitySearchEngine. Hence, the RecyclerView is reloading again with a fresh set of data.
You might remove the code associated with your RecyclerView from the onResume function of the MainActivity to remove this complication as I think this is not necessary. So the updated onResume function will look like the following.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
}
Update 3:
Take a public static variable in your MainAcitivity and declare it as a global variable like the following.
// Setting 0 as you wanted to put the first item at the first time
// If you do not want that, then initialize with -1
public static int selectedItem = 0;
Now inside your onCreate function, remove the lines for getting the intent.
paramRecyclerView = findViewById(R.id.lvEngines);
paramRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
paramRecyclerView.setHasFixedSize(true);
// Remove the following
// Intent intent = getIntent();
// int intValue = intent.getIntExtra("selected", 0);
// Move the adapter setup to the onResume
// sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedItem);
// paramRecyclerView.setAdapter(sEngineAdapter);
// Calling network APIs to populate the arrayList.
Modify the onResume function in the MainActivity to set up the adapter there.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
// Set the adapter here
sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedItem);
paramRecyclerView.setAdapter(sEngineAdapter);
}
Modify the onClickListener in your adapter like the following. Just add a new line there.
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
int PreviousSelectedItem = selectedItem;
selectedItem = i;
// Set the static value in the MainActivity
// This can be accessed from all other classes
MainActivity.selectedItem = i;
intent.putExtra("selected", selectedItem);
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
Hope that helps!
I started this program by reading in a premade database and has it display on a list, i am currently trying to convert the list to a clickable list that opens up to a new fragment. This is the code i am currently running. The commented out section is the current problem.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 =(Button) findViewById(android.R.id.button1);
db = new MyDatabase(this);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
schedule = db.getSchedule();
ListView listView = (ListView) findViewById(R.id.list);
//listView.setOnItemClickListener(this);
listView.setAdapter(new SimpleCursorAdapter(
MainActivity.this,
R.layout.row,
schedule,
new String[] {"fName", "Calories", "Protein", "Carbs" },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4 },
0));
schedule = db.getSchedule();
ListView listView2 = (ListView) findViewById(R.id.list2);
listView2.setAdapter(new SimpleCursorAdapter(
MainActivity.this,
R.layout.row,
schedule,
new String[] {"fName", "Calories", "Protein", "Carbs" },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4 },
0));
}
});
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Log.i("HelloListView", "You clicked Item: " + id + " at position:" + position);
// Then you start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, Activity2.class);
intent.putExtra("position", position);
// Or / And
intent.putExtra("id", id);
startActivity(intent);
}
listView.setOnItemClickListener(this); will not work because it is being applied to android.view.View.OnClickListener. I have been trying to modify b1.setOnClickListener(new View.OnClickListener(), to try to change its parameters, but I'm not getting any luck. Is there an easy solution I'm not seeing or do i need to reconstruct this code to revolve around a clickable list. Thanks!
Simple, put below code lines in onCreate() of Activity instead of button's onClick() And then implement AdapterView.OnItemClickListener to your Activity.
ListView listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Now on line listView.setOnItemClickListener(this); this refers to your activity class and implemented interface and onItemClick will work.
If your activity is a ListActivity then no need of listView.setOnItemClickListener(this); this line.
Change the Activity to ListActivity and override the method onListItemClick of ListActivity class. Put all the code in the onItemClick of listener to
onListItemClick.
I am a beginner programmer so please bear with me. I am trying to create an app where the item in the list view affects what will be displayed in the next activity. So far, I have the list activity:
public class Primary extends ListActivity{
private static final String[] items = {"Item1", "Item2", "Item3", "item4", "Item5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
TextView heading =(TextView)findViewById(R.id.listViewHeading);
heading.setText("Primary");
}
public void onListItemClick(ListView parent, View v, int position, long id){
}
and for the second activity, I have this:
public class ImageActivity extends Activity{
TextView heading;
ImageView image;
TextView text;
public static final String[] headings={"heading 1", "heading 2", "heading 3", "heading 4", "heading 5",};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_activity);
heading = (TextView)findViewById(R.id.adHeading);
image = (ImageView)findViewById(R.id.adImage);
text =(TextView)findViewById(R.id.adText);
addInfo();
}
private void addInfo() {
heading.setText(headings[x]);
image.setImageResource(images[x]);
text.setText(text[x]);
}
How can i make it so that the heading, image, and text change based on what item in the list view was selected?
In the listview Activity.
Intent i = new Intent(this, ImageActivity.class);
i.putExtra("data", data);
startActivity(i);
The next Acitivty onCreate() method.
final String data = getIntent().getStringExtra("data");
I think u want to set the heading, image and text in second activity, related to first activity's selected index in list.
just do 1 thing, put following code in 1st activity
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(this.getApplicationContext(), ImageActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
so, now u r passing the position of item selected in list.
now, put following code in next activity
private void addInfo()
{
Bundle ext = getIntent().getExtras();
if(ext != null)
{
int pos= ext.getInteger("pos");
// ext.getInt("pos");
heading.setText(headings[pos]);
// hey, frend, you don't have any array for selecting image-name and text
// image.setImageResource(images[x]);
// text.setText(text[x]);
}
}
Use the "extras" feature that are part of an Intent.
When you call start ImageActivity from Primary, you can use a 'extras' to pass information between the two.
See this link for details.
I'll give you a basic example here. When the list item is clicked, put the data that you want ImageActivity to have into the intent using "putExtra".
Intent intent = new Intent(getBaseContext(), ImageActivity.class);
String data = "somedata";
intent.putExtra("DATA", data);
startActivity(intent)
Then, in ImageActivity onCreate, retrieve the data like this:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String data= extras.getString("DATA"); // matches the tag used in putExtra
}
Once you have retrieved the data, set the necessary views.
use below code
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(Primary.this, ImageActivity.class);
intent.putExtra("selected value", item[position]);
startActivity(intent);
}
in ImageActivity class:in oncreate (or you can put item variable as global)
String item = getIntent().getStringExtra("Selected value");