Calling an android activity using ListView item click - android

Hy guys i am developing an android app its going well but i am stuck now.I am trying to call activities when a listview item is clicked it must open a specific activity according to the details of the listview item details.Here is my code in a method.
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet, new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL,
TAG_SPARKLING_CLASSIFICATION, TAG_CLASS}, new int[]
{ R.id.outlet_name, R.id.sparkling_channel, R.id.sparkling_classification,
R.id.cls_state});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String>map = (HashMap<String, String>)parent.getItemAtPosition(position);
String foutname = map.get(TAG_OUTLET_NAME);
String fchannel = map.get(TAG_SPARKLING_CHANNEL);
String fclass = map.get(TAG_SPARKLING_CLASSIFICATION);
String fclass_state = map.get(TAG_CLASS);
String compr = "GDB";
String compr2 = "QSRG"
if(compr == fclass_state){
Intent i = new Intent(OutletsList.this, GdgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
}
if(compr2 == fclass_state){
Intent i = new Intent(OutletsList.this, QsrgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
}
}
});
}
When i click its showing this error in the logcat, java.lang.ClassCastExeption: java.util.HashMap cannot be cast to java.lang.String.Ypur help is greatly appreciated or even alternative code and solutions.Thanks in advance guys.

The problem is that you are casting a HashMap to a String which will give you an error of ClassCastExeption
problem:
This code will return a String not a HashMap
parent.getItemAtPosition(position);
Base from your SimpleAdapter you added a Array of String not a HashMap to each of the item in the ListView.
new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet,
new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL, TAG_SPARKLING_CLASSIFICATION, TAG_CLASS},
new int[]{ R.id.outlet_name, R.id.sparkling_channel, R.id.sparkling_classification, R.id.cls_state});
solution 1
There is no way to cast it to HashMap unless you make a BaseAdapter for it, you can click here to learn to make adapter.
solution 2
Other solution is to just get all the array of items from the ListView
String foutname = parent.getItemAtPosition(0);
String fchannel = parent.getItemAtPosition(1);
String fclass = parent.getItemAtPosition(2);
String fclass_state = parent.getItemAtPosition(3);

may be this could help -
String classes[]="Start","Send","Tabs","Browser","Flipper","SharedPrefs","InternalData","Sqlite","Checking"};
// make list view from this string array
//on list item clicked use this... note the first line in try block.
String cheese=classes[position];
try{
Class cl=Class.forName("com.example.test."+cheese);
Intent i=new Intent(Menu.this,cl);
startActivity(i);
}catch(ClassNotFoundException e){}

Related

OnItemClick not working properly in listview

Using the following code, when an item from the list is selected it updates a data table. The problem is when there are several items listed, regardless of which one is selected, it always updates the first listed item showing rather than the one selected. Thanks in advance!
Edited-Updated. Incorporated (position) and tried to simplify a bit of the code. Still will not capture the selected item, always returns the top item showing on the listview, regardless. The DB controller is working fine, all else is good except this...
setContentView(R.layout.list_messages);
ArrayList<HashMap<String, String>> phraseList = controller
.getUnreadMessage();
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(
ReadUnReadMessages.this,
phraseList,
R.layout.view_list_messages,
new String[] { "mFromName", "mToAddress", "mBody",
"mToName", "messageTime", "mFromAddress", "mRead",
"messageId" },
new int[] { R.id.messageFrom, R.id.messageToAdd,
R.id.messageBody, R.id.messageTo, R.id.messageTime,
R.id.messageFromAdd, R.id.readCode, R.id.messageId });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg) {
#SuppressWarnings("unchecked")
HashMap<String, String> queryValues = (HashMap<String, String>)parent.getItemAtPosition(position);
messageBody = (TextView) findViewById(R.id.messageBody);
readCode = (TextView) findViewById(R.id.readCode);
messageId = (TextView) findViewById(R.id.messageId);
String readCode = "1";
queryValues
.put("messageId", messageId.getText().toString());
queryValues.put("mRead", readCode);
queryValues.put("mBody", messageBody.getText().toString());
controller.markMessage(queryValues);
this.callSplash(view);
}
public void callSplash(View view) {
Intent objSplash = new Intent(getApplicationContext(),
Splash.class);
startActivity(objSplash);
}
});
It's hard to tell exactly how you were expecting it to work, but it seems like your central problem is that you are ignoring the 'position' parameter to onItemClick. This is Android's way of telling you which item was clicked. Somehow you need to pass that parameter, or else the corresponding item object that you fetch first from the adapter, on to the functions you call from onItemClick:
this.insertData(position);
Otherwise those functions would have to guess which item was clicked. And apparently that is what they are doing: they are assuming the first item was clicked.

Android - Editing ListAdapter Data from another activity

I have a simple application that has 3 activities. The third activity is a ListActivity that lists movie titles and their respective gross and year, choosing any movie will display the values in the first activity. The second activity is where the user can add a movie to the ListActivity by filling up EditText fields and this is where I'm having problems.
So far, the examples I see involve use this line of code:
SampleCustomAdapter adapter = new SampleCustomAdapter(results);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
However, this line of code doesn't work for my case since the class in the second activity extends Activity and NOT ListActivity.
So far, this is the code I have when I attempt to add the new entries to the List.
//if all edit text fields have values and are valid inputs
if( titleFlag == 1 && grossFlag == 1 && yearFlag == 1){
//fix stuff here
//TODO ADD THE NEW MOVIE TO THE ARRAY IN STRINGS.XML
ArrayList<MyMovies> movieList = new ArrayList<MyMovies>();
MyMovies newMovie = new MyMovies();
newMovie.setMovie(title);
newMovie.setGross(gross);
newMovie.setYear(year);
movieList.add(newMovie);
//go back to the main page after adding
Intent intent = new Intent(this, com.Android.Lab7.Lab7_084106.class);
startActivity(intent);
finish();
}
I also tried adding the adapter.notifyDataSetChanged(); in the third activity after generating the list but to no avail. Oh, the third activitys' onCreate looks something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
//create stuff
super.onCreate(savedInstanceState);
ArrayList<MyMovies> movieList = new ArrayList<MyMovies>();
String[] movieArray = getResources().getStringArray(R.array.movieArray);
String[] grossArray = getResources().getStringArray(R.array.worldwideGross);
String[] yearArray = getResources().getStringArray(R.array.yearArray);
ArrayList<MyMovies> results = new ArrayList<MyMovies>();
// make sure the arrays have the same length
for (int i = 0; i < movieArray.length; i++) {
MyMovies sr = new MyMovies();
sr.setMovie(movieArray[i]);
sr.setGross(grossArray[i]);
sr.setYear(yearArray[i]);
results.add(sr);
}
SampleCustomAdapter adapter = new SampleCustomAdapter(results);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
adapter.notifyDataSetChanged();
//set stuff such that Page2 sends back a result to page 1
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
sendResult(position);
}
});
}
I used the strings resource to store the array of titles, gross, and year since there's a lot of them and it's not practical that I hardcode them.
So basically I'm stuck on how I can update the List in the third activity from the second activity.
Declare this in the third Activity.
public static String title, gross, year;
public static boolean newMovieAdded=false;
Then when you are in the second activity do the following
thirdActivity.title = MyEditText1.getText().toString();
thirdActivity.gross= MyEditText2.getText().toString();
thirdActivity.year= MyEditText3.getText().toString();
if(!year.equals(""))
newMovieAdded=true;
thats all. when you go to the third activity just write your code
ArrayList<MyMovies> movieList = new ArrayList<MyMovies>();
if(newMovieAdded){
MyMovies newMovie = new MyMovies();
newMovie.setMovie(title);
newMovie.setGross(gross);
newMovie.setYear(year);
movieList.add(newMovie);
newMovieAdded = false;
}

Previous activity not getting

I am working on tab host application containing 4 tabs. Each tab has individual activity that lists items. on item click of each tab takes to another activity displaying details of clicked list item in same tab host screen layout.
If i press back button after clicking an item from tab host, the application exits. But i need to visit the previously reached list and tabs. How to achieve this? Thanks in Advance
This is my Sample Code -
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list,
new String[] { "title","shortdescription"},
new int[] { R.id.titleTextView,R.id.descriptionTextView});
ListView list = (ListView)findViewById(R.id.statutesListView);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap = (HashMap<String, String>) parent.getItemAtPosition(position);
String newstitle = hashMap.get("title");
String newsdesc = hashMap.get("shortdescription");
//Get the new Activity to tab.
Intent intent = new Intent(getApplicationContext(), detailedview.class);
Bundle bundle = new Bundle();
bundle.putString("title", newstitle);
bundle.putString("desc", newsdesc);
intent.putExtras(bundle);
View setview = getLocalActivityManager().startActivity("statutes", intent).getDecorView();
setContentView(setview);
}
});
Check this link out and download sample code provided in it and let me know for more requirements
multiple activities in single tab
This code in this link also solves your problem

Passing listView row positions through Intents to another class

I'm wondering how to pass a row position(pos) value from, say, a CHOICE_MODE_SINGLE list Activity(A) to another Activity(B) using Intents? (I want to change ActivityB to show another list depending on what row in ActivityA is clicked). Here's my code:
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(
new android.widget.AdapterView.OnItemClickListener(){
#Override
public final void onItemClick(AdapterView<?> listView, View cell, int position, long id) {
Intent Courses = new Intent(this, ExpandableList.class);
Courses.putExtra(//I'm not sure what to put in here//)
});
private static final String[] GENRES = new String[] {"Barre","Buffumville","Hodges","Newton Hill"};
}
THANKS :)
Courses.putExtra("position",position);
Then to get the position in the next activity:
getIntent.getExtras().getInt("position");
You can pass the position through the intent putExtra.
please see below Code.
Intent Courses = new Intent(this, ExpandableList.class);
Courses.putExtra("position",position)
startActivity(Courses);
Now you can get this value in another activity like this.
getIntent.getExtras().getInt("position");
It will return the integer position you passed from the first activity.

How to view detailed data of a specific list view item

Let's say i have a list of cities from a country.
If the user clicks one of them, i want a new screen to be displayed, with the detailed infos for that list element.
Also, that screen will have others buttons ( eg: Write Review, Post Picture )
How can i achieve this ?
The City class should implement Parcelable. Its toString() method should return the name of the city. (Rather than simply having the city as a String.)
When you populate your ListView, use an ArrayAdapter<City> instead of an ArrayAdapter<String> (this code assumes that the cities are kept in List<City> list):
City[] cities = new City[list.size()];
list.toArray(cities);
mListView = (ListView) findViewById(R.id.citylist);
mListView.setAdapter(new ArrayAdapter<City>(this,
R.layout.listitem, cities));
In your onItemClick handler, get the selected city and add it as an extra on the intent you use to launch your details activity:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a,
View v, int position, long id) {
City city = (City) a.getItemAtPosition(position);
Intent intent = new Intent(v.getContext(), DetailsActivity.class);
intent.putExtra("com.example.cities.City", city);
startActivity(intent);
}
});
In your details activity, get the city from the extras on the intent:
Bundle bundle = getIntent().getExtras();
City city = bundle.getParcelable("com.example.cities.City");

Categories

Resources