android gridview subitems start activity onclick - java

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i = new Intent(this,second.class);
startActivity(i);
} else if (position == 1) {
Intent i1 = new Intent(this,second.class);
startActivity(i);
}
}
I know this method but lets say for example i have 20 subitems so i need 20 activities !! how do i make it so only one activity is passed in but the data inside it changes depending on the subitem clicked ( by the data inside it i mean simple Textviews ) sorry my english is very bad

You can set a extra to the activity intent to indentify where you came from:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(this, second.class);
i.putExtra("position", position);
startActivity(i);
}
Then in your activity you can get the intent that like this:
int position;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity); //if your activities have different layouts depending the given position, you can move this line inside the switch function
...
if(getIntent().getExtras() != null) {
position = getIntent().getExtras().getInt("position", 0);
}
switch(position){
case 1:
//do something
break;
case 2:
//do another thing
break;
default:
//default behaviour
break;
}
}

Related

Listview.setOnItemclicklistener with Searchview

I've a problem with my ListView onClick. I try to explain u by a particule of my code.
So when I'm filtering by
searching c for example
the ActivityA is opening, the
same with Activity B.
So during filtering
they taking the position 0.
Because without filtering
every click open the right Activity.
So, please how can I fix it?
private SearchView sv;
Protected void onCreate........
String[] Values = {"a","b","c"};
listView = findViewById(R.id.liste);
sv=findViewById(R.id.searchview);
ArrayAdapter<String>......(.simple_list_item_2,android.R.id.text1,Values);
listView.setAdapter;
sv.setOnQueryTextListener........
//everything here is ok it's filtering well.
//After that,I've my listview.onClick
listview.setOnItemClickListener()
........(parent, View view, int position, long id){
if(position == 0){
Itent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
}
if(position == 1){
Intent b = new Intent (getApplicationContext(),AtivityB.class);
startActivity(b)
}
if(position == 2){
Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
}
}```
As position will always return the first position of the list (which is 0) when you've a single filtered out item as in your case; in order to get the actual position you can search for the first index of the item in the list using .indexOf() method. This requires you to convert your array into a an ArrayList
final String[] Values = {"a", "b", "c"};
final ArrayList<String> list = Arrays.asList(Values);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos = list.indexOf(myListAdapter.getItem(position));
switch (pos) {
case 0:
Intent a = new Intent(getApplicationContext(), AtivityA.class);
startActivity(a);
return;
case 1:
Intent b = new Intent(getApplicationContext(), AtivityB.class);
startActivity(b);
return;
case 2:
Intent c = new Intent(getApplicationContext(), AtivityC.class);
startActivity(c);
}
}
});
I am not quite sure if this will help but I would use a switch instead of if statements.
switch (position) {
case 0:
Intent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
break;
case 1:
Intent b = new Intent (getApplicationContext(),AtivityB.class);
startActivity(b)
break;
case 2:
Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
break;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.//item:
startActivity(new Intent(this, ActivityA.class));
return true;
case R.id.//item:
startActivity(new Intent(this, ActivityB.class));
return true;
case R.id.//item:
startActivity(new Intent(this, ActivityC.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}

NavigationDrawer opening new activity

I implemented a basic navigationDrawer, with an array of strings. I want the user to click on something in the list and go to the corresponding Activity.
However, I am completely at loss here. I have read quite a few answers out here, but it still is not clear how to do this.
I have found a useful way for all the items combining the answers. However it is still returning my MainActivity instead of other activities.
The addDrawerItems() function:
public void addDrawerItems() {
mDrawerList = (ListView) findViewById(R.id.navList);
String[] osArray = {"How-to", "Milestones", "Bridge & Beams", "Settings"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: //First item
Intent intent1 = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent1);
break;
case 1: //Second item
Intent intent2 = new Intent(MainActivity.this, Bridge_BeamsActivity.class);
startActivity(intent2);
break;
case 2: //Third item
Intent intent3 = new Intent(MainActivity.this, MileStonesActivity.class);
startActivity(intent3);
break;
case 3: //Fourth item
Intent intent4 = new Intent(MainActivity.this, HowToActivity.class);
startActivity(intent4);
break;
default:
}
}
});
}
Now my onCreate where I call the addDrawerItems():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Check if there is any saved data
checkFirstRun();
//Apply saved data
savedData();
//Apply drawer
addDrawerItems();
}
Any help would be much appreciated!
If there are any unclear pieces of code or my explanation, please don't hesitate to reach out.
In case you want to see what is already there, please check out my beta app in the Play Store: https://play.google.com/store/apps/details?id=jhpcoenen.connectlife.beams
Add the following code after setting the adapter:
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos =position;
Intent intent = new Intent(MainActivity.this, CorrespondingActivity.class);
startActivity(intent);
switch (position) {
default:
}
}
});
The intent function will take to the desired activity.
EDIT
v.getId() will get you the id of the view, that is the id registered in the R class. As your array only contains strings, the only way to bind the string with the view Id is to manually check it. Build the listener and log your id to identify it
mDrawerList.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Log.d("your App","id clicked "+v.getId());
//this view is the item clicked by the user
Intent i = new Intent(getApplicationContext(),DestinyActivity.class)
i.putExtra("optionSelected",v.getId());
startActivity(i);
}
});
you will get an id like 234252341, and for every item of your list a different id which you can associate with the string
ORIGINAL
You have to add a click listener to your ListView and put an action on it depending on the view clicked. Something like this
mDrawerList.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//this view is the item clicked by the user
Intent i = new Intent(getApplicationContext(),DestinyActivity.class)
i.putExtra("optionSelected",v.getId())
startActivity(i)
}
})
In DestinyActivity you have to get extras with Intent.getExtras and do whatever you need.
PD: Code is handwritten, check it with your IDE

Searchview filtering gridview, and get switch case to the result instead of the first switch case

I have implemented a searchview to filter my gridview However I have also set up a switch case, which when you click the the different objects, it opens up a new activity. Example of what happens;
This is the home screen, When you click on the first picture you get the corresponding activity
However, when you type something into the search bar it filters the results. I want to be able to click this picture and go to the proper corresponding activity. This is not the case and instead it goes to the first 'switch case' activity;
Filtered results, Instead of showing the 3rd activity, its shows the first one
So yeah, I understand why it is doing this, so I just need someone to put me down a path which will give me a solution.
Here is my code which handles the switch case of my gridview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gv = (GridView) findViewById(R.id.gridView);
gv = (GridView) findViewById(R.id.gridView);
sv = (SearchView) findViewById(R.id.searchView);
final Adapter adapter = new Adapter(this, this.getChampions());
gv.setAdapter(adapter);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
return false;
}
});
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch( position )
{
case 0: Intent newActivity = new Intent(MainActivity.this, Aatrox.class);
startActivity(newActivity);
break;
case 1: Intent newActivity2 = new Intent(MainActivity.this, Ahri.class);
startActivity(newActivity2);
break;
case 2: Intent newActivity3 = new Intent(MainActivity.this, Akali.class);
startActivity(newActivity3);
break;
}
}
});
}
private ArrayList<Champions> getChampions() {
ArrayList<Champions> champions = new ArrayList<Champions>();
Champions p;
for (int i = 0; i < Champions.length; i++) {
p = new Champions(Champions[i], Champimgs[i]);
champions.add(p);
}
return champions;
}
}
I have posted this trying to clarify my last post, which was flagged as a duplicate, to a question asking a completely different question, Thank you.
Remove your switch and Use Below Code
if(ItemClicked.getName.equalIgnorecase("Aatrox")){
Intent newActivity = new Intent(MainActivity.this, Aatrox.class);
startActivity(newActivity);
}elseif(ItemClicked.getName.equalIgnorecase("Ahri")){
Intent newActivity2 = new Intent(MainActivity.this, Ahri.class);
startActivity(newActivity2);
}else if(ItemClicked.getName.equalIgnorecase("Akali")){
Intent newActivity3 = new Intent(MainActivity.this, Akali.class);
startActivity(newActivity3);
}
Note: Keep rest code as it is

Item being selected automatically from spinner?

my issue is that whenever I add a lecture to the array list in the next activity, it calls back to this activity and updates it. However, for some reason onItemSelected is called right away as soon as I get back to the calling activity and I'm sent to the Lecture activity (the displayLectureIntent is started right away) as soon as I get back to the calling activity without even actually selecting anything from the spinner.
Could it be that as soon as I add something to the spinner, the spinner chooses the first object as default and therefore it "selects" it? Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_manager0);
Intent receivedIntent = getIntent();
if (receivedIntent.hasExtra("lectureManagerExtra")) {
lectureManager = (LectureManager) getIntent().getSerializableExtra("lectureManagerExtra");
update();
} else {
lectureManager = new LectureManager();
}
}
public void update() {
Spinner spinner = (Spinner) findViewById(R.id.lecturespinner);
ArrayAdapter<String> lectureadapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item, lectureManager.getLectureNames());
lectureadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(lectureadapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
startActivity(displayLectureIntent);
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {}
});
}
please add "select" string on lectureManager.getLectureNames() array at the top
so that the array's size is increased by 1
And setSelectedIndex to 0 .
and
modify onItemSelected method as followings
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
**if(position !=0){
startActivity(displayLectureIntent);
}
else{
Toast.makeText(getApplicationContext(), " select the lecture.", Toast.LENGTH_LONG).show();**
}
}

ListView Item Open New Activity

I'm still following a couple of tutorials in order to learn Android Development, I am struggling to open new activities. I can open only one activity, in fact all items on my ListView open this one activity, which would be great for ListView item in position 0 (the first item) not all of them.
My code below:
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(mContext, MyActivity1.class);
mContext.startActivity(intent);
}
});
return view;
}
As you can see MyActivity1.class opens fine, but what if I had a second class called MyActivity2 which should be opened up by listview item in position 1 (second item), how would I do that? Also what does (View arg0) mean? I can't find proper explanation on this?
You can use Itemclick listner.
listviewOBJ.setOnItemClickListener( new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
}
});
here you can use int position to decide which item is clicked.
If my understanding is correct, then here is your answer:
Implement OnItemClickListener to your main activity:
then set listener to your listview: listView.setOnItemClickListener(this);
finallly :
private OnItemClickListener mOnGalleryClick = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch(positon)
{
case 0:
Intent intent = new Intent(mContext, MyActivity1.class);
mContext.startActivity(intent);
break;
case 1:
Intent intent = new Intent(mContext, MyActivity2.class);
mContext.startActivity(intent);
break;
}
}
};
Use listview OnItemClickListener
listView.setOnItemClickListener( new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
switch(positon)
{
case 0:
Intent intent = new Intent(mContext, MyActivity1.class);
mContext.startActivity(intent);
break;
case 1:
Intent intent = new Intent(mContext, MyActivity2.class);
mContext.startActivity(intent);
break;
}
}
});
position is the index of list item. so based on the index you can start the respective activity.
The other way without switch case
String[] classes ={"MyActivity1","MyActivity2"};
Then in onItemClick
String value = classes[position];
Class ourClass =Class.forName("packagename."+value);
Intent intent = new Intent(mContext,ourClass);
mContext.startActivity(intent);
public void onClick(View arg0) {
onClick is called when you click on something, and arg0 (you could call it view, arg0 is so useless as name) is what you clicked.
This callback is often used in Buttons, Views in general but cannot be used with ListView.
If you want to open something when an item in the listview is clicked, you should use setOnItemClickListener!
On AdapterView.OnItemClickListener you have AdapterView<?> parent, View view, int position, long id arguments.
From android doc:
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position: The position of the item clicked (0 the first, 1 the second etc.)
id: The row id of the item that was clicked.
When you write your onItemClick you should remember you are in an anonymous class!
So you cannot use this when you need to pass your context to new Intent
pastesList.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent = null;
switch (position)
{
case 0:
intent = new Intent(ActivityClass.this, Class1.class);
break;
case 1:
intent = new Intent(ActivityClass.this, Class2.class);
break;
default:
return;
}
startActivity(intent);
}
});
This line
ActivityClass.this
is used when you need to use the instance of the class ActivityClass (You should replace ActivityClass with your class name) but you cannot access it directly using this which here refer to new AdapterView.OnItemClickListener()
In your code you use mContext i don't know what is it, but i suppose it's a context.
Next time you don't have this variable, follow my advise if you want.
lv.setOnItemClickListener(n## Heading ##ew OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 1) {
//code specific to first list item
Intent myIntent = new Intent(view.getContext(), Html_file1.class);
startActivityForResult(myIntent, 0);
}
if(position == 2) {
//code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(), Html_file2.class);
startActivityForResult(myIntent, 0);
}
}
});
What you want to use is an AdapterView.OnItemClickListener.
final ListView list = ...;
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(mContext, MyActivity1.class);
if (position == 1) {
intent = new Intent(mContext, MyActivity2.class);
}
startActivity(intent);
}
});

Categories