ListView with onItemClick position - java

I got an App with ListView and on any row you click it's popup something different.(With PauseDialog). And the headers in any row is in a "array.xml" and the text that will popup in the PauseDialog is in the java code.
the problem is that i need to add a lot of rows to the ListView and i want to know if there is way more efficacious to do it than what i did.
Example of the array.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="Row_List">
<item>row1</item>
<item>row2</item>
<item>row3</item>
<item>row4</item>
</array>
</resources>
(just a lot more rows...)
the java code:
public class MainActivity extends Activity implements OnItemClickListener {
ListView list;
ArrayAdapter<String> adaptr;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
adaptr = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1
, getResources().getStringArray(R.array.Row_List));
View header = getLayoutInflater().inflate(R.layout.header, null);
list.addHeaderView(header);
list.setAdapter(adaptr);
list.setOnItemClickListener(this);
list.setFastScrollEnabled(true);
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Dialog dialog1 = new Dialog(this, R.style.PauseDialog);
dialog1.setContentView(R.layout.dialog1);
TextView text = (TextView) dialog1.findViewById(R.id.tv1);
dialog1.setTitle(R.string.Title);
dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(0));
switch(position) {
case 0:
String url = "My-Site.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
break;
case 1:
text.setText("Description of Row1");
dialog1.show();
break;
case 2:
text.setText("Description of Row2");
dialog1.show();
break;
case 3:
text.setText("Description of Row3");
dialog1.show();
break;
case 4:
text.setText("Description of Row4");
dialog1.show();
break;
}
}
}
So there is a better way to put the description into the dialog?(and i would like if there is a way the all the descriptions will be in a xml file and not in the code)
Thanks!

You can store your descriptions as a string-array in arrays.xml:
<string-array name="desciptions">
<item>item 0 descript</item>
<item>item 1 descript</item>
<item>item 2 descript</item>
</string-array>
.. define an array MainActivity:
static String[] desciptions = null;
.. initialize it in onCreate():
if (null==desciptions) desciptions
= getResources().getStringArray(R.array.descriptions);
.. and replace your switch statement with something like this, accounting for your '0' special case:
if (0==position) {
String url = "My-Site.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else {
text.setText(descriptions[position]);
dialog.show();
}
Just keep in mind you need to make allowances for your special 0 case, to keep your indexes aligned, such as using text.setText(descriptions[position-1]); or having an empty item 0 description.

Related

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

Each ListView item opens layout with different text

How my onClickListener should look like if I need to open layout with different text for each ListView item and I have a lot of ListView items (about 50)? Do I need to create new activity or layout file for each new item? Is it possible to use one activity for all items?
This is my MainActivity.java:
public class MainActivity extends Activity {
// ListView
private ListView listView;
// Adapter
ArrayAdapter<String> adapter;
String items [];
// ArrayList
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ListView data in res/values/arrays.xml
items =getResources().getStringArray(R.array.items);
listView = (ListView) findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.listItem, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
/*
I know that I can put here I can put something like this:
case 0 :Intent appInfo = new Intent(About.this, Activity1.class);
startActivity(appInfo);
break;
case 1 :Intent appInfo = new Intent(About.this, Activity2.class);
startActivity(appInfo);
break;
case 2 :Intent appInfo = new Intent(About.this, Activity3.class);
startActivity(appInfo);
break;
BUT DO I NEED REPEAT THIS MORE THAN 20 TIMES?!
*/
}
});
}
}
Some system apps like Settings has a lot of ListView and layouts and I don't believe that it has new activity for each layout.
Create a new single activity and pass the text to that activity.
Something like:
Intent intent = new Intent(About.this, <NEW_ACTIVITY>.class);
intent.putExtra("text_key", items[position]);
startActivity(intent);
on the other activity, retrieve the text like this (can be on the onCreate method):
String text = getIntent().getExtras().getString("text_key");

Beginner Android: ListView to affect the next class

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");

AutoComplete fixed selection?

How do i have an AutoComplete selection based on alphabetic instead of fixed switch cases? The situation is, everything working except when i input keyword with "B" showing Badrul as first suggestion but when clicked it will still refer to the first switch cases which is opening up Adidas.class instead of Badrul.class
Please help, i am new in this. Is AutoComplete suitable for my requirement?
public class Search extends Activity
{
public void onCreate(Bundle savedInstanceSate)
{
super.onCreate(savedInstanceSate);
setContentView(R.layout.searchshop);
AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
autoComplete.setAdapter(adapter);
autoComplete.setThreshold(1);
autoComplete.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
switch(position)
{
case 0:
startActivity(new Intent(Search.this, Adidas.class));
break;
case 1:
startActivity(new Intent(Search.this, Affin.class));
break;
case 2:
startActivity(new Intent(Search.this, AlamArt.class));
break;
case 3:
startActivity(new Intent(Search.this, Badrul.class));
break;
}
}
});
}
static final String[] shops = new String[]
{
"Adidas", "Affin Bank", "Alam Art Gallery", "Badrul"
};
}
You are adding OnItemClickListener to the AutoCompleteTextView. I think you don't know this thing about Item Click Listener.
The position variable in onItemClick() method stores the position of item clicked in the list shown.
You are telling the list shown Badrul as first suggestion, so the position of item you clicked is 0, so that its going to case 0:, so that its calling Adidas.class.
I hope you understood the problem from my answer.
This is obvious behavior as you are referring to the position of the suggestion at current time,so it would be differed according to what user types in. For achieving what you want,You need to change your code according to this:
public class Search extends Activity
{
public void onCreate(Bundle savedInstanceSate)
{
super.onCreate(savedInstanceSate);
setContentView(R.layout.searchshop);
final AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
autoComplete.setAdapter(adapter);
autoComplete.setThreshold(1);
autoComplete.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
int index=999;
for(int i=0;i<shops.length;i++)
{
if(autoComplete.getText().toString().trim().equals(shops[i]))
{
index=i;
break;
}
}
switch(index)
{
case 0:
startActivity(new Intent(Search.this, Adidas.class));
break;
case 1:
startActivity(new Intent(Search.this, Affin.class));
break;
case 2:
startActivity(new Intent(Search.this, AlamArt.class));
break;
case 3:
startActivity(new Intent(Search.this, Badrul.class));
break;
default:
Toast.makeText(Search.this, "Invalid Selection", Toast.LENGTH_SHORT).show();
}
}
});
}
static final String[] shops = new String[]
{
"Adidas", "Affin Bank", "Alam Art Gallery", "Badrul"
};
}
Mr. Kenneth The solution is already there, Hiral's answer, but you have to modify it, to make error free.
Just do below changes.
Modify the below line of code into 2 parts.
AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
1. Add below line of code before onCreate()
AutoCompleteTextView autoComplete;
2.Modify the original line as below
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);

Categories