How to navigate to another screen in android using onListItemClick - android

I am kind of new to Android development. Could you please tell me, how to navigate to another screen using onListItemClick. I have 200 items in a ListView. If i click an item from the ListView, it has to navigate to another screen which should show the details of the clicked item.

To get what you want you can do something like this...
1>create another activity with certains controls in which you can place your values...
2>on itemclick() of listview...
a>create intent and set values to pass to new activity
b>start new activity with this intent.
3>in oncreate() of new activity
a>retrive the values from intent
b>populate your controls using the values...

I am assuming you are getting the list and detail of actor from database.
I have used the same walk through to display recipe detail of selected recipe in my app.
public class ActorList extends Activity {
ListView myActorList=null;
public final static String selectedActor_ID="will Keep Actor ID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_actor_list);
//initialize controls
myActorList.setAdapter(adapter);
myActorList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
// TODO Auto-generated method stub
Intent i= new Intent(ActorList.this,ActorDetail.class);
// you have to pass the actor id to next activity
// you can get this actor id from argument of type "long"
i.putExtra(selectedActor_ID, String.valueOf(id));
startActivity(i);
}
});
}
}
//Other Activity To show Detail..
//get the ID of Selected Actor on other activity say "ActorDetail"
public class ActorDetail extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_actor_detail);
ActorID=getIntent().getStringExtra(ActorList.selectedActor_ID);
// now as you have the id here for that particular actor
//fetch the detail of that selected actor thru id and bind it to your layout.
}
}
You need to register the other activity in Manifest file also like this
<activity
android:name=".otherscreenActivity"
</activity>

Related

Saving an activity state when I press up button in action bar

I'm developing an android Wallpaper app consists of 2 activity, main activity displays the images from the internet in ListView and the second activity displays the preview of that image.
my problem is when I press the back button in preview activity to go back to the main activity, the main activity displays the images from the beginning and I would like to display the images from the last I clicked on.
The following code in onCreate() method in Main Activity:
// Find a reference to the {#link ListView} in the layout
ListView gameListView = findViewById(R.id.list);
mEmptyStateTextView = findViewById(R.id.empty_view);
gameListView.setEmptyView(mEmptyStateTextView);
// Create a new adapter that takes an empty list of games as input
mAdapter = new GamesAdapter(this, new ArrayList<Games>());
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
gameListView.setAdapter(mAdapter);
// Set an item click listener on the ListView, which sends an intent to a web browser
// to open a website with more information about the selected game.
gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current game that was clicked on
Games currentGame = mAdapter.getItem(position);
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri gameUri = Uri.parse(currentGame.getUrl());
String name = currentGame.getName();
// Create a new intent to view the game URI
Intent i = new Intent(GamesActivity.this, PreviewActivity.class);
i.setData(gameUri);
i.putExtra("name", name);
startActivity(i);
}
});
The following code in onCreate() method in Preview Activity:
final Uri i = getIntent().getData();
String profile = getIntent().getStringExtra("name");
photographer.setText(profile);
Picasso.with(this).load(i).into(img);
saveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
downloadFile(i);
}
});
I think what your are looking for is the method onSaveInstanceState(Bundle outState) here you can save your values in the outState and get them in onCreate() at the savedInstanceState
here is a very good example how to use it.
I think you want to preserve the scroll distance. For that what you need to do is you can preserve using Bundle object. But you can also clear current activity then you will get the same results.
Add this outside the onCreate() method(this is java):
#Override
public void onBackPressed() {
this.finish(); //important
}
finish() clears activity from back stack.

Selected Value from spinner into new activity

I'm developing a Androidapplication and I want to be able to start an activity through a spinner value the user have selected.
As an example: In the main activity you'll see a spinner with the values "Color", "Animals". If you choose "Color" and click on a button called "Proceed", you will come to an activity that list different colors in a listview, but if you choose "Animal" from the spinner, you will come to the same activity, but this time it shows a listview of animals instead.
Can anybody give me a hint on how to do this?
(PS this is an example on how I want it to work, I actually need to call everything from a Web Service)
you can implement android.widget.AdapterView.OnItemSelectedListener and override the method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
// Call the following method to get the selected value of the spinner and perform your
//task to start your desired activity
String selectedValue=parent.getItemAtPosition(pos).toString();
if(selectedValue.equals("Colors"))
{
//do your task using color
}
else if(selectedValue.equals("Animal"))
{
//do your task using animal
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
//Do Nothing
}
The simplest Solution would be for example:
Spinner yourSpinner = (Spinner)view.findViewById(R.id.your_spinner);
String value = yourSpinner.getSelectedItem().toString();
if(value.equalsIgnoreCase("ANIMAL")){
Intent intent = new Intent(yourActivity.this, yourNextActivity.class);
intent.putExtra("VALUE", value);
startActivity(intent)
}
Then in that Activity that You want to start:
Intent intent = getIntent();
String value= intent.getStringExtra("VALUE");
if(value.equalsIgnoreCase("ANIMAL")){
//start the part with animals
}
Its really simple just use bundle and send the appropriate data to your next activity. A small sample would look like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String spinnerText = spinner.getSelectedItem().toString();
Intent intent = new Intent(A.this,B.class);
intent.putExtra("selection",spinnerText);
}
});
Then in your next activity get the sent text and manipulate accordingly.

ListView assistance

I'm working on a project at school, and I need help implementing ListViews properly. I have to do the Settings and Help sections on the project and as of now, I can display what's on my list and it displays Toast messages of the selected item when I click it. My question is, how can I create and show the content that is inside that specific item? For example, I have an option "Edit Password" and that when I click it, it should display my "Edit Password" screen. This applies to both my sections.
This is what I have so far. It's basically the android ListView tutorial but I added my options on there. My question is, when I click one of the options on my list, how can I display its specific details? Like what I said before, if I click "Edit Password", I want it to go to a "Edit Password" screen. Or on Help, if I click let's say, "Credits", I want it direct me to the Credits page.
public class Settings extends ListActivity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.settings, SETTINGS));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
static final String[] SETTINGS = new String[]
{"Set Refresh Rate", "Edit Password", "Delete Account"};
}
When you extend ListActivity you already have the OnItemClickListener implemented, you should override the method onListItemClick. In that method you should use an Intent to get to a new Activity where you will display the stuff you want:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent i = new Intent(this, SecondActivityName.class);
i.putExtra("pos", position); //pass the position of the clicked row so we know what to show.
startActivity(i); // let's go to the other activity
}
SeconActivityName is an Activity that you should create and where you would show the other screen you want(remember to add the activity to the manifest file!):
public class SecondActivityName extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
int rowPosition = i.getIntExtra("pos", -1); //we now have the row's position that was clicked in the other activity.
// based on that you show the screen you want for example after a switch
switch (rowPosition) {
case -1:
//this is the default value, something has gone terrible wrong
//finish the activity and hide:
finish();
break;
case 0:
//row 0 was clicked so show the "Set Refresh Rate" screen
setContentView(R.layout.refresh_rate__screen);
break;
//do the same for the other rows;
//...
This will work if the screens for the various settings are not that different. If they are you'll probably have to implement a different activity for each one and start the appropriate activity in the onListItemClick based on the position parameter.

Android: get listview onClick to new intent

i hava got the code below. i want to start an activity when i click on a single item on the list. however when i do nothing happens. I alsow want every item to refer to the same intent calld "com.whiskey.app.view" and send a id variable that was given by the sql query. I browsed trough the code several times but i cant seem t get it to work.
public class MainScreen extends Activity implements OnItemClickListener{
public ListView whiskeylist;
public String[] DataArryWhiskey;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start db view of whiskey
DBConfig whiskeyrows = new DBConfig(this);
whiskeyrows.open();
DataArryWhiskey = whiskeyrows.getDataInArray();
whiskeyrows.close();
whiskeylist = (ListView)findViewById(R.id.listofWhiskey);
whiskeylist.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , DataArryWhiskey));
// End db view of whiskey
}// end onCreate
// catch itemclick event from the main list.
public void onItemClick(AdapterView av, View v, int position, long l)
{
// TODO Auto-generated method stub
String[] listitem_data = DataArryWhiskey[position].split(","); // break passed sting into a array comma seperated
Bundle passingitems = new Bundle();
passingitems.putString("whiskey_id", listitem_data[0]);
Intent currentintent = new Intent("com.wiskey.app.view");
currentintent.putExtras(passingitems);
startActivity(currentintent);
}
Although the above answers work, I think that the problem in your current implementation is that you don't call:
whiskeylist.setOnItemClickListener(this);
I think this should do the work!
If your activity only cotains this ListView, you should use a ListActivity.
These are made specifically for activities that only contain lists.
One of the methods for ListActivities is onListItemClick. That one is specifically for clicking on items in lists, as the name says.
The reason your code doesn't work is because onItemClick isn't generally used for clicking in Lists, but for clicking other objects in Activities.
Try changing your code based on the samples here: ListActivity
Derive your class from ListActivity and remove the implements OnItemClickListener
Put below code in onCreate
setListAdapter(whiskeylist);
And then have this as your onItemClick
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String[] listitem_data = DataArryWhiskey[position].split(","); // break passed sting into a array comma seperated
...your code....
startActivity(currentintent);
}
Also refer to:
ListActivity
ListView
You have not added listener for click actions, try adding:
whiskeylist.setOnItemClickListener(this);
at the end of onCreate
You might also write anonymous OnItemClickListener as in here:
http://developer.android.com/resources/tutorials/views/hello-listview.html

Android: how do i switch from one activity to another by clicking items from the ListView

i have made menu list containing play, settings, exit. but clicking the button doesn take me to the desired activity the listner is not working..can any one help me solve the problem.. will b thankfull..
yes its a list view control..
there are two errors in my code one is that
## The type new AdapterView.OnItemClickListener(){} must implement the inherited abstract method AdapterView.OnItemClickListener.onItemClick(AdapterView, View, int, long)## in LINE1
And the other one is ## View cannot be resolved to a type## in LINE 2
"Actually i want to shift from one screen to another when i click on the item in main menu screen"
Here is the code of main menu
public class MenuActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
ListView menuList = (ListView) findViewById(R.id.list);
String[] items = {
getResources().getString(R.string.pla),
getResources().getString(R.string.sco),
getResources().getString(R.string.set),
getResources().getString(R.string.hel),
getResources().getString(R.string.qui)
};
ArrayAdapter < String > adapt = new ArrayAdapter < String > (this, R.layout.menu_items, items);
menuList.setAdapter(adapt);
menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() { //LINE 1 error
public void onItemClick(AdapterView <? > parent, View itemClicked, //LINE 2 error
int position, long id) {
TextView textView = (TextView) itemClicked;
String strText = textView.getText().toString();
if (strText.equalsIgnoreCase(getResources().getString(
R.string.pla))) {
// Game
startActivity(new Intent(MenuActivity.this,
GameActivity.class));
} else if (strText.equalsIgnoreCase(getResources().getString(
R.string.hel))) {
// Help
startActivity(new Intent(MenuActivity.this,
HelpActivity.class));
} else if (strText.equalsIgnoreCase(getResources().getString(
R.string.set))) {
//Settings
startActivity(new Intent(MenuActivity.this,
SettingsActivity.class));
} else if (strText.equalsIgnoreCase(getResources().getString(
R.string.sco))) {
// Scores
startActivity(new Intent(MenuActivity.this,
ScoresActivity.class));
}
}
});
}
}
ListView lv = ...;
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,View arg1, int arg2, long arg3)
{
//Do Your Stuff
}
});
or you can make your custom adapter and write the button's click event
use intent
Intent play= new Intent(getApplicationContext(),Play.class);
startActivity(play);
there's lots of tutorial about menu
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent) which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent) -- Used to launch a new activity.
So suppose you have two Activity class and on a button click's OnClickListener() you wanna move from one Activity to another then --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
This exmple is related to button click you can use the code anywhere which is written inside button click's OnClickListener() at any place where you want to switch between your activities like in your setOnItemClickListener.

Categories

Resources