not getting ListView Item in Android - android

When I can click on ListView item with new Activity, ListView is not opening. I'm not understand why it is not open.
public class ActivityListOfSearchIDProfiles extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ListView mListOfProfiles;
private ArrayList<Registration> mArrayListOfRegistrations;
private SearchByIDAdapter mSearchByIDAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_activitylistview);
mListOfProfiles = (ListView) findViewById(R.id.listOFSerachProfiles);
Toolbar toolbar= (Toolbar) findViewById(R.id.toolbarCommon);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));
toolbar.setNavigationIcon(R.drawable.ic_action_navigation_arrow_back_inverted);
getSupportActionBar().setIcon(R.mipmap.ic_action_account_circle);
getSupportActionBar().setTitle("Profile");
mArrayListOfRegistrations = new ArrayList<Registration>();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
final Intent intent = getIntent();
String hjID = intent.getStringExtra("hjID");
if (isConnected())
{
Toast.makeText(ActivityListOfSearchIDProfiles.this, "Profile:"+hjID, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(ActivityListOfSearchIDProfiles.this, "No Internet Connection Available", Toast.LENGTH_SHORT).show();
}
new SearchByIDGETThread(ActivityListOfSearchIDProfiles.this, new HandlerRegisterSearchProfile(), hjID).execute();
System.out.println("With Thread");
mListOfProfiles.setOnItemClickListener(this);
}
public boolean isConnected() {
ConnectivityManager conManager = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("Open Listview Item");
Registration mRegistration = mArrayListOfRegistrations.get(i);
System.out.println("In listView Item");
Intent intent = new Intent(ActivityListOfSearchIDProfiles.this, ActivityShowProfileDetails.class);
intent.putExtra("fname", mRegistration.getFname());
intent.putExtra("lname", mRegistration.getLname());
intent.putExtra("hjID", mRegistration.getData());
intent.putExtra("gender", mRegistration.getGender());
intent.putExtra("dob", mRegistration.getDob());
intent.putExtra("tob", mRegistration.getTob());
intent.putExtra("age", mRegistration.getAge());
intent.putExtra("height", mRegistration.getHeight());
intent.putExtra("complexion", mRegistration.getComplexion());
intent.putExtra("blood_group", mRegistration.getBlood_group());
intent.putExtra("spect", mRegistration.getSpect());
intent.putExtra("ph_dis", mRegistration.getPh_dis());
intent.putExtra("nri", mRegistration.getNri());
intent.putExtra("caste", mRegistration.getCast());
intent.putExtra("rashi", mRegistration.getRashi());
intent.putExtra("hob", mRegistration.getHob());
intent.putExtra("city", mRegistration.getCity());
intent.putExtra("state", mRegistration.getState());
intent.putExtra("edu", mRegistration.getEdu());
intent.putExtra("occupation", mRegistration.getOcc());
intent.putExtra("place_occupation", mRegistration.getPlace_occ());
intent.putExtra("income", mRegistration.getIncome());
intent.putExtra("cat", mRegistration.getCat());
intent.putExtra("father", mRegistration.getFather());
intent.putExtra("mother", mRegistration.getMother());
intent.putExtra("father_name", mRegistration.getFather_name());
intent.putExtra("mother_name", mRegistration.getMother_name());
intent.putExtra("mama_name", mRegistration.getMama_name());
intent.putExtra("mama_place", mRegistration.getMama_place());
intent.putExtra("rel_name", mRegistration.getRel_name());
intent.putExtra("native_place", mRegistration.getNative_place());
intent.putExtra("no_brothers", mRegistration.getNo_brothers());
intent.putExtra("no_mar_bro", mRegistration.getNo_sisters());
intent.putExtra("no_sisters", mRegistration.getNo_mar_bro());
intent.putExtra("no_mar_sis", mRegistration.getNo_mar_sis());
intent.putExtra("parent_occ", mRegistration.getParent_occ());
intent.putExtra("family_property", mRegistration.getFamily_prop());
intent.putExtra("expect", mRegistration.getExpectations());
intent.putExtra("photo", mRegistration.getPhoto());
intent.putExtra("photo2", mRegistration.getPhoto2());
System.out.println("In ITem Search");
System.out.println(intent.putExtra("family_property", mRegistration.getFamily_prop()));
startActivity(intent);
}
}

You should setAdapter such as;
mListOfProfiles.setAdapter(
new CustomProfileAdapter(this,mArrayListOfRegistrations));
Without setting adapter you cannot inflate you list.

If your data set on the ListView properly then please use the switch case in the Onitemclick function of the ListView. Like below code:-
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (adapterView.getId())
{
case R.id.listOFSerachProfiles:
Intent intent = new Intent(ActivityListOfSearchIDProfiles.this, ActivityShowProfileDetails.class);
intent.putExtra("fname", mRegistration.getFname());
intent.putExtra("lname", mRegistration.getLname());
intent.putExtra("hjID", mRegistration.getData());
intent.putExtra("gender", mRegistration.getGender());
intent.putExtra("dob", mRegistration.getDob());
intent.putExtra("tob", mRegistration.getTob());
intent.putExtra("age", mRegistration.getAge());
intent.putExtra("height", mRegistration.getHeight());
intent.putExtra("complexion", mRegistration.getComplexion());
intent.putExtra("blood_group", mRegistration.getBlood_group());
intent.putExtra("spect", mRegistration.getSpect());
intent.putExtra("ph_dis", mRegistration.getPh_dis());
intent.putExtra("nri", mRegistration.getNri());
intent.putExtra("caste", mRegistration.getCast());
intent.putExtra("rashi", mRegistration.getRashi());
intent.putExtra("hob", mRegistration.getHob());
intent.putExtra("city", mRegistration.getCity());
intent.putExtra("state", mRegistration.getState());
intent.putExtra("edu", mRegistration.getEdu());
intent.putExtra("occupation", mRegistration.getOcc());
intent.putExtra("place_occupation", mRegistration.getPlace_occ());
intent.putExtra("income", mRegistration.getIncome());
intent.putExtra("cat", mRegistration.getCat());
intent.putExtra("father", mRegistration.getFather());
intent.putExtra("mother", mRegistration.getMother());
intent.putExtra("father_name", mRegistration.getFather_name());
intent.putExtra("mother_name", mRegistration.getMother_name());
intent.putExtra("mama_name", mRegistration.getMama_name());
intent.putExtra("mama_place", mRegistration.getMama_place());
intent.putExtra("rel_name", mRegistration.getRel_name());
intent.putExtra("native_place", mRegistration.getNative_place());
intent.putExtra("no_brothers", mRegistration.getNo_brothers());
intent.putExtra("no_mar_bro", mRegistration.getNo_sisters());
intent.putExtra("no_sisters", mRegistration.getNo_mar_bro());
intent.putExtra("no_mar_sis", mRegistration.getNo_mar_sis());
intent.putExtra("parent_occ", mRegistration.getParent_occ());
intent.putExtra("family_property", mRegistration.getFamily_prop());
intent.putExtra("expect", mRegistration.getExpectations());
intent.putExtra("photo", mRegistration.getPhoto());
intent.putExtra("photo2", mRegistration.getPhoto2());
System.out.println("In ITem Search");
System.out.println(intent.putExtra("family_property", mRegistration.getFamily_prop()));
startActivity(intent);
break;
}
}
Hope this code help you :-)

Its better to extends ListActivity to ActivityListOfSearchIDProfiles. Then create ArrayAdapter or your custom listAdapter and add your data list to adapter. Then set Adapter to your listview.

Related

How to get all items in listview?

I've implemented one code to scan the wifi networks and display them in the list. After selecting one of the wifi networks from the list, I have added selected network in another activity in another ListView.
Now when I restart the app and again scan the wifi networks, I'm getting that network also which I have selected before and added in the list.
(In one activity I'm searching available wifi networks and in other activity I have added list of that selected networks)
So my question is that, how to hide that network which I have already added in list view?
This is my first activity, here i have displayed the added device in listview
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btnAdd);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this,Second.class);
startActivity(intent);
finish();
}
});
try
{
listView = (ListView)findViewById(R.id.device_list);
devicesNameEspNum = new ArrayList<>();
devices = new Devices();
devicesList = alldeviceList();
for(int i=0; i<devicesList.size(); i++)
{
devices = devicesList.get(i);
devicesNameEspNum.add(devices);
}
devicesAdapter = new DevicesAdapter(MainActivity.this,devicesNameEspNum);
listView.setAdapter(devicesAdapter);
devicesAdapter.notifyDataSetChanged();
}
catch (NullPointerException ex)
{
ex.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id)
{
Intent intent = new Intent(MainActivity.this,Fourth.class);
String selected = ((TextView) view.findViewById(R.id.deviceNamList)).getText().toString();
intent.putExtra("DEVICE_ID",selected);
startActivity(intent);
finish();
}
});
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
{
Toast.makeText(this, "****", Toast.LENGTH_SHORT).show();
}
}
public static List<Devices> alldeviceList()
{
return new Select().from(Devices.class).execute();
}
This is my second activity to scan nearby wifi networks
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
list=getListView();
mainWifiObj = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if(mainWifiObj != null)
{
mainWifiObj.setWifiEnabled(true);
}
wifiReciever = new WifiScanReceiver();
mainWifiObj.startScan();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1000);
}
else
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
// listening to single list item on click
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String ssid = ((TextView) view).getText().toString();
connectToWifi(ssid);
Toast.makeText(Second.this,"Wifi SSID : "+ssid,Toast.LENGTH_SHORT).show();
}
});
}
This is the class:
class WifiScanReceiver extends BroadcastReceiver
{
#SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent)
{
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
System.out.println("Wifi Scan Result: "+wifiScanList);
wifis = new String[wifiScanList.size()];
for(int i = 0; i < wifiScanList.size(); i++)
{
wifis[i] = ((wifiScanList.get(i)).toString());
}
String filtered[] = new String[wifiScanList.size()];
int counter = 0;
for (String eachWifi : wifis) {
String[] temp = eachWifi.split(",");
filtered[counter] = temp[0].substring(5).trim();//+"\n" + temp[2].substring(12).trim()+"\n" +temp[3].substring(6).trim();//0->SSID, 2->Key Management 3-> Strength
counter++;
}
System.out.println("Filtered :"+filtered);
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,R.id.label, filtered));
}
}
What's about this ?
displayed.addAll(allItems.filter { !it.equals("abc") })

Setting On Click Listener For A Dynamic ListView

thanks for always being available...
I have been able to populate my ListView with information i have in the database.
Now, I want setOnClickListener for the items to go to different pages. Currently, I am using a "switch(position)" construct, but it doesn't function appropriately since I can't hard code how many items would be on the ListView.
Please, kindly help me out on this one.
public class SurveyActivity extends AppCompatActivity {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db;
DatabaseHelper helper = new DatabaseHelper(this);
String listItem = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_survey);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Add new survey", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
PopupMenu pop = new PopupMenu(SurveyActivity.this, fab);
pop.getMenuInflater().inflate(R.menu.addsurvey_menu, pop.getMenu());
pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), "Your choice is to " + item.getTitle().toString().toUpperCase() + " a survey form", Toast.LENGTH_LONG).show();
switch (item.getItemId()) {
case R.id.c:
//Takes admin to page where survey is created
Intent i = new Intent(getApplicationContext(), CreateSurvey.class);
startActivity(i);
case R.id.d:
//gets ready created XML forms from server
case R.id.r:
//refreshes and updates survey list from db
}
return true;
}
});
pop.show();
}
});
db = helper.getReadableDatabase();
//Cursor crs = db.rawQuery("SELECT * FROM tbNames", null);
Cursor crs=db.query("tbNames",new String[]{ "names"},null,null,null,null,null);
if(crs.moveToFirst()){
do {
listItem =crs.getString(0);
list.add(listItem);
}while(crs.moveToNext());
}
ListView surveyList = (ListView) findViewById(R.id.surveylist);
ArrayAdapter<String> aAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
surveyList.setAdapter(aAdapter);
registerForContextMenu(surveyList);
surveyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent i = new Intent(getApplicationContext(), hivActivity.class);
startActivity(i);
break;
case 1:
Intent intent = new Intent(SurveyActivity.this, CreatedSurveyActivity.class);
startActivity(intent);
}
}
});
}
}
My app would allow users create multiple surveys which would show up in the LIstView.
The problem is how to set Listeners for the items dynamically too.
You can try this code
surveyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i = new Intent(getApplicationContext(), hivActivity.class);
startActivity(i);
} else {
Intent intent = new Intent(SurveyActivity.this, CreatedSurveyActivity.class);
startActivity(intent);
}
}
});
First item will call hivActivity and all other items will call CreatedSurveyActivity. If you need to pass something to the CreatedSurveyActivity put it into the intent, like this intent.putExtra("position" position);
Maybe use setOnItemClickListener()
Posting your code would be helpful, however an approach that can often help in similar situations is:
Set a tag on each view, as you generate it. For example, the item ID, or just an incrementer.
The onClickListener will receive the view as a parameter. The tag can then be retrieved from it.
This tag can then be matched to page names, page URLs, or any other information you're trying to load.

how to Refresh Database and then put the new data in a simplecursoradapter in android?

Mainactivity where I check the clicking of the refresh button
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Will close the drawer if the home button is pressed
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.search:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
return false;
} else {
// Legacy search mode for Eclair
onSearchRequested();
return true;
}
case R.id.refresh:
startDownloadSchedule();
// TODO: resolve this
Toast.makeText(getApplication(), "Updating database", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private void startDownloadSchedule() {
progressBar.clearAnimation();
progressBar.setIndeterminate(true);
progressBar.setProgress(100);
progressBar.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.fade_out));
progressBar.setMax(100);
progressBar.setVisibility(View.VISIBLE);
//JsonToDatabase gets data from google sheets in json format and then saves it in a database
JsonToDatabase dataDownload = new JsonToDatabase(getApplicationContext());
dataDownload.setOnJsonToDatabaseCallback(new JsonToDatabase.JsonToDatabaseCallback() {
#Override
public void onDataLoaded() {
Toast.makeText(getApplication(), "done updating", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
TracksListFragment tracksListFragment1 = new TracksListFragment();
tracksListFragment1.onCreate(new Bundle());
}
});
dataDownload.startDataDownload();
}
TracklistFragment.class ( this is the activity whose data I want to refresh)
public class TracksListFragment extends SmoothListFragment {
//public String[] columns;
//public int[] to;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
displaydata();
}
public void displaydata() {
String[] columns = new String[]{DatabaseHelper.TABLE_COLUMN_NAME, DatabaseHelper.TABLE_COLOUMN_INFORMATION};
// THE XML DEFINED VIEWS WHICH THE DATA WILL BE BOUND TO
int[] to = new int[]{R.id.textView_track_title, R.id.textView_track_information};
DatabaseManager db = DatabaseManager.getInstance();
if (getActivity() != null) {
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(
getActivity(), R.layout.list_tracks, db.getTracks(), columns, to, CursorAdapter.NO_SELECTION);
setListAdapter(mAdapter);
Toast.makeText(getActivity(),"display data",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String text = ((TextView) v.findViewById(R.id.textView_track_title)).getText().toString();
Intent intent = new Intent(getActivity(), TrackActivity.class);
intent.putExtra("TRACK", text);
startActivity(intent);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setEmptyText("No data present");
}
}
I am just stuck at how to display the new refreshed data. I have checked that the data gets downloaded. Any help would be appreciated. Thanks in advance.
Version the database. Add SharedPreferences for the database and increment it each time new data is added, then Call updateDb from Open helper.

Android Listview duplicate on back button pressed

In my activity I have the ActionBar with an action button new(that adds a new item on the ListView) and a ListView. The problem is that after I add some items and then I press back button, the ListView returns to the previous ListView with an item less and after one/two seconds shows the complete listviews with all items. I think the problem is something like the listview duplicate one over the previous.
Here is my activity:
public class ListNotesActivity extends ActionBarActivity {
private ArrayList<Note> notes;
private Database db;
private long lastBackPressTime = 0;
private Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_notes);
notes = new ArrayList<Note>();
db = new Database(this);
getNotes();
ActionBar ab = getSupportActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#E89619")));
ab.setTitle("Your notes");
}
#Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(this, "Press back again to exit", 4000);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null)
toast.cancel();
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list_notes, menu);
return true;
}
#Override
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();
switch (id) {
case R.id.action_new:
//In this activity that I start, It will save the new Item in the database and then it starts this activity again that will read the database with the new item.
Intent i = new Intent(ListNotesActivity.this,
NotesActivity.class);
i.putExtra(NEWNOTE, true);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void getNotes() {
final Toast t = Toast.makeText(this, R.string.retrieving_notes,
Toast.LENGTH_SHORT);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
notes = db.getNotes();
Log.v("MyActivity",
"Read notes on the database: " + notes.size());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
populateList();
}
};
t.show();
task.execute();
}
public void populateList() {
NoteAdapter adapter = new NoteAdapter(this, notes);
final ListView listView = (ListView) findViewById(R.id.list_notes);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView, View childView,
int position, long id) {
Note note = notes.get(position);
Log.v("MyActivity",
"LISTNOTESACTIVITY: note's title: " + note.getTitle());
Bundle b = new Bundle();
b.putSerializable(EDITNOTE2, note);
Intent i = new Intent(ListNotesActivity.this,
NotesActivity.class);
i.putExtra(EDITNOTE, true);
i.putExtra(EDITNOTE2, b);
startActivity(i);
}
});
}
I hope I made me clear.
Thanks in advance!
try to remove this line from your getNotes() Method
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Your list view is update only when activity is created ( not when is resumed ) , because you call getNotes() only in onCreate(). In method getNotes(), you make asynch operation.
If you want to update immediately your list view, should take strategy like this.
Start new activity for result, and in second activity after create new item pass data back to the first.
In NotesActivity after create new item add and call this method
private void saveItem(Note note)
{
Intent data = new Intent();
// set all data from your item
data.putExtra(name, value);
setResult(RESULT_OK, data);
}
In ListNotesActivity you should start new activity by using this call
startActivityForResult(intent, 1);
And override this method
#Override
protected void onResume()
{
super.onResume();
// This call on your list view to update rows
listViewAdapter.notifyDataSetChanged();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK && requestCode == 1)
{
Note note = new Note();
// Extract your data from intent
data.getExtra(name); // and set to note variable
// add your new item to list view adapter
listViewAdapter.addNewItem(note);
}
}
I hope this will help you.

Android OnItemCLickListener not working in listview

I am new to android programming.I am developing an app in which when user clicks on any ListView item it should go to Google maps app and display pin for that address on the map. But when I click on any item nothing happens.
Following is my display Activity.
public class DisplayActivity extends Activity implements OnItemClickListener{
ListView listView;
private String tag_name;
public List<NameAddress> nameAddressList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
listView = (ListView) findViewById(R.id.list);
Intent intent = getIntent();
if(intent!= null)
{
tag_name = intent.getStringExtra("DashItemName");
setTitle("List of " +tag_name+ " addresses");
}
nameAddressList = null;
try {
XMLDOMParserHandler parser = new XMLDOMParserHandler(tag_name);
nameAddressList = parser.parseXML(getAssets().open("data.xml"));
ArrayAdapter<NameAddress> adapter =
new ArrayAdapter<NameAddress>(this,R.layout.list_item, nameAddressList);
listView.setAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// Build the intent
String address = nameAddressList.get(position).toString();
address = "geo:0,0?q=" + address;
String query = URLEncoder.encode(address, "utf-8");
Uri location = Uri.parse(query);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location;
mapIntent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(mapIntent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it's safe
if (isIntentSafe) {
startActivity(mapIntent);
}
else
{
Toast.makeText(this, "Please install google maps app", Toast.LENGTH_LONG).show();
}
}
}
Please suggest me a way to solve this problem.
Please suggest me a way to solve this problem.
It doesn't work for you because you forgot to assign listener to ListView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
...
}
Now, it will work for you.
You forgot to set the listener to your ListView.
Just after the creation of listView you should add:
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//your onItemClick code
}
}

Categories

Resources