How to launch an Activity on ListView Item click android - Java for Android App Development

hello
I am new to android application development and i am developing and application for learning purpose.
Can any body please help me in creating an activity that launch and activity on ListView Item Click.
I am using Following code for Populating Listview Items.
filename: activity_menu.java
package com.my.android.app;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.LauncherActivity.ListItem;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class activity_menu extends Activity {
String[] countries = new String[] {
"Contacts",
"SMS",
"Files & Photos",
"Prefrences",
"Logout",
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[]{
R.drawable.phonebook,
R.drawable.sms,
R.drawable.filesphotos,
R.drawable.settings,
R.drawable.key,
};
// Array of strings to store currencies
String[] currency = new String[]{
"Manage Contacts Backup",
"Manage SMS Backup",
"Manage files & Photos Backup",
"Set your prefrences",
"Logout of Application",
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<5;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", countries);
hm.put("cur", currency);
hm.put("flag", Integer.toString(flags) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
Please help on this. waiting for Responses.

Try this
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do your action here
}
});

There are multiple ways. If using a ListFragment/ListActivity, onListItemClick can also be used. However, I think that that is used especially with a programmatically-defined ListView.

If you want to start a new Activity, do some research about Intents.

SagiLo said:
Try this
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do your action here
}
});
Click to expand...
Click to collapse
This. Use the position parameter if you want it to only open when a particular item is clicked (It is zero-based, if I remember correctly)
Then, to open the Intent:
Code:
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
Opening on any listitem click:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
});
Opening on a specific item:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});

how so i implement the code to open new activity on row cick?
cyr0s said:
This. Use the position parameter if you want it to only open when a particular item is clicked (It is zero-based, if I remember correctly)
Then, to open the Intent:
Code:
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
Opening on any listitem click:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
});
Opening on a specific item:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
Click to expand...
Click to collapse
How do i implement this code in my main activity's java file?
suppose, i have a main activity which contains the listview and i have another activity "Activity_game"
and i want to open Activity_game on clicking the first row,
so i put "0" at "ITEM_POSITION_HERE" and "game" at the place of "ActivityName"
but it gives my a bunch of errors and it doesn't work
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});

nnnn1111 said:
How do i implement this code in my main activity's java file?
suppose, i have a main activity which contains the listview and i have another activity "Activity_game"
and i want to open Activity_game on clicking the first row,
so i put "0" at "ITEM_POSITION_HERE" and "game" at the place of "ActivityName"
but it gives my a bunch of errors and it doesn't work
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
Click to expand...
Click to collapse
We need to know which errors you get.
Read this: http://forum.xda-developers.com/showthread.php?t=2439748

one question
nikwen said:
We need to know which errors you get.
Read this: http://forum.xda-developers.com/showthread.php?t=2439748
Click to expand...
Click to collapse
my problem is , when i run the app, it doesn't show any rows , not even any listview , or string
(just blank white page)
i have two activities
first one is Activity_main.xml in which ive implemented listview
here is it's java file
package com.example.desi;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
public class MainActivity extends Activity {
String[] items = { "item 1", "item 2", "item 3", "item 4", "item 5" };
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0: Intent newActivity = new Intent(this, Munda.class);
startActivity(newActivity);
break;
}
}
}
and another activity is Activity_munda.xml
so, i want to run "Activity_munda" through on row click of listview
i also want to have many activities later in my app
my project is error free right now
do you think i have incomplete code?

nnnn1111 said:
my problem is , when i run the app, it doesn't show any rows , not even any listview , or string
(just blank white page)
i have two activities
first one is Activity_main.xml in which ive implemented listview
here is it's java file
package com.example.desi;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
public class MainActivity extends Activity {
String[] items = { "item 1", "item 2", "item 3", "item 4", "item 5" };
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0: Intent newActivity = new Intent(this, Munda.class);
startActivity(newActivity);
break;
}
}
}
and another activity is Activity_munda.xml
so, i want to run "Activity_munda" through on row click of listview
i also want to have many activities later in my app
my project is error free right now
do you think i have incomplete code?
Click to expand...
Click to collapse
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.

vijai2011 said:
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
Click to expand...
Click to collapse
Right. Read this: http://www.vogella.com/articles/AndroidListView/article.html

i already tried that
vijai2011 said:
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
Click to expand...
Click to collapse
but with no luck
its very complicated
can you please give me a simple tutorial ?
please dont refer to any other tutorial as i have already tried all of them,
thanks

nnnn1111 said:
but with no luck
its very complicated
can you please give me a simple tutorial ?
please dont refer to any other tutorial as i have already tried all of them,
thanks
Click to expand...
Click to collapse
Come on, you haven't tried all of them. Please don't let everyone else do the work for you. And if you can manage to do it yourself, it will be a better learning experience.
I can offer that you try the tutorial I posted and if your code doesn't work, you can post it together with a logcat and we'll check it.

haha i know
nikwen said:
Come on, you haven't tried all of them. Please don't let everyone else do the work for you. And if you can manage to do it yourself, it will be a better learning experience.
I can offer that you try the tutorial I posted and if your code doesn't work, you can post it together with a logcat and we'll check it.
Click to expand...
Click to collapse
but ive been searching for like 15 days about this problem on stack overflow , saw like 30 posts but they arent clear , please do me a favor and
tell me in few steps you will also feel good helping me.
and it will be a VERY big favor to me , trust me

nnnn1111 said:
but ive been searching for like 15 days about this problem on stack overflow , saw like 30 posts but they arent clear , please do me a favor and
tell me in few steps you will also feel good helping me.
and it will be a VERY big favor to me , trust me
Click to expand...
Click to collapse
Read this about ListActivity. It should answer your questions: http://www.vogella.com/articles/AndroidListView/article.html#listactivity
And I won't post step by step guides on how to implement ListViews. There are many great tutorials out there. I can help you if you have problems/errors with your code, but @vijai2011 has already explained what you need to do.

You cannot expect anyone to spoon feed you. We are here to help people who try to do something but run into problems. Not people who doesnt even try to understand what they do. The guides by vogella are very simple and there is no problem with the guide. You cannot simply copy paste the codes from the tutorial and expect it to compile and work.

vijai2011 said:
You cannot expect anyone to spoon feed you. We are here to help people who try to do something but run into problems. Not people who doesnt even try to understand what they do. The guides by vogella are very simple and there is no problem with the guide. You cannot simply copy paste the codes from the tutorial and expect it to compile and work.
Click to expand...
Click to collapse
i didn't find my answer on that website

nnnn1111 said:
i didn't find my answer on that website
Click to expand...
Click to collapse
Then it may mean that you dont know what you are searching for! Because the tutorial is all about what you need - ListView!

Related

Android/Java Newbie

Hi all, im having a go at developing a simple app. i have little experience with Java and Android development. i have a little test app at the moment and have created a new class, im trying to create a new instance of this class on a button click. it fails to do so, i cant for the life of me see why so.. can someone shed any light on this?
Thanks
Debuging this shows it hitting the "LocationFactory locationf = new LocationFactory();" line and throwing an exception-
"java.lang.NullPointerException"
Main
Code:
package com.example.testapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private static final Context Context = null;
protected static final String TAG = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void mainButton(View view) throws IOException {
try {
LocationFactory locationf = new LocationFactory();
Toast.makeText(this, locationf.getAddress(),Toast.LENGTH_LONG).show();
} catch (Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Class
Code:
package com.example.testapp;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import java.io.IOException;
import java.util.Locale;
import java.util.List;
public class LocationFactory
{
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory()
{
}
public String getAddress() throws IOException
{
String ReturnAddress = "";
String Address = "", City = "", Country = "";
List<Address> addresses = null;
if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
// Use GPS Radio Location
Location GPSlocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Latitude = GPSlocation.getLatitude();
Longitude = GPSlocation.getLongitude();
}
else
{
// Use Cell Tower Location
Location NETlocation = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Latitude = NETlocation.getLatitude();
Longitude = NETlocation.getLongitude();
}
if(Latitude > 0 && Longitude > 0)
{
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
if(!addresses.isEmpty())
{
Address = addresses.get(0).getAddressLine(0);
City = addresses.get(0).getAddressLine(1);
Country = addresses.get(0).getAddressLine(2);
}
}
ReturnAddress = Address + " " + City + " " + Country;
return ReturnAddress;
}
}
I don't see anywhere in your code where you are calling the mainButton(View view) method. In the Android lifecycle, the onCreate method is the equivalent of a normal Java program's main() method, which means that code execution begins with the first line of onCreate(). Not knowing what you're trying to do, a good start would be to call your mainButton() method AFTER setContentView() in onCreate().
Side note: your mainButton() method has a View parameter that is never used. Is there a reason for that?
Android activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
e.g
Code:
Button button = (Button) findViewById(R.id.[B]button[/B]) // replace latter button with actual id defined in main xml.
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("[B]com.example.packagename.CLASSNAME[/B]")); // this should be your own package name.
}
});
Also define this in android manifest under the <application> and </application>
Code:
<activity
android:name=".[B]CLASSNAME[/B]"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="[B]com.example.packagename.CLASSNAME[/B]" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Change the values of BOLD text according to your own values.
I tried to help you as far as I understood your question. Please let me know if you face any problem I would be more than happy to help you. Rest I am also in the learning phase so you can always PM me if you face any problem.
Hit thanks if I have helped you in any way.
coolbud012 said:
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
Click to expand...
Click to collapse
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
jpepin said:
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
Click to expand...
Click to collapse
Oops yeah right read that now...I thought he want to start an activity... Anyways tried to delete my reply but not getting an option to delete.
There are many flaws in his code. And the other thing is if its his first app and if he has low level of programming experience then according to me it would be a next to impossible app for him, as per his code and what he is trying to implement.
I think he should rather start up with small apps, understand things and then move on to complex apps.
P.S - its just my opinion
Click to expand...
Click to collapse
Agreed that he should start small...which is exactly why your suggestion for creating and handling Intents makes no sense. Before that, he should first understand the activity lifecycle. Until then, he can just stick to trivial single-activity apps to gain experience.
OP: This code should be placed in the onCreate method:
Code:
Button button = (Button) findViewById(R.id.your_button_ID_here)
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
mainButton(); // get rid of the View parameter in this method...it's not needed
}
});
This will cause a new instance of your LocationFactory to be created, and will also cause your Toast message to be displayed.
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
osmorgan said:
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
Click to expand...
Click to collapse
I also believe in the same, I also keep on doing experiments and testing things out.
What I would suggest is that start with a small app and understand the insights on how android works and all...
Thanks
Potential Solution
Alright, I think I've found your problem. Have a look at where you define your variables in your LocationManager class:
Code:
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
This is your problem:
Code:
Context Context = null;
If your context is null, and you use it to create a geocoder and call Context.getSystemService, you'll hit a null pointer. You're trying to access an object (the Context) that doesn't even exist
I'd recommend you pass the context in the LocationManager constructor and then instantiate your objects there. That's standard java procedure.
Code:
private Context mContext = null;
Geocoder geocoder = null;
LocationManager manager = null;
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory(Context context)
{
this.mContext = context;
this.geocoder = new Geocoder(context, Locale.getDefault());
this.manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
}
I also renamed Context to mContext - it's generally a good idea to keep the instance's name separate from the class name.
Try that - it should work. Please feel free to ask any more questions - this is how I learned, and I think it's the best way!

[Q]How to hand different Strings to dynamically created Fragments using ViewPager?

I can't seem to find a way to give different text to a dynamically created fragment for my pageviewer-supoorted application. I've came to a point of my codding where I got stuck. For my application I want to have 400-500 dynamically created fragments, where you can horizontally slide thru them and every content of the fragment to be the same (repeating the same fragment) and the only different thing to be the text on them.
Here's where I got stuck at my codding :
Code:
package com.example.testarearg;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
[user=439709]@override[/user]
public void onPageSelected(int position) {
}
});
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
[user=439709]@override[/user]
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
[user=439709]@override[/user]
public int getCount() {
// Show 3 total pages.
return 3;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/ private String mText; // display this text in your fragment
public static Fragment getInstance(String text) {
Fragment f = new Fragment();
Bundle args = new Bundle();
args.putString("text", text);
f.setArguments(args);
return f;
}
public void onCreate(Bundle state) {
super.onCreate(state);
setmText(getArguments().getString("text"));
// rest of your code
}
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
}
}
featyhu James
I wanted to first off introduce you to a widget called Viewpagerindicator by Jake Wharton if you haven't already come across it. It is a very popular viewpager extension.
You can download a demo from google play (this I recommend), search for "viewpager indicator"
To give you a back of the envelope solution, I would suggest you try creating at least 2 fragments and then page between them updating the text in on resume(). Do these fragment words need to be remembered? For instance if the user swipes back and forth are the same words meant to reappear?
hgpb said:
I wanted to first off introduce you to a widget called Viewpagerindicator by Jake Wharton if you haven't already come across it. It is a very popular viewpager extension.
You can download a demo from google play (this I recommend), search for "viewpager indicator"
To give you a back of the envelope solution, I would suggest you try creating at least 2 fragments and then page between them updating the text in on resume(). Do these fragment words need to be remembered? For instance if the user swipes back and forth are the same words meant to reappear?
Click to expand...
Click to collapse
Ohh, I was not aware about this extension. I'm gonna try it and see what I get out of it. Yes, the words need to be remembered. Thank you for the heads-up about 'viewpager indicator' .
Feciuc said:
Ohh, I was not aware about this extension. I'm gonna try it and see what I get out of it. Yes, the words need to be remembered. Thank you for the heads-up about 'viewpager indicator' .
Click to expand...
Click to collapse
When you get the Viewpager indicator setup with a couple of fragments initialised you need to track the words you create. You could use a SparseArray/ArrayList or such like to track the position of frag and word perhaps. Then you should be able to move through the array depending on the swipe you receive. The swipe would move you up or down the array giving you access.
Code:
SparseArray<String> sa = new SparseArray<String>();
As I said this is a back of the envelope solution but it may just do the trick.

[Q] Code not bringing desired results

good day,
i'm trying to create an app that will create options in a listview on an an activity based on the option a user selects in the previous activity
below is the code i came up with but it doesn't work.
please what am i doing wrong?
thanks in advance
package com.inveniotech.moneyventure;
/**
* Created by BolorunduroWB on 9/3/13.
*/
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import java.util.*;
import android.content.Intent;
public class menu_options extends Activity {
SimpleAdapter simpleAdpt;
Intent intent = getIntent();
public String message = intent.getStringExtra(football.EXTRA_MESSAGE);
String[] menuList;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuoptionsview);
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, optionList, android.R.layout.simple_list_item_1, new String[] {"options"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(menu_options.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// The data to show
List<Map<String, String>> optionList = new ArrayList<Map<String,String>>();
private void initList() {
// We populate the planets
if (message.equals("5")){
menuList = new String[]{"News", "Fixtures","Results","Standings"," "};
}
else if (message.equals("6")){
menuList = new String[]{"News", "Tables"," "," "," "};
}
else if (message.equals("7")){
menuList = new String[]{"Done Deals", "Rumours","Latest News","Live","Transfer Centre"};
}
else {
menuList = new String[] {"News","Teams","Fixtures","Results","Table"};
}
optionList.add(createOptions("options", menuList[0]));
optionList.add(createOptions("options", menuList[1]));
optionList.add(createOptions("options", menuList[2]));
optionList.add(createOptions("options", menuList[3]));
optionList.add(createOptions("options", menuList[4]));
}
private HashMap<String, String> createOptions(String key, String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put(key, name);
return options;
}
}
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
SimplicityApks said:
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
Click to expand...
Click to collapse
Thank you. Wanted to post the link, too. :laugh:

Data That is Fetched From The Web Server Are Appending

I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.

[Q] Open another screen on button click

Hello, I'm extremely new to both android application developing, and this forum.
I am trying to open another screen ( activity ) when a button ( readyButton ) on the splash screen is pressed. I've tried at least ten different times with different tutorials to no avail, this is my current code which didn't work, and instead forces the app to crash.
Code:
public class MainActivity extends Activity {
// Called when the activity is first created.
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
OnClickListener listener = new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent("SecondActivity");
startActivity(intent);
}
};
Button btn = (Button) findViewById(R.id.readybutton);
btn.setOnClickListener(listener);
}
}
Please help.
The button's name is 'readybutton'
the second activity name is 'SecondActivity'
also, where am I supposed to put this code into the java class? Here is how it is currently set up:
Code:
package com.unchat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
// Default Items
public class FirstActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
/** New button code start */
public class MainActivity extends Activity {
// Called when the activity is first created.
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
OnClickListener listener = new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent("SecondActivity");
startActivity(intent);
}
};
Button btn = (Button) findViewById(R.id.readybutton);
btn.setOnClickListener(listener);
}
}
/** new button code end */
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
// End of Default Items
incorrectly announces intent
Try like this.
Code:
Intent intent = new Intent(this, SecondActivity.class) ;
startActivity(intent);
and check whether your Listener
1. you need to use the full name of your activity, including the package name.
2. you need to declare the activity in your AndroidManifest.xml file before calling it.
rhmsoft said:
2. you need to declare the activity in your AndroidManifest.xml file before calling it.
Click to expand...
Click to collapse
Unless he want's to run an activity that's not his, like opening the contact list, but I think you're right in assuming he's looking to launch a second one of his own activities.
bornander said:
Unless he want's to run an activity that's not his, like opening the contact list, but I think you're right in assuming he's looking to launch a second one of his own activities.
Click to expand...
Click to collapse
I thought you had to declare all your activities in the manifest?
Log
Post the error log please

Categories

Resources